From a8ae14e94f10e86ed8105ab6c8d0dabf79f40218 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Tue, 9 Feb 2016 01:17:05 +0100 Subject: [PATCH 0001/1265] Introducing a will-enter-full-screen event that's cancellable --- atom/browser/api/atom_api_window.cc | 4 ++++ atom/browser/api/atom_api_window.h | 1 + atom/browser/native_window.cc | 7 +++++++ atom/browser/native_window.h | 3 +++ atom/browser/native_window_mac.mm | 3 +++ atom/browser/native_window_observer.h | 1 + atom/browser/native_window_views.cc | 25 +++++++++++++++++-------- 7 files changed, 36 insertions(+), 8 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index bcf6ccc5a33..3a3b3c6efc8 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -219,6 +219,10 @@ void Window::OnWindowMoved() { Emit("moved"); } +void Window::OnWindowWillEnterFullScreen(bool* prevent_default) { + *prevent_default = Emit("will-enter-full-screen"); +} + void Window::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 641124f4dfd..2d1e6d71ec3 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -67,6 +67,7 @@ class Window : public mate::TrackableObject, void OnWindowMoved() override; void OnWindowScrollTouchBegin() override; void OnWindowScrollTouchEnd() override; + void OnWindowWillEnterFullScreen(bool* prevent_default) override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index c25534f7f18..a09705fbd96 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -445,6 +445,13 @@ void NativeWindow::NotifyWindowMoved() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowMoved()); } +bool NativeWindow::RequestEnterFullScreen() { + bool prevent_default = false; + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, + OnWindowWillEnterFullScreen(&prevent_default)); + return prevent_default; +} + void NativeWindow::NotifyWindowEnterFullScreen() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowEnterFullScreen()); diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 09fae6c6bcf..4cc04e790e1 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -197,6 +197,9 @@ class NativeWindow : public base::SupportsUserData, // Requests the WebContents to close, can be cancelled by the page. virtual void RequestToClosePage(); + // Request the WebContents to go fullscreen, can be cancelled by the page. + virtual bool RequestEnterFullScreen(); + // Methods called by the WebContents. virtual void CloseContents(content::WebContents* source); virtual void RendererUnresponsive(content::WebContents* source); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 7967a177173..aa0dde4c486 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -602,6 +602,9 @@ void NativeWindowMac::SetFullScreen(bool fullscreen) { if (fullscreen == IsFullscreen()) return; + if (fullscreen && shell_->RequestEnterFullScreen()) + return; + if (!base::mac::IsOSLionOrLater()) { LOG(ERROR) << "Fullscreen mode is only supported above Lion"; return; diff --git a/atom/browser/native_window_observer.h b/atom/browser/native_window_observer.h index 4af181085a0..1f66bac5b63 100644 --- a/atom/browser/native_window_observer.h +++ b/atom/browser/native_window_observer.h @@ -52,6 +52,7 @@ class NativeWindowObserver { virtual void OnWindowMoved() {} virtual void OnWindowScrollTouchBegin() {} virtual void OnWindowScrollTouchEnd() {} + virtual void OnWindowWillEnterFullScreen(bool* prevent_default) {} virtual void OnWindowEnterFullScreen() {} virtual void OnWindowLeaveFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {} diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 44df87da9fb..101c57515af 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -347,24 +347,33 @@ bool NativeWindowViews::IsMinimized() { } void NativeWindowViews::SetFullScreen(bool fullscreen) { + bool prevent_default = false; + if (fullscreen) + prevent_default = RequestEnterFullScreen(); + #if defined(OS_WIN) // There is no native fullscreen state on Windows. if (fullscreen) { - last_window_state_ = ui::SHOW_STATE_FULLSCREEN; - NotifyWindowEnterFullScreen(); + if (!prevent_default) { + last_window_state_ = ui::SHOW_STATE_FULLSCREEN; + NotifyWindowEnterFullScreen(); + } } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // We set the new value after notifying, so we can handle the size event // correctly. - window_->SetFullscreen(fullscreen); -#else - if (IsVisible()) + if (!prevent_default) window_->SetFullscreen(fullscreen); - else - window_->native_widget_private()->ShowWithWindowState( - ui::SHOW_STATE_FULLSCREEN); +#else + if (!(fullscreen && prevent_default)) { + if (IsVisible()) + window_->SetFullscreen(fullscreen); + else + window_->native_widget_private()->ShowWithWindowState( + ui::SHOW_STATE_FULLSCREEN); + } #endif } From 664f95a7b4e8bb5b2850fa19e841805b2ebb055a Mon Sep 17 00:00:00 2001 From: gellert Date: Tue, 9 Feb 2016 01:39:27 +0100 Subject: [PATCH 0002/1265] fixes osx request call --- atom/browser/native_window_mac.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index aa0dde4c486..f4f5a8c9789 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -602,7 +602,7 @@ void NativeWindowMac::SetFullScreen(bool fullscreen) { if (fullscreen == IsFullscreen()) return; - if (fullscreen && shell_->RequestEnterFullScreen()) + if (fullscreen && RequestEnterFullScreen()) return; if (!base::mac::IsOSLionOrLater()) { From 157a290e38ecd8416ffcaf558b1d734c276b8de4 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Tue, 9 Feb 2016 02:41:19 +0100 Subject: [PATCH 0003/1265] :memo: Adding documentation for will-enter-full-screen event --- docs/api/browser-window.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 7cf684a3953..827bb84db81 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -276,6 +276,11 @@ __Note__: On OS X this event is just an alias of `moved`. Emitted once when the window is moved to a new position. +### Event: 'will-enter-full-screen' + +Emitted when the window is about to enter full screen state. Calling `event.preventDefault()` +will cancel the state change. + ### Event: 'enter-full-screen' Emitted when the window enters full screen state. From 7bf17f2541680835fa60f9666becb6224061ae41 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Thu, 18 Feb 2016 01:15:00 +0100 Subject: [PATCH 0004/1265] Improved frame subscriber - now we only use framesubscription events as an event, and we copy from the backing store directly (instead of accessing it through a videoframe) --- atom/browser/api/atom_api_web_contents.cc | 2 +- atom/browser/api/frame_subscriber.cc | 63 ++++++++++++++--------- atom/browser/api/frame_subscriber.h | 10 ++-- 3 files changed, 46 insertions(+), 29 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index b04553e654b..6531874e6a9 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1065,7 +1065,7 @@ void WebContents::BeginFrameSubscription( const auto view = web_contents()->GetRenderWidgetHostView(); if (view) { FrameSubscriber* frame_subscriber = new FrameSubscriber( - isolate(), view->GetVisibleViewportSize(), callback); + isolate(), view, callback); scoped_ptr del_frame_subscriber( frame_subscriber->GetSubscriber()); view->BeginFrameSubscription(del_frame_subscriber.Pass()); diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index 7d973892405..60bf84c0eb9 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -8,6 +8,8 @@ #include "base/bind.h" #include "media/base/video_frame.h" #include "media/base/yuv_convert.h" +#include "content/public/browser/render_widget_host.h" +#include "ui/gfx/screen.h" namespace atom { @@ -16,10 +18,11 @@ namespace api { using Subscriber = FrameSubscriber::Subscriber; FrameSubscriber::FrameSubscriber(v8::Isolate* isolate, - const gfx::Size& size, + content::RenderWidgetHostView* view, const FrameCaptureCallback& callback) - : isolate_(isolate), size_(size), callback_(callback), pending_frames(0) { + : isolate_(isolate), callback_(callback), pending_frames(0), view_(view) { subscriber_ = new Subscriber(this); + size_ = view->GetVisibleViewportSize(); } Subscriber::Subscriber( @@ -36,14 +39,32 @@ bool Subscriber::ShouldCaptureFrame( base::TimeTicks present_time, scoped_refptr* storage, DeliverFrameCallback* callback) { - *storage = media::VideoFrame::CreateFrame( - media::PIXEL_FORMAT_YV12, - frame_subscriber_->size_, gfx::Rect(frame_subscriber_->size_), - frame_subscriber_->size_, base::TimeDelta()); - *callback = base::Bind(&FrameSubscriber::OnFrameDelivered, - base::Unretained(frame_subscriber_), *storage); + const auto view = frame_subscriber_->view_; + const auto host = view ? view->GetRenderWidgetHost() : nullptr; + if (!view || !host) { + return false; + } + + const gfx::Size view_size = view->GetViewBounds().size(); + + gfx::Size bitmap_size = view_size; + const gfx::NativeView native_view = view->GetNativeView(); + gfx::Screen* const screen = gfx::Screen::GetScreenFor(native_view); + const float scale = + screen->GetDisplayNearestWindow(native_view).device_scale_factor(); + if (scale > 1.0f) + bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); + + host->CopyFromBackingStore( + gfx::Rect(view_size), + bitmap_size, + base::Bind(&FrameSubscriber::OnFrameDelivered, + base::Unretained(frame_subscriber_), + frame_subscriber_->callback_), + kBGRA_8888_SkColorType); + frame_subscriber_->pending_frames++; - return true; + return false; } Subscriber* FrameSubscriber::GetSubscriber() { @@ -60,33 +81,25 @@ bool FrameSubscriber::RequestDestruct() { return deletable; } -void FrameSubscriber::OnFrameDelivered( - scoped_refptr frame, base::TimeTicks, bool result) { +void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback, + const SkBitmap& bitmap, content::ReadbackResponse response){ pending_frames--; - if (RequestDestruct() || subscriber_ == NULL || !result) + if (RequestDestruct() || subscriber_ == NULL || bitmap.computeSize64() == 0) return; v8::Locker locker(isolate_); v8::HandleScope handle_scope(isolate_); - gfx::Rect rect = frame->visible_rect(); - size_t rgb_arr_size = rect.width() * rect.height() * 4; + size_t rgb_arr_size = bitmap.width() * bitmap.height() * + bitmap.bytesPerPixel(); v8::MaybeLocal buffer = node::Buffer::New(isolate_, rgb_arr_size); if (buffer.IsEmpty()) return; - // Convert a frame of YUV to 32 bit ARGB. - media::ConvertYUVToRGB32(frame->data(media::VideoFrame::kYPlane), - frame->data(media::VideoFrame::kUPlane), - frame->data(media::VideoFrame::kVPlane), - reinterpret_cast( - node::Buffer::Data(buffer.ToLocalChecked())), - rect.width(), rect.height(), - frame->stride(media::VideoFrame::kYPlane), - frame->stride(media::VideoFrame::kUVPlane), - rect.width() * 4, - media::YV12); + bitmap.copyPixelsTo( + reinterpret_cast(node::Buffer::Data(buffer.ToLocalChecked())), + rgb_arr_size); callback_.Run(buffer.ToLocalChecked()); } diff --git a/atom/browser/api/frame_subscriber.h b/atom/browser/api/frame_subscriber.h index 6f6d66b6be8..745cf382adb 100644 --- a/atom/browser/api/frame_subscriber.h +++ b/atom/browser/api/frame_subscriber.h @@ -6,7 +6,10 @@ #define ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_ #include "base/callback.h" +#include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_widget_host_view_frame_subscriber.h" +#include "content/public/browser/readback_types.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/size.h" #include "v8/include/v8.h" @@ -35,19 +38,20 @@ class FrameSubscriber { }; FrameSubscriber(v8::Isolate* isolate, - const gfx::Size& size, + content::RenderWidgetHostView* view, const FrameCaptureCallback& callback); Subscriber* GetSubscriber(); private: - void OnFrameDelivered( - scoped_refptr frame, base::TimeTicks, bool); + void OnFrameDelivered(const FrameCaptureCallback& callback, + const SkBitmap& bitmap, content::ReadbackResponse response); bool RequestDestruct(); v8::Isolate* isolate_; gfx::Size size_; + content::RenderWidgetHostView* view_; FrameCaptureCallback callback_; Subscriber* subscriber_; int pending_frames; From 2610aa60e955cb34271d57c062e5962e58325652 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Thu, 18 Feb 2016 01:19:41 +0100 Subject: [PATCH 0005/1265] :art: lint fix --- atom/browser/api/frame_subscriber.cc | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index 60bf84c0eb9..ec3bcd05ab7 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -41,9 +41,8 @@ bool Subscriber::ShouldCaptureFrame( DeliverFrameCallback* callback) { const auto view = frame_subscriber_->view_; const auto host = view ? view->GetRenderWidgetHost() : nullptr; - if (!view || !host) { + if (!view || !host) return false; - } const gfx::Size view_size = view->GetViewBounds().size(); @@ -82,7 +81,7 @@ bool FrameSubscriber::RequestDestruct() { } void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback, - const SkBitmap& bitmap, content::ReadbackResponse response){ + const SkBitmap& bitmap, content::ReadbackResponse response) { pending_frames--; if (RequestDestruct() || subscriber_ == NULL || bitmap.computeSize64() == 0) From 39bb670719e4bb65cabc1bc3edad885b61945447 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Mon, 22 Feb 2016 10:23:56 +0100 Subject: [PATCH 0006/1265] Revert will-enter-full-screen event, matching osx fullscreen: false behaviour on windows instead --- atom/browser/api/atom_api_window.cc | 4 ---- atom/browser/api/atom_api_window.h | 1 - atom/browser/native_window.cc | 19 +++++++++---------- atom/browser/native_window.h | 3 --- atom/browser/native_window_mac.mm | 3 --- atom/browser/native_window_observer.h | 1 - atom/browser/native_window_views.cc | 21 +++++++++++---------- atom/browser/native_window_views.h | 1 + docs/api/browser-window.md | 13 ++++--------- 9 files changed, 25 insertions(+), 41 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 3a3b3c6efc8..bcf6ccc5a33 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -219,10 +219,6 @@ void Window::OnWindowMoved() { Emit("moved"); } -void Window::OnWindowWillEnterFullScreen(bool* prevent_default) { - *prevent_default = Emit("will-enter-full-screen"); -} - void Window::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 2d1e6d71ec3..641124f4dfd 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -67,7 +67,6 @@ class Window : public mate::TrackableObject, void OnWindowMoved() override; void OnWindowScrollTouchBegin() override; void OnWindowScrollTouchEnd() override; - void OnWindowWillEnterFullScreen(bool* prevent_default) override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index a09705fbd96..273bd948fe5 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -134,10 +134,16 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { SetAlwaysOnTop(true); } #if defined(OS_MACOSX) || defined(OS_WIN) - bool fullscreen; - if (options.Get(options::kFullscreen, &fullscreen) && fullscreen) { + // Disable fullscreen button when 'fullscreenable' is false or 'fullscreen' + // is specified to false. + bool fullscreenable = true; + options.Get(options::kFullScreenable, &fullscreenable); + bool fullscreen = false; + if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) + fullscreenable = false; + SetFullScreenable(fullscreenable); + if (fullscreen) SetFullScreen(true); - } #endif bool skip; if (options.Get(options::kSkipTaskbar, &skip) && skip) { @@ -445,13 +451,6 @@ void NativeWindow::NotifyWindowMoved() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowMoved()); } -bool NativeWindow::RequestEnterFullScreen() { - bool prevent_default = false; - FOR_EACH_OBSERVER(NativeWindowObserver, observers_, - OnWindowWillEnterFullScreen(&prevent_default)); - return prevent_default; -} - void NativeWindow::NotifyWindowEnterFullScreen() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowEnterFullScreen()); diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 4cc04e790e1..09fae6c6bcf 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -197,9 +197,6 @@ class NativeWindow : public base::SupportsUserData, // Requests the WebContents to close, can be cancelled by the page. virtual void RequestToClosePage(); - // Request the WebContents to go fullscreen, can be cancelled by the page. - virtual bool RequestEnterFullScreen(); - // Methods called by the WebContents. virtual void CloseContents(content::WebContents* source); virtual void RendererUnresponsive(content::WebContents* source); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index f4f5a8c9789..7967a177173 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -602,9 +602,6 @@ void NativeWindowMac::SetFullScreen(bool fullscreen) { if (fullscreen == IsFullscreen()) return; - if (fullscreen && RequestEnterFullScreen()) - return; - if (!base::mac::IsOSLionOrLater()) { LOG(ERROR) << "Fullscreen mode is only supported above Lion"; return; diff --git a/atom/browser/native_window_observer.h b/atom/browser/native_window_observer.h index 1f66bac5b63..4af181085a0 100644 --- a/atom/browser/native_window_observer.h +++ b/atom/browser/native_window_observer.h @@ -52,7 +52,6 @@ class NativeWindowObserver { virtual void OnWindowMoved() {} virtual void OnWindowScrollTouchBegin() {} virtual void OnWindowScrollTouchEnd() {} - virtual void OnWindowWillEnterFullScreen(bool* prevent_default) {} virtual void OnWindowEnterFullScreen() {} virtual void OnWindowLeaveFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {} diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 101c57515af..4b3b32024df 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -117,7 +117,8 @@ NativeWindowViews::NativeWindowViews( movable_(true), resizable_(true), maximizable_(true), - minimizable_(true) { + minimizable_(true), + fullscreenable_(true) { options.Get(options::kTitle, &title_); options.Get(options::kAutoHideMenuBar, &menu_bar_autohide_); @@ -347,14 +348,10 @@ bool NativeWindowViews::IsMinimized() { } void NativeWindowViews::SetFullScreen(bool fullscreen) { - bool prevent_default = false; - if (fullscreen) - prevent_default = RequestEnterFullScreen(); - #if defined(OS_WIN) // There is no native fullscreen state on Windows. if (fullscreen) { - if (!prevent_default) { + if (IsFullScreenable()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } @@ -364,10 +361,10 @@ void NativeWindowViews::SetFullScreen(bool fullscreen) { } // We set the new value after notifying, so we can handle the size event // correctly. - if (!prevent_default) + if (IsFullScreenable()) window_->SetFullscreen(fullscreen); #else - if (!(fullscreen && prevent_default)) { + if (!fullscreen || IsFullScreenable()) { if (IsVisible()) window_->SetFullscreen(fullscreen); else @@ -499,11 +496,15 @@ bool NativeWindowViews::IsMaximizable() { #endif } -void NativeWindowViews::SetFullScreenable(bool maximizable) { +void NativeWindowViews::SetFullScreenable(bool fullscreenable) { + #if defined(OS_WIN) + FlipWindowStyle(GetAcceleratedWidget(), false, WS_MAXIMIZEBOX); + #endif + fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { - return true; + return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { diff --git a/atom/browser/native_window_views.h b/atom/browser/native_window_views.h index 934f2aa00c9..862cd5458bb 100644 --- a/atom/browser/native_window_views.h +++ b/atom/browser/native_window_views.h @@ -212,6 +212,7 @@ class NativeWindowViews : public NativeWindow, bool resizable_; bool maximizable_; bool minimizable_; + bool fullscreenable_; std::string title_; gfx::Size widget_size_; diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 827bb84db81..96ce955db59 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -276,11 +276,6 @@ __Note__: On OS X this event is just an alias of `moved`. Emitted once when the window is moved to a new position. -### Event: 'will-enter-full-screen' - -Emitted when the window is about to enter full screen state. Calling `event.preventDefault()` -will cancel the state change. - ### Event: 'enter-full-screen' Emitted when the window enters full screen state. @@ -589,17 +584,17 @@ nothing. Returns whether the window can be manually maximized by user. On Linux always returns `true`. -### `win.setFullScreenable(fullscreenable)` _OS X_ +### `win.setFullScreenable(fullscreenable)` * `fullscreenable` Boolean Sets whether the maximize/zoom window button toggles fullscreen mode or -maximizes the window. On Windows and Linux does nothing. +maximizes the window. -### `win.isFullScreenable()` _OS X_ +### `win.isFullScreenable()` Returns whether the maximize/zoom window button toggles fullscreen mode or -maximizes the window. On Windows and Linux always returns `true`. +maximizes the window. ### `win.setClosable(closable)` _OS X_ _Windows_ From 367d12402ae6f3822b769da63fa5adeeaf8643b2 Mon Sep 17 00:00:00 2001 From: Robo Date: Wed, 17 Feb 2016 13:06:18 +0530 Subject: [PATCH 0007/1265] ipc: allow passing date instances --- .../v8_value_converter.cc | 35 +++++++++++++------ .../v8_value_converter.h | 4 --- spec/api-ipc-spec.js | 9 +++++ 3 files changed, 33 insertions(+), 15 deletions(-) diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index 7d3a1277cb8..f5d7217ae52 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -4,6 +4,7 @@ #include "atom/common/native_mate_converters/v8_value_converter.h" +#include #include #include #include @@ -20,6 +21,14 @@ namespace { const int kMaxRecursionDepth = 100; +const double kMsPerDay = 24 * 60 * 60 * 1000; + +int TimeInDay(double time_ms) { + if (time_ms < 0) time_ms -= (kMsPerDay -1); + int days = static_cast(time_ms / kMsPerDay); + return static_cast(time_ms - days * kMsPerDay); +} + } // namespace // The state of a call to FromV8Value. @@ -76,15 +85,10 @@ class V8ValueConverter::FromV8ValueState { }; V8ValueConverter::V8ValueConverter() - : date_allowed_(false), - reg_exp_allowed_(false), + : reg_exp_allowed_(false), function_allowed_(false), strip_null_from_objects_(false) {} -void V8ValueConverter::SetDateAllowed(bool val) { - date_allowed_ = val; -} - void V8ValueConverter::SetRegExpAllowed(bool val) { reg_exp_allowed_ = val; } @@ -243,12 +247,21 @@ base::Value* V8ValueConverter::FromV8ValueImpl( return NULL; if (val->IsDate()) { - if (!date_allowed_) - // JSON.stringify would convert this to a string, but an object is more - // consistent within this class. - return FromV8Object(val->ToObject(), state, isolate); v8::Date* date = v8::Date::Cast(*val); - return new base::FundamentalValue(date->NumberValue() / 1000.0); + double const time_ms = date->NumberValue(); + int const time_in_day_ms = TimeInDay(time_ms); + std::time_t time_s(time_ms / 1000.0); + char buf[128]; + std::tm* gm_time = std::gmtime(&time_s); + int year = gm_time->tm_year + 1900; + int month = gm_time->tm_mon + 1; + int ms = time_in_day_ms % 1000; + size_t length = snprintf(buf, sizeof buf, + "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + year, month, gm_time->tm_mday, + gm_time->tm_hour, gm_time->tm_min, + gm_time->tm_sec, ms); + return new base::StringValue(std::string(buf, length)); } if (val->IsRegExp()) { diff --git a/atom/common/native_mate_converters/v8_value_converter.h b/atom/common/native_mate_converters/v8_value_converter.h index 2b695b43747..95840c01ba7 100644 --- a/atom/common/native_mate_converters/v8_value_converter.h +++ b/atom/common/native_mate_converters/v8_value_converter.h @@ -22,7 +22,6 @@ class V8ValueConverter { public: V8ValueConverter(); - void SetDateAllowed(bool val); void SetRegExpAllowed(bool val); void SetFunctionAllowed(bool val); void SetStripNullFromObjects(bool val); @@ -58,9 +57,6 @@ class V8ValueConverter { FromV8ValueState* state, v8::Isolate* isolate) const; - // If true, we will convert Date JavaScript objects to doubles. - bool date_allowed_; - // If true, we will convert RegExp JavaScript objects to string. bool reg_exp_allowed_; diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 2c8bc28f156..92a8c001bf1 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -102,6 +102,15 @@ describe('ipc module', function() { }); ipcRenderer.send('message', obj); }); + + it('can send instance of Date', function(done) { + const currentDate = new Date(); + ipcRenderer.once('message', function(event, value) { + assert.equal(value, currentDate.toISOString()); + done(); + }); + ipcRenderer.send('message', currentDate); + }); }); describe('ipc.sendSync', function() { From 467870deb64f307be89578205a1e5cab7cc9ad6e Mon Sep 17 00:00:00 2001 From: Robo Date: Wed, 24 Feb 2016 16:25:41 +0530 Subject: [PATCH 0008/1265] use builtin method --- .../v8_value_converter.cc | 34 ++++++------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index f5d7217ae52..6a858f2749c 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -4,7 +4,6 @@ #include "atom/common/native_mate_converters/v8_value_converter.h" -#include #include #include #include @@ -21,14 +20,6 @@ namespace { const int kMaxRecursionDepth = 100; -const double kMsPerDay = 24 * 60 * 60 * 1000; - -int TimeInDay(double time_ms) { - if (time_ms < 0) time_ms -= (kMsPerDay -1); - int days = static_cast(time_ms / kMsPerDay); - return static_cast(time_ms - days * kMsPerDay); -} - } // namespace // The state of a call to FromV8Value. @@ -248,20 +239,17 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsDate()) { v8::Date* date = v8::Date::Cast(*val); - double const time_ms = date->NumberValue(); - int const time_in_day_ms = TimeInDay(time_ms); - std::time_t time_s(time_ms / 1000.0); - char buf[128]; - std::tm* gm_time = std::gmtime(&time_s); - int year = gm_time->tm_year + 1900; - int month = gm_time->tm_mon + 1; - int ms = time_in_day_ms % 1000; - size_t length = snprintf(buf, sizeof buf, - "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", - year, month, gm_time->tm_mday, - gm_time->tm_hour, gm_time->tm_min, - gm_time->tm_sec, ms); - return new base::StringValue(std::string(buf, length)); + v8::Local toISOString = + date->GetRealNamedPropertyInPrototypeChain( + v8::String::NewFromUtf8(isolate, "toISOString")); + if (toISOString->IsFunction()) { + v8::Local result = + toISOString.As()->Call(val, 0, nullptr); + if (!result.IsEmpty()) { + v8::String::Utf8Value utf8(result->ToString()); + return new base::StringValue(std::string(*utf8, utf8.length())); + } + } } if (val->IsRegExp()) { From a1a17b7ee8d0c1313ef9ac37c33ae979c26b62fd Mon Sep 17 00:00:00 2001 From: Robo Date: Thu, 25 Feb 2016 11:21:21 +0530 Subject: [PATCH 0009/1265] use v8::Object::Get --- atom/common/native_mate_converters/v8_value_converter.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index 6a858f2749c..1a729dda535 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -240,8 +240,7 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsDate()) { v8::Date* date = v8::Date::Cast(*val); v8::Local toISOString = - date->GetRealNamedPropertyInPrototypeChain( - v8::String::NewFromUtf8(isolate, "toISOString")); + date->Get(v8::String::NewFromUtf8(isolate, "toISOString")); if (toISOString->IsFunction()) { v8::Local result = toISOString.As()->Call(val, 0, nullptr); From 2b547bd44a8eca9bd2d0c7872f0a49906d808af7 Mon Sep 17 00:00:00 2001 From: Robo Date: Wed, 17 Feb 2016 22:33:27 +0530 Subject: [PATCH 0010/1265] webContents: provide responses for executeJavscript method --- atom/browser/api/lib/ipc-main.js | 4 ++ atom/browser/api/lib/web-contents.js | 14 ++++++- .../native_mate_converters/blink_converter.h | 14 +++++++ atom/renderer/api/atom_api_web_frame.cc | 41 +++++++++++++++++-- atom/renderer/lib/init.js | 10 +++++ atom/renderer/lib/web-view/web-view.js | 17 +++++--- docs/api/web-contents.md | 4 +- docs/api/web-view-tag.md | 4 +- spec/webview-spec.js | 18 +++++++- 9 files changed, 113 insertions(+), 13 deletions(-) diff --git a/atom/browser/api/lib/ipc-main.js b/atom/browser/api/lib/ipc-main.js index e253e03eaab..d6a043a92bf 100644 --- a/atom/browser/api/lib/ipc-main.js +++ b/atom/browser/api/lib/ipc-main.js @@ -1,3 +1,7 @@ const EventEmitter = require('events').EventEmitter; module.exports = new EventEmitter; + +// Every webContents would add a listenter to the +// WEB_FRAME_RESPONSE event, so ignore the listenters warning. +module.exports.setMaxListeners(0); diff --git a/atom/browser/api/lib/web-contents.js b/atom/browser/api/lib/web-contents.js index e0c16999c72..c2376af53a2 100644 --- a/atom/browser/api/lib/web-contents.js +++ b/atom/browser/api/lib/web-contents.js @@ -11,6 +11,7 @@ const debuggerBinding = process.atomBinding('debugger'); let slice = [].slice; let nextId = 0; +let responseCallback = {}; let getNextId = function() { return ++nextId; @@ -109,13 +110,24 @@ let wrapWebContents = function(webContents) { // Make sure webContents.executeJavaScript would run the code only when the // webContents has been loaded. const executeJavaScript = webContents.executeJavaScript; - webContents.executeJavaScript = function(code, hasUserGesture) { + webContents.executeJavaScript = function(code, hasUserGesture, callback) { + if (typeof hasUserGesture === "function") { + callback = hasUserGesture; + hasUserGesture = false; + } + if (callback !== null) + responseCallback["executeJavaScript"] = callback; if (this.getURL() && !this.isLoading()) return executeJavaScript.call(this, code, hasUserGesture); else return this.once('did-finish-load', executeJavaScript.bind(this, code, hasUserGesture)); }; + ipcMain.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_RESPONSE', function(event, method, result) { + if (responseCallback[method]) + responseCallback[method].apply(null, [result]); + }); + // Dispatch IPC messages to the ipc module. webContents.on('ipc-message', function(event, packed) { var args, channel; diff --git a/atom/common/native_mate_converters/blink_converter.h b/atom/common/native_mate_converters/blink_converter.h index 6a360192921..f066ea29ccd 100644 --- a/atom/common/native_mate_converters/blink_converter.h +++ b/atom/common/native_mate_converters/blink_converter.h @@ -6,6 +6,7 @@ #define ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ #include "native_mate/converter.h" +#include "third_party/WebKit/public/platform/WebVector.h" namespace blink { class WebInputEvent; @@ -87,6 +88,19 @@ struct Converter { blink::WebFindOptions* out); }; +template +struct Converter > { + static v8::Local ToV8(v8::Isolate* isolate, + const blink::WebVector& val) { + v8::Local result( + MATE_ARRAY_NEW(isolate, static_cast(val.size()))); + for (size_t i = 0; i < val.size(); ++i) { + result->Set(static_cast(i), Converter::ToV8(isolate, val[i])); + } + return result; + } +}; + } // namespace mate #endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index c72882886b9..06c9621b820 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -8,6 +8,7 @@ #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" +#include "atom/common/native_mate_converters/blink_converter.h" #include "atom/renderer/api/atom_api_spell_check_client.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" @@ -15,7 +16,7 @@ #include "native_mate/object_template_builder.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" -#include "third_party/WebKit/public/web/WebScopedUserGesture.h" +#include "third_party/WebKit/public/web/WebScriptExecutionCallback.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebSecurityPolicy.h" #include "third_party/WebKit/public/web/WebView.h" @@ -26,6 +27,33 @@ namespace atom { namespace api { +namespace { + +class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { + public: + using CompletionCallback = + base::Callback>& result)>; + + explicit ScriptExecutionCallback(const CompletionCallback& callback) + : callback_(callback) {} + ~ScriptExecutionCallback() {} + + void completed( + const blink::WebVector>& result) override { + if (!callback_.is_null()) + callback_.Run(result); + delete this; + } + + private: + CompletionCallback callback_; + + DISALLOW_COPY_AND_ASSIGN(ScriptExecutionCallback); +}; + +} // namespace + WebFrame::WebFrame() : web_frame_(blink::WebLocalFrame::frameForCurrentContext()) { } @@ -124,9 +152,14 @@ void WebFrame::ExecuteJavaScript(const base::string16& code, mate::Arguments* args) { bool has_user_gesture = false; args->GetNext(&has_user_gesture); - scoped_ptr gesture( - has_user_gesture ? new blink::WebScopedUserGesture : nullptr); - web_frame_->executeScriptAndReturnValue(blink::WebScriptSource(code)); + ScriptExecutionCallback::CompletionCallback completion_callback; + args->GetNext(&completion_callback); + scoped_ptr callback( + new ScriptExecutionCallback(completion_callback)); + web_frame_->requestExecuteScriptAndReturnValue( + blink::WebScriptSource(code), + has_user_gesture, + callback.release()); } mate::ObjectTemplateBuilder WebFrame::GetObjectTemplateBuilder( diff --git a/atom/renderer/lib/init.js b/atom/renderer/lib/init.js index 340a1ef5053..ab03a9055ce 100644 --- a/atom/renderer/lib/init.js +++ b/atom/renderer/lib/init.js @@ -32,7 +32,17 @@ v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter); const electron = require('electron'); // Call webFrame method. +const asyncWebFrameMethods = [ + 'executeJavaScript' +]; + electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, method, args) => { + if (asyncWebFrameMethods.includes(method)) { + const responseCallback = function(result) { + event.sender.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_RESPONSE', method, result); + }; + args.push(responseCallback); + } electron.webFrame[method].apply(electron.webFrame, args); }); diff --git a/atom/renderer/lib/web-view/web-view.js b/atom/renderer/lib/web-view/web-view.js index 44fc1042162..892ecf56192 100644 --- a/atom/renderer/lib/web-view/web-view.js +++ b/atom/renderer/lib/web-view/web-view.js @@ -307,7 +307,7 @@ var registerBrowserPluginElement = function() { // Registers custom element. var registerWebViewElement = function() { - var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto; + var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, webFrameMethods, proto; proto = Object.create(HTMLObjectElement.prototype); proto.createdCallback = function() { return new WebViewImpl(this); @@ -391,14 +391,16 @@ var registerWebViewElement = function() { 'printToPDF', ]; nonblockMethods = [ - 'executeJavaScript', 'insertCSS', - 'insertText', 'send', - 'sendInputEvent', + 'sendInputEvent' + ]; + webFrameMethods = [ + 'executeJavaScript', + 'insertText', 'setZoomFactor', 'setZoomLevel', - 'setZoomLevelLimits', + 'setZoomLevelLimits' ]; // Forward proto.foo* method calls to WebViewImpl.foo*. @@ -430,6 +432,11 @@ var registerWebViewElement = function() { proto[m] = createNonBlockHandler(m); } + // Forward proto.foo* webframe method calls to WebFrame.foo*. + for (let method of webFrameMethods) { + proto[method] = webFrame[method].bind(webFrame); + } + // WebContents associated with this webview. proto.getWebContents = function() { var internal = v8Util.getHiddenValue(this, 'internal'); diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index dde701d7f48..376860b17f9 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -425,10 +425,12 @@ Returns a `String` representing the user agent for this web page. Injects CSS into the current web page. -### `webContents.executeJavaScript(code[, userGesture])` +### `webContents.executeJavaScript(code[, userGesture, callback])` * `code` String * `userGesture` Boolean (optional) +* `callback` Function (optional) - Called after script has been executed. + * `result` Array Evaluates `code` in page. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 4a0697ad843..3bc4f0e9f64 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -279,10 +279,12 @@ Returns a `String` representing the user agent for guest page. Injects CSS into the guest page. -### `.executeJavaScript(code, userGesture)` +### `.executeJavaScript(code, userGesture, callback)` * `code` String * `userGesture` Boolean - Default `false`. +* `callback` Function (optional) - Called after script has been executed. + * `result` Array Evaluates `code` in page. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require diff --git a/spec/webview-spec.js b/spec/webview-spec.js index d73a177d097..fef49de454f 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -194,6 +194,7 @@ describe(' tag', function() { document.body.appendChild(webview); }); }); + describe('partition attribute', function() { it('inserts no node symbols when not set', function(done) { webview.addEventListener('console-message', function(e) { @@ -356,6 +357,7 @@ describe(' tag', function() { document.body.appendChild(webview); }); }); + describe('did-navigate-in-page event', function() { it('emits when an anchor link is clicked', function(done) { var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html'); @@ -556,7 +558,7 @@ describe(' tag', function() { done(); }; var listener2 = function() { - var jsScript = 'document.getElementsByTagName("video")[0].webkitRequestFullScreen()'; + var jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); webview.removeEventListener('did-finish-load', listener2); }; @@ -565,6 +567,20 @@ describe(' tag', function() { webview.src = "file://" + fixtures + "/pages/fullscreen.html"; document.body.appendChild(webview); }); + + it('can return the result of the executed script', function(done) { + var listener = function() { + var jsScript = "'4'+2"; + webview.executeJavaScript(jsScript, false, function(result) { + assert.equal(result[0], '42'); + done(); + }); + webview.removeEventListener('did-finish-load', listener); + }; + webview.addEventListener('did-finish-load', listener); + webview.src = "about:blank"; + document.body.appendChild(webview); + }); }); describe('sendInputEvent', function() { From a734326907d4a23c328cf602dabe62d677ec695b Mon Sep 17 00:00:00 2001 From: Robo Date: Mon, 22 Feb 2016 19:30:21 +0530 Subject: [PATCH 0011/1265] track async api requests --- atom/browser/api/lib/web-contents.js | 29 ++++++++++++++----- .../native_mate_converters/blink_converter.h | 14 --------- atom/renderer/api/atom_api_web_frame.cc | 6 ++-- atom/renderer/lib/init.js | 19 ++++++------ atom/renderer/lib/web-view/web-view.js | 4 +-- docs/api/web-contents.md | 2 +- docs/api/web-view-tag.md | 2 +- spec/webview-spec.js | 2 +- 8 files changed, 39 insertions(+), 39 deletions(-) diff --git a/atom/browser/api/lib/web-contents.js b/atom/browser/api/lib/web-contents.js index c2376af53a2..ed8afef7a52 100644 --- a/atom/browser/api/lib/web-contents.js +++ b/atom/browser/api/lib/web-contents.js @@ -11,6 +11,8 @@ const debuggerBinding = process.atomBinding('debugger'); let slice = [].slice; let nextId = 0; + +// Map of requestId and response callback. let responseCallback = {}; let getNextId = function() { @@ -59,13 +61,16 @@ let PDFPageSize = { // Following methods are mapped to webFrame. const webFrameMethods = [ - 'executeJavaScript', 'insertText', 'setZoomFactor', 'setZoomLevel', 'setZoomLevelLimits' ]; +const asyncWebFrameMethods = [ + 'executeJavaScript', +]; + let wrapWebContents = function(webContents) { // webContents is an EventEmitter. var controller, method, name, ref1; @@ -107,25 +112,35 @@ let wrapWebContents = function(webContents) { }; } + for (let method of asyncWebFrameMethods) { + webContents[method] = function() { + let args = Array.prototype.slice.call(arguments); + this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', method, args); + }; + } + // Make sure webContents.executeJavaScript would run the code only when the // webContents has been loaded. const executeJavaScript = webContents.executeJavaScript; webContents.executeJavaScript = function(code, hasUserGesture, callback) { + let requestId = getNextId(); if (typeof hasUserGesture === "function") { callback = hasUserGesture; hasUserGesture = false; } if (callback !== null) - responseCallback["executeJavaScript"] = callback; + responseCallback[requestId] = callback; if (this.getURL() && !this.isLoading()) - return executeJavaScript.call(this, code, hasUserGesture); + return executeJavaScript.call(this, requestId, code, hasUserGesture); else - return this.once('did-finish-load', executeJavaScript.bind(this, code, hasUserGesture)); + return this.once('did-finish-load', executeJavaScript.bind(this, requestId, code, hasUserGesture)); }; - ipcMain.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_RESPONSE', function(event, method, result) { - if (responseCallback[method]) - responseCallback[method].apply(null, [result]); + ipcMain.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE', function(event, id, result) { + if (responseCallback[id]) { + responseCallback[id].apply(null, [result]); + delete responseCallback[id]; + } }); // Dispatch IPC messages to the ipc module. diff --git a/atom/common/native_mate_converters/blink_converter.h b/atom/common/native_mate_converters/blink_converter.h index f066ea29ccd..6a360192921 100644 --- a/atom/common/native_mate_converters/blink_converter.h +++ b/atom/common/native_mate_converters/blink_converter.h @@ -6,7 +6,6 @@ #define ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ #include "native_mate/converter.h" -#include "third_party/WebKit/public/platform/WebVector.h" namespace blink { class WebInputEvent; @@ -88,19 +87,6 @@ struct Converter { blink::WebFindOptions* out); }; -template -struct Converter > { - static v8::Local ToV8(v8::Isolate* isolate, - const blink::WebVector& val) { - v8::Local result( - MATE_ARRAY_NEW(isolate, static_cast(val.size()))); - for (size_t i = 0; i < val.size(); ++i) { - result->Set(static_cast(i), Converter::ToV8(isolate, val[i])); - } - return result; - } -}; - } // namespace mate #endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index 06c9621b820..af9a3c41621 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -8,7 +8,6 @@ #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" -#include "atom/common/native_mate_converters/blink_converter.h" #include "atom/renderer/api/atom_api_spell_check_client.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" @@ -33,7 +32,7 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { public: using CompletionCallback = base::Callback>& result)>; + const v8::Local& result)>; explicit ScriptExecutionCallback(const CompletionCallback& callback) : callback_(callback) {} @@ -42,7 +41,8 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { void completed( const blink::WebVector>& result) override { if (!callback_.is_null()) - callback_.Run(result); + // Right now only single results per frame is supported. + callback_.Run(result[0]); delete this; } diff --git a/atom/renderer/lib/init.js b/atom/renderer/lib/init.js index ab03a9055ce..f7f78e84a1b 100644 --- a/atom/renderer/lib/init.js +++ b/atom/renderer/lib/init.js @@ -32,17 +32,16 @@ v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter); const electron = require('electron'); // Call webFrame method. -const asyncWebFrameMethods = [ - 'executeJavaScript' -]; - electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, method, args) => { - if (asyncWebFrameMethods.includes(method)) { - const responseCallback = function(result) { - event.sender.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_RESPONSE', method, result); - }; - args.push(responseCallback); - } + electron.webFrame[method].apply(electron.webFrame, args); +}); + +electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (event, method, args) => { + let requestId = args.shift(); + const responseCallback = function(result) { + event.sender.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE', requestId, result); + }; + args.push(responseCallback); electron.webFrame[method].apply(electron.webFrame, args); }); diff --git a/atom/renderer/lib/web-view/web-view.js b/atom/renderer/lib/web-view/web-view.js index 892ecf56192..25e5eead2dd 100644 --- a/atom/renderer/lib/web-view/web-view.js +++ b/atom/renderer/lib/web-view/web-view.js @@ -393,14 +393,14 @@ var registerWebViewElement = function() { nonblockMethods = [ 'insertCSS', 'send', - 'sendInputEvent' + 'sendInputEvent', ]; webFrameMethods = [ 'executeJavaScript', 'insertText', 'setZoomFactor', 'setZoomLevel', - 'setZoomLevelLimits' + 'setZoomLevelLimits', ]; // Forward proto.foo* method calls to WebViewImpl.foo*. diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 376860b17f9..e095213bd97 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -430,7 +430,7 @@ Injects CSS into the current web page. * `code` String * `userGesture` Boolean (optional) * `callback` Function (optional) - Called after script has been executed. - * `result` Array + * `result` Evaluates `code` in page. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 3bc4f0e9f64..fa48ef60f3f 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -284,7 +284,7 @@ Injects CSS into the guest page. * `code` String * `userGesture` Boolean - Default `false`. * `callback` Function (optional) - Called after script has been executed. - * `result` Array + * `result` Evaluates `code` in page. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require diff --git a/spec/webview-spec.js b/spec/webview-spec.js index fef49de454f..cd2be69d737 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -572,7 +572,7 @@ describe(' tag', function() { var listener = function() { var jsScript = "'4'+2"; webview.executeJavaScript(jsScript, false, function(result) { - assert.equal(result[0], '42'); + assert.equal(result, '42'); done(); }); webview.removeEventListener('did-finish-load', listener); From 8386baf267545157584588f244bdfa8a75652555 Mon Sep 17 00:00:00 2001 From: Robo Date: Wed, 24 Feb 2016 15:41:09 +0530 Subject: [PATCH 0012/1265] add spec --- atom/browser/api/lib/ipc-main.js | 4 ---- atom/browser/api/lib/web-contents.js | 33 ++++++++++------------------ atom/renderer/lib/init.js | 5 ++--- spec/api-browser-window-spec.js | 19 ++++++++++++++++ spec/static/main.js | 11 ++++++++++ 5 files changed, 44 insertions(+), 28 deletions(-) diff --git a/atom/browser/api/lib/ipc-main.js b/atom/browser/api/lib/ipc-main.js index d6a043a92bf..e253e03eaab 100644 --- a/atom/browser/api/lib/ipc-main.js +++ b/atom/browser/api/lib/ipc-main.js @@ -1,7 +1,3 @@ const EventEmitter = require('events').EventEmitter; module.exports = new EventEmitter; - -// Every webContents would add a listenter to the -// WEB_FRAME_RESPONSE event, so ignore the listenters warning. -module.exports.setMaxListeners(0); diff --git a/atom/browser/api/lib/web-contents.js b/atom/browser/api/lib/web-contents.js index ed8afef7a52..7cd54bfddfb 100644 --- a/atom/browser/api/lib/web-contents.js +++ b/atom/browser/api/lib/web-contents.js @@ -67,10 +67,6 @@ const webFrameMethods = [ 'setZoomLevelLimits' ]; -const asyncWebFrameMethods = [ - 'executeJavaScript', -]; - let wrapWebContents = function(webContents) { // webContents is an EventEmitter. var controller, method, name, ref1; @@ -112,37 +108,32 @@ let wrapWebContents = function(webContents) { }; } - for (let method of asyncWebFrameMethods) { - webContents[method] = function() { - let args = Array.prototype.slice.call(arguments); - this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', method, args); - }; - } + const asyncWebFrameMethods = function(requestId, method, ...args) { + this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args); + ipcMain.once('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE_' + requestId, function(event, result) { + if (responseCallback[requestId]) { + responseCallback[requestId](result); + delete responseCallback[requestId]; + } + }); + }; // Make sure webContents.executeJavaScript would run the code only when the // webContents has been loaded. - const executeJavaScript = webContents.executeJavaScript; webContents.executeJavaScript = function(code, hasUserGesture, callback) { let requestId = getNextId(); if (typeof hasUserGesture === "function") { callback = hasUserGesture; hasUserGesture = false; } - if (callback !== null) + if (callback != null) responseCallback[requestId] = callback; if (this.getURL() && !this.isLoading()) - return executeJavaScript.call(this, requestId, code, hasUserGesture); + return asyncWebFrameMethods.call(this, requestId, "executeJavaScript", code, hasUserGesture); else - return this.once('did-finish-load', executeJavaScript.bind(this, requestId, code, hasUserGesture)); + return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, "executeJavaScript", code, hasUserGesture)); }; - ipcMain.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE', function(event, id, result) { - if (responseCallback[id]) { - responseCallback[id].apply(null, [result]); - delete responseCallback[id]; - } - }); - // Dispatch IPC messages to the ipc module. webContents.on('ipc-message', function(event, packed) { var args, channel; diff --git a/atom/renderer/lib/init.js b/atom/renderer/lib/init.js index f7f78e84a1b..cf42aa27229 100644 --- a/atom/renderer/lib/init.js +++ b/atom/renderer/lib/init.js @@ -36,10 +36,9 @@ electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, m electron.webFrame[method].apply(electron.webFrame, args); }); -electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (event, method, args) => { - let requestId = args.shift(); +electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (event, requestId, method, args) => { const responseCallback = function(result) { - event.sender.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE', requestId, result); + event.sender.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE_' + requestId, result); }; args.push(responseCallback); electron.webFrame[method].apply(electron.webFrame, args); diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 58cf57cc8d0..25e92382cca 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -10,6 +10,7 @@ const screen = require('electron').screen; const app = remote.require('electron').app; const ipcMain = remote.require('electron').ipcMain; +const ipcRenderer = require('electron').ipcRenderer; const BrowserWindow = remote.require('electron').BrowserWindow; const isCI = remote.getGlobal('isCi'); @@ -690,4 +691,22 @@ describe('browser-window module', function() { assert.equal(fs.existsSync(serializedPath), false); }); }); + + describe('window.webContents.executeJavaScript', function() { + var expected = 'hello, world!'; + var code = '(() => \"' + expected + '\")()'; + + it('doesnt throw when no calback is provided', function() { + const result = ipcRenderer.sendSync('executeJavaScript', code, false); + assert.equal(result, 'success'); + }); + + it('returns result when calback is provided', function(done) { + ipcRenderer.send('executeJavaScript', code, true); + ipcRenderer.once('executeJavaScript-response', function(event, result) { + assert.equal(result, expected); + done(); + }); + }); + }); }); diff --git a/spec/static/main.js b/spec/static/main.js index 48fdf17c3dc..9a049e3f107 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -138,4 +138,15 @@ app.on('ready', function() { }); event.returnValue = "done"; }); + + ipcMain.on('executeJavaScript', function(event, code, hasCallback) { + if (hasCallback) { + window.webContents.executeJavaScript(code, (result) => { + window.webContents.send('executeJavaScript-response', result); + }); + } else { + window.webContents.executeJavaScript(code); + event.returnValue = "success"; + } + }); }); From 6f45678e9c68874474de2d3727f16a96ac45a528 Mon Sep 17 00:00:00 2001 From: Robert Lyall Date: Thu, 25 Feb 2016 18:28:03 +0000 Subject: [PATCH 0013/1265] Fix Menu template API example --- docs-translations/jp/api/menu.md | 2 +- docs-translations/ko-KR/api/menu.md | 2 +- docs/api/menu.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs-translations/jp/api/menu.md b/docs-translations/jp/api/menu.md index e68a69cca83..12039b1d6ad 100644 --- a/docs-translations/jp/api/menu.md +++ b/docs-translations/jp/api/menu.md @@ -135,7 +135,7 @@ var template = [ ]; if (process.platform == 'darwin') { - var name = require('electron').app.getName(); + var name = require('electron').remote.app.getName(); template.unshift({ label: name, submenu: [ diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 347ea880dce..61c68023b07 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -140,7 +140,7 @@ var template = [ ]; if (process.platform == 'darwin') { - var name = require('electron').app.getName(); + var name = require('electron').remote.app.getName(); template.unshift({ label: name, submenu: [ diff --git a/docs/api/menu.md b/docs/api/menu.md index 49a499a3d4b..7d05f88aa2b 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -143,7 +143,7 @@ var template = [ ]; if (process.platform == 'darwin') { - var name = require('electron').app.getName(); + var name = require('electron').remote.app.getName(); template.unshift({ label: name, submenu: [ From 9a0372b61be525c528919742384ecc56bf3428ec Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Thu, 25 Feb 2016 23:48:58 +0100 Subject: [PATCH 0014/1265] Removed size_ since it's not needed anymore --- atom/browser/api/frame_subscriber.cc | 6 +++--- atom/browser/api/frame_subscriber.h | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index ec3bcd05ab7..4653fc452ad 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -4,13 +4,14 @@ #include "atom/browser/api/frame_subscriber.h" -#include "atom/common/node_includes.h" #include "base/bind.h" +#include "atom/common/node_includes.h" #include "media/base/video_frame.h" #include "media/base/yuv_convert.h" -#include "content/public/browser/render_widget_host.h" #include "ui/gfx/screen.h" +#include "content/public/browser/render_widget_host.h" + namespace atom { namespace api { @@ -22,7 +23,6 @@ FrameSubscriber::FrameSubscriber(v8::Isolate* isolate, const FrameCaptureCallback& callback) : isolate_(isolate), callback_(callback), pending_frames(0), view_(view) { subscriber_ = new Subscriber(this); - size_ = view->GetVisibleViewportSize(); } Subscriber::Subscriber( diff --git a/atom/browser/api/frame_subscriber.h b/atom/browser/api/frame_subscriber.h index 745cf382adb..7029e0ed33a 100644 --- a/atom/browser/api/frame_subscriber.h +++ b/atom/browser/api/frame_subscriber.h @@ -6,12 +6,13 @@ #define ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_ #include "base/callback.h" +#include "v8/include/v8.h" + #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_widget_host_view_frame_subscriber.h" #include "content/public/browser/readback_types.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/size.h" -#include "v8/include/v8.h" namespace atom { @@ -50,7 +51,6 @@ class FrameSubscriber { bool RequestDestruct(); v8::Isolate* isolate_; - gfx::Size size_; content::RenderWidgetHostView* view_; FrameCaptureCallback callback_; Subscriber* subscriber_; From 12359078357f0d0227864a9700e660a673f764e3 Mon Sep 17 00:00:00 2001 From: Robo Date: Thu, 25 Feb 2016 23:35:01 +0530 Subject: [PATCH 0015/1265] run webframe methods for webview in its context --- atom/browser/api/lib/web-contents.js | 19 ++++++------------ atom/browser/lib/rpc-server.js | 10 ++++++++-- atom/renderer/api/atom_api_web_frame.cc | 2 +- atom/renderer/lib/init.js | 2 +- atom/renderer/lib/web-view/web-view.js | 26 +++++++++++++++---------- 5 files changed, 32 insertions(+), 27 deletions(-) diff --git a/atom/browser/api/lib/web-contents.js b/atom/browser/api/lib/web-contents.js index 7cd54bfddfb..9486378264b 100644 --- a/atom/browser/api/lib/web-contents.js +++ b/atom/browser/api/lib/web-contents.js @@ -12,9 +12,6 @@ const debuggerBinding = process.atomBinding('debugger'); let slice = [].slice; let nextId = 0; -// Map of requestId and response callback. -let responseCallback = {}; - let getNextId = function() { return ++nextId; }; @@ -108,13 +105,11 @@ let wrapWebContents = function(webContents) { }; } - const asyncWebFrameMethods = function(requestId, method, ...args) { + const asyncWebFrameMethods = function(requestId, method, callback, ...args) { this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args); - ipcMain.once('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE_' + requestId, function(event, result) { - if (responseCallback[requestId]) { - responseCallback[requestId](result); - delete responseCallback[requestId]; - } + ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function(event, result) { + if (callback) + callback(result); }); }; @@ -126,12 +121,10 @@ let wrapWebContents = function(webContents) { callback = hasUserGesture; hasUserGesture = false; } - if (callback != null) - responseCallback[requestId] = callback; if (this.getURL() && !this.isLoading()) - return asyncWebFrameMethods.call(this, requestId, "executeJavaScript", code, hasUserGesture); + return asyncWebFrameMethods.call(this, requestId, "executeJavaScript", callback, code, hasUserGesture); else - return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, "executeJavaScript", code, hasUserGesture)); + return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, "executeJavaScript", callback, code, hasUserGesture)); }; // Dispatch IPC messages to the ipc module. diff --git a/atom/browser/lib/rpc-server.js b/atom/browser/lib/rpc-server.js index 20ee8fbdeae..a31c6e146e8 100644 --- a/atom/browser/lib/rpc-server.js +++ b/atom/browser/lib/rpc-server.js @@ -354,11 +354,17 @@ ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function(event, guestInstanceId) { } }); -ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function(event, guestInstanceId, method, ...args) { +ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function(event, requestId, guestInstanceId, method, ...args) { try { let guestViewManager = require('./guest-view-manager'); let guest = guestViewManager.getGuest(guestInstanceId); - return guest[method].apply(guest, args); + if (requestId) { + const responseCallback = function(result) { + event.sender.send(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result); + }; + args.push(responseCallback); + } + guest[method].apply(guest, args); } catch (error) { return event.returnValue = exceptionToMeta(error); } diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index af9a3c41621..e00b901bfff 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -40,7 +40,7 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { void completed( const blink::WebVector>& result) override { - if (!callback_.is_null()) + if (!callback_.is_null() && !result.isEmpty() && !result[0].IsEmpty()) // Right now only single results per frame is supported. callback_.Run(result[0]); delete this; diff --git a/atom/renderer/lib/init.js b/atom/renderer/lib/init.js index cf42aa27229..166e64237de 100644 --- a/atom/renderer/lib/init.js +++ b/atom/renderer/lib/init.js @@ -38,7 +38,7 @@ electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, m electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (event, requestId, method, args) => { const responseCallback = function(result) { - event.sender.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_RESPONSE_' + requestId, result); + event.sender.send(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, result); }; args.push(responseCallback); electron.webFrame[method].apply(electron.webFrame, args); diff --git a/atom/renderer/lib/web-view/web-view.js b/atom/renderer/lib/web-view/web-view.js index 25e5eead2dd..bd128f6fffe 100644 --- a/atom/renderer/lib/web-view/web-view.js +++ b/atom/renderer/lib/web-view/web-view.js @@ -307,7 +307,7 @@ var registerBrowserPluginElement = function() { // Registers custom element. var registerWebViewElement = function() { - var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, webFrameMethods, proto; + var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto; proto = Object.create(HTMLObjectElement.prototype); proto.createdCallback = function() { return new WebViewImpl(this); @@ -392,12 +392,9 @@ var registerWebViewElement = function() { ]; nonblockMethods = [ 'insertCSS', + 'insertText', 'send', 'sendInputEvent', - ]; - webFrameMethods = [ - 'executeJavaScript', - 'insertText', 'setZoomFactor', 'setZoomLevel', 'setZoomLevelLimits', @@ -424,7 +421,7 @@ var registerWebViewElement = function() { var args, internal; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; internal = v8Util.getHiddenValue(this, 'internal'); - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', internal.guestInstanceId, m].concat(slice.call(args))); + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(slice.call(args))); }; }; for (j = 0, len1 = nonblockMethods.length; j < len1; j++) { @@ -432,10 +429,19 @@ var registerWebViewElement = function() { proto[m] = createNonBlockHandler(m); } - // Forward proto.foo* webframe method calls to WebFrame.foo*. - for (let method of webFrameMethods) { - proto[method] = webFrame[method].bind(webFrame); - } + proto.executeJavaScript = function(code, hasUserGesture, callback) { + var internal = v8Util.getHiddenValue(this, 'internal'); + if (typeof hasUserGesture === "function") { + callback = hasUserGesture; + hasUserGesture = false; + } + let requestId = getNextId(); + ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, "executeJavaScript", code, hasUserGesture); + ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function(event, result) { + if (callback) + callback(result); + }); + }; // WebContents associated with this webview. proto.getWebContents = function() { From 4bfa03e5f4574ecea0d513b359406ded69449f9c Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Fri, 26 Feb 2016 02:13:17 +0100 Subject: [PATCH 0016/1265] Removed an include no longer needed --- atom/browser/api/frame_subscriber.cc | 2 -- 1 file changed, 2 deletions(-) diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index 89e05d3e2dc..c76d5ffc87d 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -6,8 +6,6 @@ #include "base/bind.h" #include "atom/common/node_includes.h" -#include "ui/gfx/screen.h" - #include "content/public/browser/render_widget_host.h" namespace atom { From a3b8e81c213a157d944937c7c73641040622529e Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Wed, 24 Feb 2016 12:19:43 -0800 Subject: [PATCH 0017/1265] :memo: Add Headless CI Tutorial --- docs/README.md | 1 + docs/tutorial/testing-on-headless-ci.md | 38 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 docs/tutorial/testing-on-headless-ci.md diff --git a/docs/README.md b/docs/README.md index 9d2b36eb6c1..19ec51343d4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,7 @@ an issue: * [DevTools Extension](tutorial/devtools-extension.md) * [Using Pepper Flash Plugin](tutorial/using-pepper-flash-plugin.md) * [Using Widevine CDM Plugin](tutorial/using-widevine-cdm-plugin.md) +* [Testing on Headless CI Systems (Travis, Jenkins)](tutorial/testing-on-headless-ci.md) ## Tutorials diff --git a/docs/tutorial/testing-on-headless-ci.md b/docs/tutorial/testing-on-headless-ci.md new file mode 100644 index 00000000000..6b0dacf788f --- /dev/null +++ b/docs/tutorial/testing-on-headless-ci.md @@ -0,0 +1,38 @@ +# Testing Electron with headless CI Systems (Travis CI, Jenkins) + +Being based on Chromium, Electron requires a display driver to function. If Chromium can't find a display driver, Electron will simply fail to launch - and therefore not executing any of your tests, regardless of how you are running them. Testing Electron-based apps on Travis, Circle, Jenkins or similar systems requires therefore a little bit of configuration. In essence, we need to use a virtual display driver. + +## Configuring the Virtual Display Server +First, install [Xvfb](https://en.wikipedia.org/wiki/Xvfb). It's a virtual framebuffer, implementing the X11 display server protocol - it performs all graphical operations in memory without showing any screen output, which is exactly what we need. + +Then, create a virtual xvfb screen and export an environment variable called DISPLAY that points to it. Chromium in Electron will automatically look for `$DISPLAY`, so no further configuration of your app is required. This step can be automated with Paul Betts's [xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe): Prepend your test commands with `xfvb-maybe` and the little tool will automatically configure xfvb, if required by the current system. On Windows or Mac OS X, it will simply do nothing. + +``` +## On Windows or OS X, this just invokes electron-mocha +## On Linux, if we are in a headless environment, this will be equivalent +## to xvfb-run electron-mocha ./test/*.js +xvfb-maybe electron-mocha ./test/*.js +``` + +### Travis CI +On Travis, your `.travis.yml` should look roughly like this: + +``` +addons: + apt: + packages: + - xvfb + +install: + - export DISPLAY=':99.0' + - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +``` + +### Jenkins +For Jenkins, a [Xfvb plugin is available](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). + +### Circle CI +Circle CI is awesome and has xvfb and `$DISPLAY` [already setup, so no further configuration is required](https://circleci.com/docs/environment#browsers). + +### AppVeyor +AppVeyor runs on Windows, supporting Selenium, Chromium, Electron and similar tools out of the box - no configuration is required. From 8a744255facacf54cecc8b5eb526ce08afab1ec4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 26 Feb 2016 09:23:39 +0800 Subject: [PATCH 0018/1265] Update libchromiumcontent, use harfbuzz 1.06 Close #4513. --- script/lib/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/lib/config.py b/script/lib/config.py index e3404918ce4..d4a055912e4 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '599c8941e1884e155218ec1013cba9fc5c7c7072' +LIBCHROMIUMCONTENT_COMMIT = 'ff714bf7ad79b0d278bcd20c3081a69b40be8bb8' PLATFORM = { 'cygwin': 'win32', From a67b29d8d28c1eb993c89a097dda17c0cf63d99b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 26 Feb 2016 02:18:27 +0000 Subject: [PATCH 0019/1265] Bump v0.36.9 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index 68a30cc637f..0bccc254b1b 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.36.8', + 'version%': '0.36.9', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index e1a5694d27a..b3eb7d8efaa 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.36.8 + 0.36.9 CFBundleShortVersionString - 0.36.8 + 0.36.9 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index ff125b3edf7..2dee1c0e433 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,36,8,0 - PRODUCTVERSION 0,36,8,0 + FILEVERSION 0,36,9,0 + PRODUCTVERSION 0,36,9,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.36.8" + VALUE "FileVersion", "0.36.9" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.36.8" + VALUE "ProductVersion", "0.36.9" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index b464ebdae4f..136c375e2ac 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 36 -#define ATOM_PATCH_VERSION 8 +#define ATOM_PATCH_VERSION 9 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index e6d399fb3be..504bdd6a4f7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.36.8", + "version": "0.36.9", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From fce641aab64da828cf03afd2e07b7b81333655ad Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 26 Feb 2016 15:47:28 +0530 Subject: [PATCH 0020/1265] browser: allow enumeration of media device labels --- atom/browser/api/atom_api_web_contents.cc | 7 +++++++ atom/browser/api/atom_api_web_contents.h | 4 ++++ spec/chromium-spec.js | 14 ++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 4935adbc75a..28893a54a3d 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -463,6 +463,13 @@ void WebContents::FindReply(content::WebContents* web_contents, } } +bool WebContents::CheckMediaAccessPermission( + content::WebContents* web_contents, + const GURL& security_origin, + content::MediaStreamType type) { + return true; +} + void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index b4f29090dbd..a785e1c070d 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -202,6 +202,10 @@ class WebContents : public mate::TrackableObject, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; + bool CheckMediaAccessPermission( + content::WebContents* web_contents, + const GURL& security_origin, + content::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index e4444f55b11..8477aea776a 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -87,6 +87,20 @@ describe('chromium feature', function() { }); }); + describe('navigator.mediaDevices', function() { + if (process.env.TRAVIS === 'true') { + return; + } + + it('can return labels of enumerated devices', function(done) { + navigator.mediaDevices.enumerateDevices().then((devices) => { + const result = devices.some((device) => !!device.label); + if (result) + done(); + }); + }); + }); + describe('navigator.language', function() { it('should not be empty', function() { assert.notEqual(navigator.language, ''); From 070772b4b984e0bc03cea28388dffaa63b14d0d0 Mon Sep 17 00:00:00 2001 From: gellert Date: Sat, 6 Feb 2016 22:33:21 +0100 Subject: [PATCH 0021/1265] Added special key identifiers for OSX and Windows --- atom/common/keyboard_util.cc | 10 ++++++++++ docs/api/web-contents.md | 6 ++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/atom/common/keyboard_util.cc b/atom/common/keyboard_util.cc index e5dedd84ded..1884246d233 100644 --- a/atom/common/keyboard_util.cc +++ b/atom/common/keyboard_util.cc @@ -80,6 +80,16 @@ ui::KeyboardCode KeyboardCodeFromKeyIdentifier(const std::string& chr) { if (chr == "tab") return ui::VKEY_TAB; if (chr == "escape") return ui::VKEY_ESCAPE; if (chr == "control") return ui::VKEY_CONTROL; +#if defined(OS_MACOSX) + if (chr == "command" + || chr == "cmd" + || chr == "meta") return ui::VKEY_COMMAND; + if (chr == "option") return ui::VKEY_MENU; +#endif +#if defined(OS_WIN) + if (chr == "meta") return ui::VKEY_LWIN; + if (chr == "altgr") return ui::VKEY_ALTGR; +#endif if (chr == "alt") return ui::VKEY_MENU; if (chr == "shift") return ui::VKEY_SHIFT; if (chr == "end") return ui::VKEY_END; diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index dde701d7f48..31c55801aab 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -769,8 +769,10 @@ For keyboard events, the `event` object also have following properties: * `keyCode` Char or String (**required**) - The character that will be sent as the keyboard event. Can be a single UTF-8 character, or the name of the key that generates the event. Accepted key names are `enter`, `backspace`, - `delete`, `tab`, `escape`, `control`, `alt`, `shift`, `end`, `home`, `insert`, - `left`, `up`, `right`, `down`, `pageUp`, `pageDown`, `printScreen` + `delete`, `tab`, `escape`, `control`, `alt`, `altgr` (Windows only), `shift`, + `end`, `home`, `insert`, `left`, `up`, `right`, `down`, `pageUp`, `pageDown`, + `printScreen`, `meta`, `cmd` (OSX only), `command` (OSX only), `option` + (OSX only) For mouse events, the `event` object also have following properties: From bb0ac688b2d1d19904370a33a49a19c75a31e129 Mon Sep 17 00:00:00 2001 From: Heilig Benedek Date: Sat, 27 Feb 2016 03:07:53 +0100 Subject: [PATCH 0022/1265] Reverted SetFullscreenable disabling maximize button on Windows and removed that from the docs. --- atom/browser/native_window_views.cc | 3 --- docs/api/browser-window.md | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 4b3b32024df..c74e8808150 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -497,9 +497,6 @@ bool NativeWindowViews::IsMaximizable() { } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { - #if defined(OS_WIN) - FlipWindowStyle(GetAcceleratedWidget(), false, WS_MAXIMIZEBOX); - #endif fullscreenable_ = fullscreenable; } diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 96ce955db59..d38a5b7083d 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -59,8 +59,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`. other windows. Default is `false`. * `fullscreen` Boolean - Whether the window should show in fullscreen. When explicity set to `false` the fullscreen button will be hidden or disabled - on OS X, or the maximize button will be disabled on Windows. Default is - `false`. + on OS X. Default is `false`. * `fullscreenable` Boolean - Whether the maximize/zoom button on OS X should toggle full screen mode or maximize window. Default is `true`. * `skipTaskbar` Boolean - Whether to show the window in taskbar. Default is From fd11b7e7db57683da2453cb61a289d53012923d2 Mon Sep 17 00:00:00 2001 From: Andrea Parodi Date: Sat, 27 Feb 2016 20:34:51 +0100 Subject: [PATCH 0023/1265] Removed duplicate isDevToolsFocused entry --- docs/api/web-contents.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 25597d9b6c8..66ab545bf21 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -664,10 +664,6 @@ Returns whether the devtools view is focused . Toggles the developer tools. -### `webContents.isDevToolsFocused()` - -Returns whether the developer tools is focused. - ### `webContents.inspectElement(x, y)` * `x` Integer From a06392459e2c43fcc2070513f564d506526d837f Mon Sep 17 00:00:00 2001 From: brenca Date: Sat, 27 Feb 2016 22:37:42 +0100 Subject: [PATCH 0024/1265] Making fullsceenable work on Linux --- atom/browser/native_window.cc | 4 ++-- atom/browser/native_window_views.cc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 273bd948fe5..16154be6bea 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -133,7 +133,7 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(true); } -#if defined(OS_MACOSX) || defined(OS_WIN) + // Disable fullscreen button when 'fullscreenable' is false or 'fullscreen' // is specified to false. bool fullscreenable = true; @@ -144,7 +144,7 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { SetFullScreenable(fullscreenable); if (fullscreen) SetFullScreen(true); -#endif + bool skip; if (options.Get(options::kSkipTaskbar, &skip) && skip) { SetSkipTaskbar(skip); diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 1c9493a1cf9..a0c2e3f170b 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -379,7 +379,7 @@ void NativeWindowViews::SetFullScreen(bool fullscreen) { if (IsFullScreenable()) window_->SetFullscreen(fullscreen); #else - if (!fullscreen || IsFullScreenable()) { + if (!fullscreen || (fullscreen && IsFullScreenable())) { if (IsVisible()) window_->SetFullscreen(fullscreen); else From 681a772f5f4797fe4e7efeb5b8f094d801a1c43a Mon Sep 17 00:00:00 2001 From: RacioN Date: Sun, 28 Feb 2016 20:42:14 +0900 Subject: [PATCH 0025/1265] Add list --- docs-translations/jp/README.md | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/docs-translations/jp/README.md b/docs-translations/jp/README.md index accde973976..6248e35044d 100644 --- a/docs-translations/jp/README.md +++ b/docs-translations/jp/README.md @@ -3,6 +3,7 @@ そうでない場合、おそらくご使用の Electron のバージョンと互換性のない API 変更を含んだ development ブランチのドキュメントを使っているものと思われます。 その場合、atom.io の [available versions](http://electron.atom.io/docs/) リストにある別のバージョンのドキュメントに切り替えることができます。また GitHub で閲覧している場合、"Switch branches/tags" ドロップダウンを開いて、バージョンに対応したタグを選ぶこともできます。 +_リンクになっていないリストは未翻訳のものです。_ ## FAQ 頻繁に聞かれる質問がありますので、issueを作成する前にこれをチェックしてください。 @@ -31,3 +32,57 @@ ## API リファレンス * [概要](api/synopsis.md) +* [Process Object](api/process.md) +* [Supported Chrome Command Line Switches](api/chrome-command-line-switches.md) +* [Environment Variables](api/environment-variables.md) + +### Custom DOM Elements: + +* [`File` Object](api/file-object.md) +* `` Tag +* [`window.open` Function](api/window-open.md) + +### Modules for the Main Process: + +* [app](api/app.md) +* [autoUpdater](api/auto-updater.md) +* BrowserWindow + * [frameless-window](frameless-window.md) +* [contentTracing](api/content-tracing.md) +* [dialog](api/dialog.md) +* [globalShortcut](api/global-shortcut.md) +* [ipcMain](api/ipc-main.md) +* [Menu](api/menu.md) +* [MenuItem](api/menu-item.md) +* [powerMonitor](api/power-monitor.md) +* [powerSaveBlocker](api/power-save-blocker.md) +* [protocol](api/protocol.md) +* [session](api/session.md) +* webContents +* [Tray](api/tray.md) + +### Modules for the Renderer Process (Web Page): + +* [desktopCapturer](api/desktop-capturer.md) +* [ipcRenderer](api/ipc-renderer.md) +* [remote](api/remote.md) +* [webFrame](api/web-frame.md) + +### Modules for Both Processes: + +* [clipboard](api/clipboard.md) +* [crashReporter](api/crash-reporter.md) +* [nativeImage](api/native-image.md) +* [screen](api/screen.md) +* [shell](api/shell.md) + +## 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 (OS X)](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) From e3dde12c45d2e8817005c74beea1f57696d3f13b Mon Sep 17 00:00:00 2001 From: RacioN Date: Sun, 28 Feb 2016 20:50:16 +0900 Subject: [PATCH 0026/1265] Update read me tranlation --- docs-translations/jp/README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs-translations/jp/README.md b/docs-translations/jp/README.md index 6248e35044d..558d362498a 100644 --- a/docs-translations/jp/README.md +++ b/docs-translations/jp/README.md @@ -33,21 +33,21 @@ _リンクになっていないリストは未翻訳のものです。_ * [概要](api/synopsis.md) * [Process Object](api/process.md) -* [Supported Chrome Command Line Switches](api/chrome-command-line-switches.md) -* [Environment Variables](api/environment-variables.md) +* [サポートしているChromeコマンドラインスイッチ](api/chrome-command-line-switches.md) +* [環境変数](api/environment-variables.md) ### Custom DOM Elements: * [`File` Object](api/file-object.md) * `` Tag -* [`window.open` Function](api/window-open.md) +* [`window.open` 関数](api/window-open.md) ### Modules for the Main Process: * [app](api/app.md) * [autoUpdater](api/auto-updater.md) * BrowserWindow - * [frameless-window](frameless-window.md) + * [フレームの無いウィンドウ](api/frameless-window.md) * [contentTracing](api/content-tracing.md) * [dialog](api/dialog.md) * [globalShortcut](api/global-shortcut.md) @@ -78,11 +78,11 @@ _リンクになっていないリストは未翻訳のものです。_ ## 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 (OS X)](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 +* Source Code Directory Structure +* Technical Differences to NW.js (formerly node-webkit) +* Build System Overview +* Build Instructions (OS X) +* Build Instructions (Windows) +* Build Instructions (Linux) +* Setting Up Symbol Server in debugger From 2d11b1d9eb36e88d8650ed7596b5b8d29ff508e9 Mon Sep 17 00:00:00 2001 From: RacioN Date: Sun, 28 Feb 2016 20:55:47 +0900 Subject: [PATCH 0027/1265] Update read me tranlation --- docs-translations/jp/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs-translations/jp/README.md b/docs-translations/jp/README.md index 558d362498a..a71661a7e53 100644 --- a/docs-translations/jp/README.md +++ b/docs-translations/jp/README.md @@ -36,13 +36,13 @@ _リンクになっていないリストは未翻訳のものです。_ * [サポートしているChromeコマンドラインスイッチ](api/chrome-command-line-switches.md) * [環境変数](api/environment-variables.md) -### Custom DOM Elements: +### カスタムDOM要素: * [`File` Object](api/file-object.md) * `` Tag * [`window.open` 関数](api/window-open.md) -### Modules for the Main Process: +### Main Processのモジュール: * [app](api/app.md) * [autoUpdater](api/auto-updater.md) @@ -61,14 +61,14 @@ _リンクになっていないリストは未翻訳のものです。_ * webContents * [Tray](api/tray.md) -### Modules for the Renderer Process (Web Page): +### Renderer Processのモジュール (Web Page): * [desktopCapturer](api/desktop-capturer.md) * [ipcRenderer](api/ipc-renderer.md) * [remote](api/remote.md) * [webFrame](api/web-frame.md) -### Modules for Both Processes: +### 両方のProcessのモジュール : * [clipboard](api/clipboard.md) * [crashReporter](api/crash-reporter.md) @@ -76,7 +76,7 @@ _リンクになっていないリストは未翻訳のものです。_ * [screen](api/screen.md) * [shell](api/shell.md) -## Development +## 開発 * Coding Style * Source Code Directory Structure From 24ae9b0ea923fdf84999dad134a8cccb001cbe53 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 29 Feb 2016 01:38:32 +0900 Subject: [PATCH 0028/1265] Cleanup docs * Adjust 80 chars per line * Line feed after header --- docs/tutorial/testing-on-headless-ci.md | 32 +++++++++++++++++++++---- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/docs/tutorial/testing-on-headless-ci.md b/docs/tutorial/testing-on-headless-ci.md index 6b0dacf788f..ec1f4635c90 100644 --- a/docs/tutorial/testing-on-headless-ci.md +++ b/docs/tutorial/testing-on-headless-ci.md @@ -1,11 +1,27 @@ # Testing Electron with headless CI Systems (Travis CI, Jenkins) -Being based on Chromium, Electron requires a display driver to function. If Chromium can't find a display driver, Electron will simply fail to launch - and therefore not executing any of your tests, regardless of how you are running them. Testing Electron-based apps on Travis, Circle, Jenkins or similar systems requires therefore a little bit of configuration. In essence, we need to use a virtual display driver. +Being based on Chromium, Electron requires a display driver to function. +If Chromium can't find a display driver, Electron will simply fail to launch - +and therefore not executing any of your tests, regardless of how you are running +them. Testing Electron-based apps on Travis, Circle, Jenkins or similar Systems +requires therefore a little bit of configuration. In essence, we need to use +a virtual display driver. ## Configuring the Virtual Display Server -First, install [Xvfb](https://en.wikipedia.org/wiki/Xvfb). It's a virtual framebuffer, implementing the X11 display server protocol - it performs all graphical operations in memory without showing any screen output, which is exactly what we need. -Then, create a virtual xvfb screen and export an environment variable called DISPLAY that points to it. Chromium in Electron will automatically look for `$DISPLAY`, so no further configuration of your app is required. This step can be automated with Paul Betts's [xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe): Prepend your test commands with `xfvb-maybe` and the little tool will automatically configure xfvb, if required by the current system. On Windows or Mac OS X, it will simply do nothing. +First, install [Xvfb](https://en.wikipedia.org/wiki/Xvfb). +It's a virtual framebuffer, implementing the X11 display server protocol - +it performs all graphical operations in memory without showing any screen output, +which is exactly what we need. + +Then, create a virtual xvfb screen and export an environment variable +called DISPLAY that points to it. Chromium in Electron will automatically look +for `$DISPLAY`, so no further configuration of your app is required. +This step can be automated with Paul Betts's +[xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe): Prepend your test +commands with `xfvb-maybe` and the little tool will automatically configure +xfvb, if required by the current system. On Windows or Mac OS X, it will simply +do nothing. ``` ## On Windows or OS X, this just invokes electron-mocha @@ -15,6 +31,7 @@ xvfb-maybe electron-mocha ./test/*.js ``` ### Travis CI + On Travis, your `.travis.yml` should look roughly like this: ``` @@ -29,10 +46,15 @@ install: ``` ### Jenkins + For Jenkins, a [Xfvb plugin is available](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). ### Circle CI -Circle CI is awesome and has xvfb and `$DISPLAY` [already setup, so no further configuration is required](https://circleci.com/docs/environment#browsers). + +Circle CI is awesome and has xvfb and `$DISPLAY` +[already setup, so no further configuration is required](https://circleci.com/docs/environment#browsers). ### AppVeyor -AppVeyor runs on Windows, supporting Selenium, Chromium, Electron and similar tools out of the box - no configuration is required. + +AppVeyor runs on Windows, supporting Selenium, Chromium, Electron and similar +tools out of the box - no configuration is required. From 9c7bb0b3700475d7f378d6a91ae0d22ce8bd5f6d Mon Sep 17 00:00:00 2001 From: akameco Date: Tue, 1 Mar 2016 01:41:46 +0900 Subject: [PATCH 0029/1265] Fix JP docs tranlation --- docs-translations/jp/api/app.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs-translations/jp/api/app.md b/docs-translations/jp/api/app.md index 8d109937358..168f7a09399 100644 --- a/docs-translations/jp/api/app.md +++ b/docs-translations/jp/api/app.md @@ -378,6 +378,7 @@ if (browserOptions.transparent) { // No transparency, so we load a fallback that uses basic styles. win.loadURL('file://' + __dirname + '/fallback.html'); } +``` ### `app.commandLine.appendSwitch(switch[, value])` From eaac67ac603d025664b80ad127f09c4f1ca119d8 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Fri, 19 Feb 2016 12:40:41 -0500 Subject: [PATCH 0030/1265] :apple: Add 'isDarkModeEnabled' to app api --- atom/browser/api/atom_api_app.cc | 1 + atom/browser/browser.h | 3 +++ atom/browser/browser_mac.mm | 5 +++++ docs/api/app.md | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index e54d7fee176..53415c4d9c9 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -370,6 +370,7 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) + .SetMethod("isDarkModeEnabled", base::Bind(&Browser::IsDarkModeEnabled, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 2c44eaa107b..b2e1679b7fc 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -83,6 +83,9 @@ class Browser : public WindowListObserver { // Show the application. void Show(); + // Check if Dark Mode enabled. + bool IsDarkModeEnabled(); + // Bounce the dock icon. enum BounceType { BOUNCE_CRITICAL = 0, diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index bc0be22dcae..affeead255a 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -26,6 +26,11 @@ void Browser::Show() { [[AtomApplication sharedApplication] unhide:nil]; } +bool Browser::IsDarkModeEnabled() { + NSString *mode = CFBridgingRelease(CFPreferencesCopyValue((CFStringRef)@"AppleInterfaceStyle", kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost)); + return [mode isEqualToString: @"Dark"]; +} + void Browser::AddRecentDocument(const base::FilePath& path) { NSString* path_string = base::mac::FilePathToNSString(path); if (!path_string) diff --git a/docs/api/app.md b/docs/api/app.md index bdf0a8a5587..3d0790a9294 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -461,6 +461,10 @@ if (browserOptions.transparent) { } ``` +### `app.isDarkModeEnabled()` _OS X_ + +This method returns `true` if Dark Mode is enabled, and `false` otherwise. + ### `app.commandLine.appendSwitch(switch[, value])` Append a switch (with optional `value`) to Chromium's command line. From c4049cb393cc6266e5d1cc34780621b8dad2ad26 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Tue, 1 Mar 2016 15:05:44 -0500 Subject: [PATCH 0031/1265] :apple: Add 'dark-mode-changed' event to app api --- atom/browser/api/atom_api_app.cc | 9 ++++++++- atom/browser/api/atom_api_app.h | 4 ++++ atom/browser/browser.cc | 4 ++++ atom/browser/browser.h | 2 ++ atom/browser/browser_observer.h | 2 ++ atom/browser/mac/atom_application_delegate.mm | 7 +++++++ docs/api/app.md | 4 ++++ 7 files changed, 31 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 53415c4d9c9..76a5f32a245 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -282,6 +282,12 @@ void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) { Emit("gpu-process-crashed"); } +#if defined(OS_MACOSX) +void App::OnDarkModeChanged() { + Emit("dark-mode-changed"); +} +#endif + base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) { bool succeed = false; base::FilePath path; @@ -370,7 +376,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) - .SetMethod("isDarkModeEnabled", base::Bind(&Browser::IsDarkModeEnabled, browser)) + .SetMethod("isDarkModeEnabled", + base::Bind(&Browser::IsDarkModeEnabled, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index c59b9154df1..54d3f9dc743 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -71,6 +71,10 @@ class App : public AtomBrowserClient::Delegate, // content::GpuDataManagerObserver: void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; +#if defined(OS_MACOSX) + void OnDarkModeChanged() override; +#endif + // mate::Wrappable: mate::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 7a2c22ea9d2..7fbe01633b0 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -181,4 +181,8 @@ void Browser::OnWindowAllClosed() { FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed()); } +void Browser::DarkModeChanged() { + FOR_EACH_OBSERVER(BrowserObserver, observers_, OnDarkModeChanged()); +} + } // namespace atom diff --git a/atom/browser/browser.h b/atom/browser/browser.h index b2e1679b7fc..04b7a725787 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -145,6 +145,8 @@ class Browser : public WindowListObserver { // Request basic auth login. void RequestLogin(LoginHandler* login_handler); + void DarkModeChanged(); + void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); } diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index f6d76bc13fb..0577712becd 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -45,6 +45,8 @@ class BrowserObserver { // The browser requests HTTP login. virtual void OnLogin(LoginHandler* login_handler) {} + virtual void OnDarkModeChanged() {} + protected: virtual ~BrowserObserver() {} }; diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index 7662162ab61..0b9c60e7d26 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -24,6 +24,9 @@ // Don't add the "Enter Full Screen" menu item automatically. [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"]; + // Add observer to monitor the system's Dark Mode theme. + [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(darkModeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; + atom::Browser::Get()->WillFinishLaunching(); } @@ -59,4 +62,8 @@ return flag; } +- (void)darkModeChanged:(NSNotification *)notify { + atom::Browser::Get()->DarkModeChanged(); +} + @end diff --git a/docs/api/app.md b/docs/api/app.md index 3d0790a9294..3469c6b108d 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -228,6 +228,10 @@ app.on('login', function(event, webContents, request, authInfo, callback) { Emitted when the gpu process crashes. +### Event: 'dark-mode-changed' _OS X_ + +Emitted when the system's Dark Mode theme is toggled. + ## Methods The `app` object has the following methods: From f02affbc18bf1e02af030b2a0f6cf891fb0d0844 Mon Sep 17 00:00:00 2001 From: Prince J Wesley Date: Thu, 3 Mar 2016 08:37:16 +0530 Subject: [PATCH 0032/1265] :bug: Add platform predicate for menu item action --- atom/browser/api/lib/menu-item.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/api/lib/menu-item.js b/atom/browser/api/lib/menu-item.js index d58a0fad2c7..eef8881cf52 100644 --- a/atom/browser/api/lib/menu-item.js +++ b/atom/browser/api/lib/menu-item.js @@ -67,7 +67,7 @@ MenuItem = (function() { } } else if (typeof click === 'function') { return click(_this, focusedWindow); - } else if (typeof _this.selector === 'string') { + } else if (typeof _this.selector === 'string' && process.platform === 'darwin') { return Menu.sendActionToFirstResponder(_this.selector); } }; From b6958e5221590f8a67b20b182ca462af47263691 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 29 Feb 2016 01:30:43 +0900 Subject: [PATCH 0033/1265] Update as upstream [ci skip] --- README-ko.md | 5 +- docs-translations/ko-KR/README.md | 1 + docs-translations/ko-KR/api/web-contents.md | 23 +++++--- docs-translations/ko-KR/api/web-view-tag.md | 10 +++- .../ko-KR/tutorial/testing-on-headless-ci.md | 58 +++++++++++++++++++ 5 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 docs-translations/ko-KR/tutorial/testing-on-headless-ci.md diff --git a/README-ko.md b/README-ko.md index b9085828d46..28bb02a1637 100644 --- a/README-ko.md +++ b/README-ko.md @@ -71,8 +71,9 @@ API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝 - Atom 포럼의 [`electron`](http://discuss.atom.io/c/electron) 카테고리 - Freenode 채팅의 `#atom-shell` 채널 - Slack의 [`Atom`](http://atom-slack.herokuapp.com/) 채널 -- [`electron-br`](https://electron-br.slack.com) *(브라질 포르투갈어)* 커뮤니티 -- [`electron-kr`](http://www.meetup.com/electron-kr/) *(한국어)* 커뮤니티 +- [`electron-br`](https://electron-br.slack.com) *(브라질)* 커뮤니티 +- [`electron-kr`](http://www.meetup.com/electron-kr/) *(한국)* 커뮤니티 +- [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(일본)* 커뮤니티 [awesome-electron](https://github.com/sindresorhus/awesome-electron) 프로젝트에 커뮤니티가 운영중인 유용한 예제 어플리케이션과 도구, 리소스가 있으니 한번 참고해 보시기 diff --git a/docs-translations/ko-KR/README.md b/docs-translations/ko-KR/README.md index 6f4a1c520f5..8c5912f604b 100644 --- a/docs-translations/ko-KR/README.md +++ b/docs-translations/ko-KR/README.md @@ -30,6 +30,7 @@ Electron에 대해 자주 묻는 질문이 있습니다. 이슈를 생성하기 * [개발자 도구 확장 기능](tutorial/devtools-extension.md) * [Pepper 플래시 플러그인 사용하기](tutorial/using-pepper-flash-plugin.md) * [Widevine CDM 플러그인 사용하기](tutorial/using-widevine-cdm-plugin.md) +* [Headless CI 시스템에서 테스팅하기 (Travis, Jenkins)](tutorial/testing-on-headless-ci.md) ## 튜토리얼 diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 6e41f31155c..ed2f05f1d5a 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -421,10 +421,12 @@ var currentURL = win.webContents.getURL(); CSS 코드를 현재 웹 페이지에 삽입합니다. -### `webContents.executeJavaScript(code[, userGesture])` +### `webContents.executeJavaScript(code[, userGesture, callback])` * `code` String * `userGesture` Boolean (optional) +* `callback` Function (optional) - 스크립트의 실행이 완료되면 호출됩니다. + * `result` 페이지에서 자바스크립트 코드를 실행합니다. @@ -646,14 +648,14 @@ mainWindow.webContents.on('devtools-opened', function() { 개발자 도구가 열려있는지 여부를 반환합니다. -### `webContents.toggleDevTools()` - -개발자 도구를 토글합니다. - ### `webContents.isDevToolsFocused()` 개발자 도구에 포커스 되어있는지 여부를 반환합니다. +### `webContents.toggleDevTools()` + +개발자 도구를 토글합니다. + ### `webContents.inspectElement(x, y)` * `x` Integer @@ -758,9 +760,10 @@ Input `event`를 웹 페이지로 전송합니다. * `keyCode` Char or String (**required**) - 키보드 이벤트로 보내지는 문자. 단일 UTF-8 문자를 사용할 수 있고 이벤트를 발생시키는 다음 키 중 하나를 포함할 수 있습니다: - `enter`, `backspace`, `delete`, `tab`, `escape`, `control`, `alt`, `shift`, - `end`, `home`, `insert`, `left`, `up`, `right`, `down`, `pageUp`, `pageDown`, - `printScreen` + `enter`, `backspace`, `delete`, `tab`, `escape`, `control`, `alt`, `altgr` + (Windows 전용), `shift`, `end`, `home`, `insert`, `left`, `up`, `right`, + `down`, `pageUp`, `pageDown`, `printScreen`, `meta`, `cmd` (OSX 전용), + `command` (OSX 전용), `option` (OSX 전용) 마우스 이벤트들에 대해서는 `event` 객체는 다음 속성들을 사용할 수 있습니다: @@ -832,6 +835,10 @@ win.webContents.on('did-finish-load', function() { 이 webContents에서 사용하는 [session](session.md) 객체를 반환합니다. +### `webContents.hostWebContents` + +현재 `WebContents`를 소유하는 `WebContents`를 반환합니다. + ### `webContents.devToolsWebContents` 이 `WebContents`에 대한 개발자 도구의 `WebContents`를 가져옵니다. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index 30da9f253b4..bda18b78898 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -272,12 +272,14 @@ Webview에 웹 페이지 `url`을 로드합니다. `url`은 `http://`, `file://` 페이지에 CSS를 삽입합니다. -### `.executeJavaScript(code[, userGesture])` +### `.executeJavaScript(code[, userGesture, callback])` * `code` String * `userGesture` Boolean +* `callback` Function (optional) - 스크립트의 실행이 완료되면 호출됩니다. + * `result` -페이지에서 자바스크립트 `code`를 실행합니다. +페이지에서 자바스크립트 코드를 실행합니다. 만약 `userGesture`가 `true`로 설정되어 있으면 페이지에 유저 제스쳐 컨텍스트를 만듭니다. 이 옵션을 활성화 시키면 `requestFullScreen`와 같은 HTML API에서 유저의 승인을 @@ -427,6 +429,10 @@ Webview 페이지를 PDF 형식으로 인쇄합니다. `event` 객체에 대해 자세히 알아보려면 [webContents.sendInputEvent](web-contents.md##webcontentssendinputeventevent)를 참고하세요. +### `.getWebContents()` + +이 `webview`에 해당하는 [WebContents](web-contents.md)를 반환합니다. + ## DOM 이벤트 `webview` 태그는 다음과 같은 DOM 이벤트를 가지고 있습니다: diff --git a/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md new file mode 100644 index 00000000000..be88be1cec6 --- /dev/null +++ b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md @@ -0,0 +1,58 @@ +# Headless CI 시스템에서 테스팅하기 (Travis, Jenkins) (Travis CI, Jenkins) + +Chromium을 기반으로 한 Electron은 작업을 위해 디스플레이 드라이버가 필요합니다. +만약 Chromium이 디스플레이 드라이버를 찾기 못한다면, Electron은 그대로 실행에 +실패할 것입니다. 따라서 실행하는 방법에 관계없이 모든 테스트를 실행하지 못하게 됩니다. +Electron 기반 어플리케이션을 Travis, Circle, Jenkins 또는 유사한 시스템에서 테스팅을 +진행하려면 약간의 설정이 필요합니다. 요점만 말하자면, 가상 디스플레이 드라이버가 +필요합니다. + +## 가상 디스플레이 드라이버 설정 + +먼저, [Xvfb](https://en.wikipedia.org/wiki/Xvfb)를 설치합니다. 이것은 X11 +디스플레이 서버 프로토콜의 구현이며 모든 그래픽 작업을 스크린 출력없이 인-메모리에서 +수행하는 가상 프레임버퍼입니다. 정확히 우리가 필요로 하는 것입니다. + +그리고, 가상 xvfb 스크린을 생성하고 DISPLAY라고 불리우는 환경 변수를 지정합니다. +Electron의 Chromium은 자동적으로 `$DISPLAY` 변수를 찾습니다. 따라서 앱의 추가적인 +다른 설정이 필요하지 않습니다. 이러한 작업은 Paul Betts의 +[xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe)를 통해 자동화 할 수 +있습니다: `xfvb-maybe`를 테스트 커맨드 앞에 추가하고 현재 시스템에서 요구하면 +이 작은 툴이 자동적으로 xfvb를 설정합니다. Windows와 Mac OS X에선 간단히 아무 작업도 +하지 않습니다. + +``` +## Windows와 OS X에선, 그저 electron-mocha를 호출합니다 +## Linux에선, 현재 headless 환경에 있는 경우 +## xvfb-run electron-mocha ./test/*.js와 같습니다 +xvfb-maybe electron-mocha ./test/*.js +``` + +### Travis CI + +Travis에선, `.travis.yml`이 대충 다음과 같이 되어야 합니다: + +``` +addons: + apt: + packages: + - xvfb + +install: + - export DISPLAY=':99.0' + - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +``` + +### Jenkins + +Jenkins는 [Xfvb 플러그인이 존재합니다](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). + +### Circle CI + +Circle CI는 멋지게도 이미 xvfb와 `$DISPLY` 변수가 준비되어 있습니다. 따라서 +[추가적인 설정이 필요하지](https://circleci.com/docs/environment#browsers) 않습니다. + +### AppVeyor + +AppVeyor는 Windows에서 작동하기 때문에 Selenium, Chromium, Electron과 그 비슷한 +툴들을 복잡한 과정 없이 모두 지원합니다. - 설정이 필요하지 않습니다. From b46fc8bc4c16f9defdc06e8f9b724f2f91ee605b Mon Sep 17 00:00:00 2001 From: Victor Zhu Date: Thu, 3 Mar 2016 15:42:14 -0500 Subject: [PATCH 0034/1265] Add Pepper Flash doc and match doc style - Add Pepper Flash plugin documentation - Use and match the same documentaion style for other CN docs. - Fix some typos and grammar. --- .../tutorial/application-distribution.md | 5 +- .../zh-CN/tutorial/application-packaging.md | 84 +++++++++++-------- .../zh-CN/tutorial/debugging-main-process.md | 4 +- .../zh-CN/tutorial/devtools-extension.md | 22 ++--- .../zh-CN/tutorial/supported-platforms.md | 2 +- .../tutorial/using-native-node-modules.md | 27 +++--- .../tutorial/using-pepper-flash-plugin.md | 48 +++++++++++ .../tutorial/using-selenium-and-webdriver.md | 40 ++++----- 8 files changed, 149 insertions(+), 83 deletions(-) create mode 100644 docs-translations/zh-CN/tutorial/using-pepper-flash-plugin.md diff --git a/docs-translations/zh-CN/tutorial/application-distribution.md b/docs-translations/zh-CN/tutorial/application-distribution.md index dcfe4d240ee..f3cf3692b5d 100644 --- a/docs-translations/zh-CN/tutorial/application-distribution.md +++ b/docs-translations/zh-CN/tutorial/application-distribution.md @@ -1,6 +1,7 @@ # 应用部署 -为了使用Electron部署你的应用程序,你存放应用程序的文件夹需要叫做 `app` 并且需要放在 Electron 的资源文件夹下(在 OS X 中是指 `Electron.app/Contents/Resources/`,在 Linux 和 Windows 中是指 `resources/`) +为了使用 Electron 部署你的应用程序,你存放应用程序的文件夹需要叫做 `app` 并且需要放在 Electron 的 +资源文件夹下(在 OS X 中是指 `Electron.app/Contents/Resources/`,在 Linux 和 Windows 中是指 `resources/`) 就像这样: 在 OS X 中: @@ -56,7 +57,7 @@ electron/resources/ 你可以将 `electron.exe` 改成任意你喜欢的名字,然后可以使用像 [rcedit](https://github.com/atom/rcedit) -编辑它的icon和其他信息。 +编辑它的 icon 和其他信息。 ### OS X diff --git a/docs-translations/zh-CN/tutorial/application-packaging.md b/docs-translations/zh-CN/tutorial/application-packaging.md index ee4b7bf63b8..13a24d2d1c3 100644 --- a/docs-translations/zh-CN/tutorial/application-packaging.md +++ b/docs-translations/zh-CN/tutorial/application-packaging.md @@ -1,34 +1,38 @@ # 应用打包 -为舒缓Windows下路径名过长的问题[issues](https://github.com/joyent/node/issues/6960), 也略对`require`加速以及简单隐匿你的源代码, 你可以通过极小的源代码改动将你的应用打包成[asar][asar]. +为舒缓 Windows 下路径名过长的问题[issues](https://github.com/joyent/node/issues/6960), +也略对 `require` 加速以及简单隐匿你的源代码,你可以通过极小的源代码改动将你的应用打包成 [asar][asar]。 -## 生成`asar`包 +## 生成 `asar` 包 -[asar][asar]是一种将多个文件合并成一个文件的类tar风格的归档格式。 Electron可以无需解压,即从其中读取任意文件内容。 +[asar][asar] 是一种将多个文件合并成一个文件的类 tar 风格的归档格式。 +Electron 可以无需解压,即从其中读取任意文件内容。 -参照如下步骤将你的应用打包成`asar`: +参照如下步骤将你的应用打包成 `asar`: -### 1. 安装asar +### 1. 安装 asar ```bash $ npm install -g asar ``` -### 2. 用`asar pack`打包 +### 2. 用 `asar pack` 打包 ```bash $ asar pack your-app app.asar ``` -## 使用`asar`包 +## 使用 `asar` 包 -在Electron中有两类APIs:Node.js提供的Node APIs和Chromium提供的Web APIs。这两种APIs都支持从`asar`包中读取文件。 +在 Electron 中有两类 APIs:Node.js 提供的 Node API 和 Chromium 提供的 Web API。 +这两种 API 都支持从 `asar` 包中读取文件。 ### Node API -由于Electron中打了特别补丁, Node APIs中如`fs.readFile`或者`require`之类的方法可以将`asar`视之为虚拟文件夹,读取`asar`里面的文件就和从真实的文件系统中读取一样。 +由于 Electron 中打了特别补丁, Node API 中如 `fs.readFile` 或者 `require` 之类 +的方法可以将 `asar` 视之为虚拟文件夹,读取 `asar` 里面的文件就和从真实的文件系统中读取一样。 -例如,假设我们在`/path/to`文件夹下有个`example.asar`包: +例如,假设我们在 `/path/to` 文件夹下有个 `example.asar` 包: ```bash $ asar list /path/to/example.asar @@ -40,27 +44,27 @@ $ asar list /path/to/example.asar /static/jquery.min.js ``` -从`asar`包读取一个文件: +从 `asar` 包读取一个文件: ```javascript const fs = require('fs'); fs.readFileSync('/path/to/example.asar/file.txt'); ``` -列出`asar`包中根目录下的所有文件: +列出 `asar` 包中根目录下的所有文件: ```javascript const fs = require('fs'); fs.readdirSync('/path/to/example.asar'); ``` -使用`asar`包中的一个模块: +使用 `asar` 包中的一个模块: ```javascript require('/path/to/example.asar/dir/module.js'); ``` -你也可以使用`BrowserWindow`来显示一个`asar`包里的web页面: +你也可以使用 `BrowserWindow` 来显示一个 `asar` 包里的 web 页面: ```javascript const BrowserWindow = require('electron').BrowserWindow; @@ -70,9 +74,9 @@ win.loadURL('file:///path/to/example.asar/static/index.html'); ### Web API -在Web页面里,用`file:`协议可以获取`asar`包中文件。和Node API一样,视`asar`包如虚拟文件夹。 +在 Web 页面里,用 `file:` 协议可以获取 `asar` 包中文件。和 Node API 一样,视 `asar` 包如虚拟文件夹。 -例如,用`$.get`获取文件: +例如,用 `$.get` 获取文件: ```html ``` -### 像“文件”那样处理`asar`包 +### 像“文件”那样处理 `asar` 包 -有些场景,如:核查`asar`包的校验和,我们需要像读取“文件”那样读取`asar`包的内容(而不是当成虚拟文件夹)。你可以使用内置的`original-fs`(提供和`fs`一样的APIs)模块来读取`asar`包的真实信息。 +有些场景,如:核查 `asar` 包的校验和,我们需要像读取“文件”那样读取 `asar` 包的内容(而不是当成虚拟文件夹)。 +你可以使用内置的 `original-fs` (提供和 `fs` 一样的 API)模块来读取 `asar` 包的真实信息。 ```javascript var originalFs = require('original-fs'); originalFs.readFileSync('/path/to/example.asar'); ``` -## Node API缺陷 +## Node API 缺陷 -尽管我们已经尽了最大努力使得`asar`包在Node API下的应用尽可能的趋向于真实的目录结构,但仍有一些底层Node API我们无法保证其正常工作。 +尽管我们已经尽了最大努力使得 `asar` 包在 Node API 下的应用尽可能的趋向于真实的目录结构,但仍有一些底层 Node API 我们无法保证其正常工作。 -### `asar`包是只读的 +### `asar` 包是只读的 -`asar`包中的内容不可更改,所以Node APIs里那些可以用来修改文件的方法在对待`asar`包时都无法正常工作。 +`asar` 包中的内容不可更改,所以 Node APIs 里那些可以用来修改文件的方法在对待 `asar` 包时都无法正常工作。 -### Working Directory在`asar`包中无效 +### Working Directory 在 `asar` 包中无效 -尽管`asar`包是虚拟文件夹,但其实并没有真实的目录架构对应在文件系统里,所以你不可能将working Directory设置成`asar`包里的一个文件夹。将`asar`中的文件夹以`cwd`形式作为参数传入一些API中也会报错。 +尽管 `asar` 包是虚拟文件夹,但其实并没有真实的目录架构对应在文件系统里,所以你不可能将 working Directory +设置成 `asar` 包里的一个文件夹。将 `asar` 中的文件夹以 `cwd` 形式作为参数传入一些 API 中也会报错。 -### API中的额外“开箱” +### API 中的额外“开箱” -大部分`fs`API可以无需解压即从`asar`包中读取文件或者文件的信息,但是在处理一些依赖真实文件路径的底层系统方法时,Electron会将所需文件解压到临时目录下,然后将临时目录下的真实文件路径传给底层系统方法使其正常工作。 对于这类API,耗费会略多一些。 +大部分 `fs` API 可以无需解压即从 `asar` 包中读取文件或者文件的信息,但是在处理一些依赖真实文件路径的底层 +系统方法时,Electron 会将所需文件解压到临时目录下,然后将临时目录下的真实文件路径传给底层系统方法使其正 +常工作。 对于这类API,耗费会略多一些。 -以下是一些需要额外解压的APIs: +以下是一些需要额外解压的 API: * `child_process.execFile` * `child_process.execFileSync` @@ -116,26 +124,32 @@ originalFs.readFileSync('/path/to/example.asar'); * `fs.openSync` * `process.dlopen` - `require`native模块时用到 -### `fs.stat`获取的stat信息不可靠 +### `fs.stat` 获取的 stat 信息不可靠 -对`asar`包中的文件取`fs.stat`,返回的`Stats`对象不是精确值,因为这些文件不是真实存在于文件系统里。所以除了文件大小和文件类型以外,你不应该依赖`Stats`对象的值。 +对 `asar` 包中的文件取 `fs.stat`,返回的 `Stats` 对象不是精确值,因为这些文件不是真实存在于文件系 +统里。所以除了文件大小和文件类型以外,你不应该依赖 `Stats` 对象的值。 -### 执行`asar`包中的程序 +### 执行 `asar` 包中的程序 -Node中有一些可以执行程序的API,如`child_process.exec`,`child_process.spawn`和`child_process.execFile`等,但只有`execFile`可以执行`asar`包中的程序。 +Node 中有一些可以执行程序的 API,如 `child_process.exec`,`child_process.spawn` 和 `child_process.execFile` 等, +但只有 `execFile` 可以执行 `asar` 包中的程序。 -因为`exec`和`spawn`允许`command`替代`file`作为输入,而`command`是需要在shell下执行的,目前没有可靠的方法来判断`command`中是否在操作一个`asar`包中的文件,而且即便可以判断,我们依旧无法保证可以在无任何副作用的情况下替换`command`中的文件路径。 +因为 `exec` 和 `spawn` 允许 `command` 替代 `file` 作为输入,而 `command` 是需要在 shell 下执行的,目前没有 +可靠的方法来判断 `command` 中是否在操作一个 `asar` 包中的文件,而且即便可以判断,我们依旧无法保证可以在无任何 +副作用的情况下替换 `command` 中的文件路径。 ## 打包时排除文件 -如上所述,一些Node API会在调用时将文件解压到文件系统中,除了效率问题外,也有可能引起杀毒软件的注意! +如上所述,一些 Node API 会在调用时将文件解压到文件系统中,除了效率问题外,也有可能引起杀毒软件的注意! -为解决这个问题,你可以在生成`asar`包时使用`--unpack`选项来排除一些文件,使其不打包到`asar`包中,下面是如何排除一些用作共享用途的native模块的方法: +为解决这个问题,你可以在生成 `asar` 包时使用 `--unpack` 选项来排除一些文件,使其不打包到 `asar` 包中, +下面是如何排除一些用作共享用途的 native 模块的方法: ```bash $ asar pack app app.asar --unpack *.node ``` -经过上述命令后,除了生成的`app.asar`包以外,还有一个包含了排除文件的`app.asar.unpacked`文件夹,你需要将这个文件夹一起拷贝,提供给用户。 +经过上述命令后,除了生成的 `app.asar` 包以外,还有一个包含了排除文件的 `app.asar.unpacked` 文件夹, +你需要将这个文件夹一起拷贝,提供给用户。 [asar]: https://github.com/atom/asar diff --git a/docs-translations/zh-CN/tutorial/debugging-main-process.md b/docs-translations/zh-CN/tutorial/debugging-main-process.md index f971a40892f..e3eec0c5b39 100644 --- a/docs-translations/zh-CN/tutorial/debugging-main-process.md +++ b/docs-translations/zh-CN/tutorial/debugging-main-process.md @@ -1,6 +1,6 @@ # 主进程调试 -浏览器窗口的开发工具仅能调试渲染器的进程脚本(比如web 页面)。为了提供一个可以调试主进程 +浏览器窗口的开发工具仅能调试渲染器的进程脚本(比如 web 页面)。为了提供一个可以调试主进程 的方法,Electron 提供了 `--debug` 和 `--debug-brk` 开关。 ## 命令行开关 @@ -18,7 +18,7 @@ ## 使用 node-inspector 来调试 -__备注:__ Electron 目前对 node-inspector支持的不是特别好, +__备注:__ Electron 目前对 node-inspector 支持的不是特别好, 如果你通过 node-inspector 的 console 来检查 `process` 对象,主进程就会崩溃。 ### 1. 确认你已经安装了 [node-gyp 所需工具](https://github.com/nodejs/node-gyp#installation) diff --git a/docs-translations/zh-CN/tutorial/devtools-extension.md b/docs-translations/zh-CN/tutorial/devtools-extension.md index 9a2d9fc8832..0270eae2955 100644 --- a/docs-translations/zh-CN/tutorial/devtools-extension.md +++ b/docs-translations/zh-CN/tutorial/devtools-extension.md @@ -1,10 +1,10 @@ # DevTools扩展 -为了使调试更容易,Electron原生支持[Chrome DevTools Extension][devtools-extension]。 +为了使调试更容易,Electron 原生支持 [Chrome DevTools Extension][devtools-extension]。 -对于大多数DevTools的扩展,你可以直接下载源码,然后通过`BrowserWindow.addDevToolsExtension`API加载它们。Electron会记住已经加载了哪些扩展,所以你不需要每次创建一个新window时都调用`BrowserWindow.addDevToolsExtension`API。 +对于大多数DevTools的扩展,你可以直接下载源码,然后通过 `BrowserWindow.addDevToolsExtension` API 加载它们。Electron会记住已经加载了哪些扩展,所以你不需要每次创建一个新window时都调用 `BrowserWindow.addDevToolsExtension` API。 -** 注:React DevTools目前不能直接工作,详情留意[https://github.com/atom/electron/issues/915](https://github.com/atom/electron/issues/915) ** +** 注:React DevTools目前不能直接工作,详情留意 [https://github.com/atom/electron/issues/915](https://github.com/atom/electron/issues/915) ** 例如,要用[React DevTools Extension](https://github.com/facebook/react-devtools),你得先下载他的源码: @@ -13,33 +13,33 @@ $ cd /some-directory $ git clone --recursive https://github.com/facebook/react-devtools.git ``` -参考[`react-devtools/shells/chrome/Readme.md`](https://github.com/facebook/react-devtools/blob/master/shells/chrome/Readme.md)来编译这个扩展源码。 +参考 [`react-devtools/shells/chrome/Readme.md`](https://github.com/facebook/react-devtools/blob/master/shells/chrome/Readme.md) 来编译这个扩展源码。 -然后你就可以在任意页面的DevTools里加载React DevTools了,通过控制台输入如下命令加载扩展: +然后你就可以在任意页面的 DevTools 里加载 React DevTools 了,通过控制台输入如下命令加载扩展: ```javascript const BrowserWindow = require('electron').remote.BrowserWindow; BrowserWindow.addDevToolsExtension('/some-directory/react-devtools/shells/chrome'); ``` -要卸载扩展,可以调用`BrowserWindow.removeDevToolsExtension`API(扩展名作为参数传入),该扩展在下次打开DevTools时就不会加载了: +要卸载扩展,可以调用 `BrowserWindow.removeDevToolsExtension` API (扩展名作为参数传入),该扩展在下次打开DevTools时就不会加载了: ```javascript BrowserWindow.removeDevToolsExtension('React Developer Tools'); ``` -## DevTools扩展的格式 +## DevTools 扩展的格式 -理论上,Electron可以加载所有为chrome浏览器编写的DevTools扩展,但它们必须存放在文件夹里。那些以`crx`形式发布的扩展是不能被加载的,除非你把它们解压到一个文件夹里。 +理论上,Electron 可以加载所有为 chrome 浏览器编写的 DevTools 扩展,但它们必须存放在文件夹里。那些以 `crx` 形式发布的扩展是不能被加载的,除非你把它们解压到一个文件夹里。 ## 后台运行(background pages) -Electron目前并不支持chrome扩展里的后台运行(background pages)功能,所以那些依赖此特性的DevTools扩展在Electron里可能无法正常工作。 +Electron 目前并不支持 chrome 扩展里的后台运行(background pages)功能,所以那些依赖此特性的 DevTools 扩展在 Electron 里可能无法正常工作。 ## `chrome.*` APIs -有些chrome扩展使用了`chrome.*`APIs,而且这些扩展在Electron中需要额外实现一些代码才能使用,所以并不是所有的这类扩展都已经在Electron中实现完毕了。 +有些 chrome 扩展使用了 `chrome.*`APIs,而且这些扩展在 Electron 中需要额外实现一些代码才能使用,所以并不是所有的这类扩展都已经在 Electron 中实现完毕了。 -考虑到并非所有的`chrome.*`APIs都实现完毕,如果DevTools正在使用除了`chrome.devtools.*`之外的其它APIs,这个扩展很可能无法正常工作。你可以通过报告这个扩展的异常信息,这样做方便我们对该扩展的支持。 +考虑到并非所有的 `chrome.*`APIs 都实现完毕,如果 DevTools 正在使用除了 `chrome.devtools.*` 之外的其它 APIs,这个扩展很可能无法正常工作。你可以通过报告这个扩展的异常信息,这样做方便我们对该扩展的支持。 [devtools-extension]: https://developer.chrome.com/extensions/devtools diff --git a/docs-translations/zh-CN/tutorial/supported-platforms.md b/docs-translations/zh-CN/tutorial/supported-platforms.md index d4d42ec03ff..e03ccd82364 100644 --- a/docs-translations/zh-CN/tutorial/supported-platforms.md +++ b/docs-translations/zh-CN/tutorial/supported-platforms.md @@ -20,7 +20,7 @@ Ubuntu 12.04 下编译的,`arm` 版的二进制文件是在 ARM v7(硬浮点 Debian Wheezy 版本的 NEON)下完成的。 预编译二进制文件是否能够运行,取决于其中是否包括了编译平台链接的库,所以只有 Ubuntu 12.04 -可以保证正常工作,但是以下的平台也被证实可以运行 Electron的预编译版本: +可以保证正常工作,但是以下的平台也被证实可以运行 Electron 的预编译版本: * Ubuntu 12.04 及更新 * Fedora 21 diff --git a/docs-translations/zh-CN/tutorial/using-native-node-modules.md b/docs-translations/zh-CN/tutorial/using-native-node-modules.md index e03e7b8948a..0fe67d4a08a 100644 --- a/docs-translations/zh-CN/tutorial/using-native-node-modules.md +++ b/docs-translations/zh-CN/tutorial/using-native-node-modules.md @@ -1,12 +1,12 @@ # 使用原生模块 -Electron同样也支持原生模块,但由于和官方的Node相比使用了不同的V8引擎,如果你想编译原生模块,则需要手动设置Electron的headers的位置。 +Electron 同样也支持原生模块,但由于和官方的 Node 相比使用了不同的 V8 引擎,如果你想编译原生模块,则需要手动设置 Electron 的 headers 的位置。 ## 原生Node模块的兼容性 -当Node开始换新的V8引擎版本时,原生模块可能“坏”掉。为确保一切工作正常,你需要检查你想要使用的原生模块是否被Electron内置的Node支持。你可以在[这里](https://github.com/atom/electron/releases)查看Electron内置的Node版本,或者使用`process.version`(参考:[快速入门](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md))查看。 +当 Node 开始换新的V8引擎版本时,原生模块可能“坏”掉。为确保一切工作正常,你需要检查你想要使用的原生模块是否被 Electron 内置的 Node 支持。你可以在[这里](https://github.com/atom/electron/releases)查看 Electron 内置的 Node 版本,或者使用 `process.version` (参考:[快速入门](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md))查看。 -考虑到[NAN](https://github.com/nodejs/nan/)可以使你的开发更容易对多版本Node的支持,建议使用它来开发你自己的模块。你也可以使用[NAN](https://github.com/nodejs/nan/)来移植旧的模块到新的Node版本,以使它们可以在新的Electron下良好工作。 +考虑到 [NAN](https://github.com/nodejs/nan/) 可以使你的开发更容易对多版本 Node 的支持,建议使用它来开发你自己的模块。你也可以使用 [NAN](https://github.com/nodejs/nan/) 来移植旧的模块到新的 Nod e版本,以使它们可以在新的 Electron 下良好工作。 ## 如何安装原生模块 @@ -14,7 +14,7 @@ Electron同样也支持原生模块,但由于和官方的Node相比使用了 ### 最简单方式 -最简单的方式就是通过[`electron-rebuild`](https://github.com/paulcbetts/electron-rebuild)包重新编译原生模块,它帮你自动完成了下载headers、编译原生模块等步骤: +最简单的方式就是通过 [`electron-rebuild`](https://github.com/paulcbetts/electron-rebuild) 包重新编译原生模块,它帮你自动完成了下载 headers、编译原生模块等步骤: ```sh npm install --save-dev electron-rebuild @@ -26,9 +26,9 @@ npm install --save-dev electron-rebuild .\node_modules\.bin\electron-rebuild.cmd ``` -### 通过npm安装 +### 通过 npm 安装 -你当然也可以通过`npm`安装原生模块。大部分步骤和安装普通模块时一样,除了以下一些系统环境变量你需要自己操作: +你当然也可以通过 `npm` 安装原生模块。大部分步骤和安装普通模块时一样,除了以下一些系统环境变量你需要自己操作: ```bash export npm_config_disturl=https://atom.io/download/atom-shell @@ -38,16 +38,19 @@ export npm_config_runtime=electron HOME=~/.electron-gyp npm install module-name ``` -### 通过node-gyp安装 +### 通过 node-gyp 安装 -你需要告诉`node-gyp`去哪下载Electron的headers,以及下载什么版本: +你需要告诉 `node-gyp` 去哪下载 Electron 的 headers,以及下载什么版本: ```bash $ cd /path-to-module/ $ HOME=~/.electron-gyp node-gyp rebuild --target=0.29.1 --arch=x64 --dist-url=https://atom.io/download/atom-shell ``` -`HOME=~/.electron-gyp`设置了去哪找开发时的headers。 -`--target=0.29.1`设置了Electron的版本 -`--dist-url=...`设置了Electron的headers的下载地址 -`--arch=x64`设置了该模块为适配64bit操作系统而编译 +`HOME=~/.electron-gyp` 设置去哪找开发时的 headers。 + +`--target=0.29.1` 设置了 Electron 的版本 + +`--dist-url=...` 设置了 Electron 的 headers 的下载地址 + +`--arch=x64` 设置了该模块为适配64位操作系统而编译 diff --git a/docs-translations/zh-CN/tutorial/using-pepper-flash-plugin.md b/docs-translations/zh-CN/tutorial/using-pepper-flash-plugin.md new file mode 100644 index 00000000000..ce1f210c5c9 --- /dev/null +++ b/docs-translations/zh-CN/tutorial/using-pepper-flash-plugin.md @@ -0,0 +1,48 @@ +# 使用 Pepper Flash 插件 + +Electron 现在支持 Pepper Flash 插件。要在 Electron 里面使用 Pepper Flash 插件,你需 +要手动设置 Pepper Flash 的路径和在你的应用里启用 Pepper Flash。 + +## 保留一份 Flash 插件的副本 + +在 OS X 和 Linux 上,你可以在 Chrome 浏览器的 `chrome://plugins` 页面上找到 Pepper +Flash 的插件信息。插件的路径和版本会对 Election 对其的支持有帮助。你也可以把插件 +复制到另一个路径以保留一份副本。 + +## 添加插件在 Electron 里的开关 + +你可以直接在命令行中用 `--ppapi-flash-path` 和 `ppapi-flash-version` 或者 +在 app 的准备事件前调用 `app.commandLine.appendSwitch` 这个 method。同时, +添加 `browser-window` 的插件开关。 +例如: + +```javascript +// Specify flash path. 设置 flash 路径 +// On Windows, it might be /path/to/pepflashplayer.dll +// On OS X, /path/to/PepperFlashPlayer.plugin +// On Linux, /path/to/libpepflashplayer.so +app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'); + +// Specify flash version, for example, v17.0.0.169 设置版本号 +app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169'); + +app.on('ready', function() { + mainWindow = new BrowserWindow({ + 'width': 800, + 'height': 600, + 'web-preferences': { + 'plugins': true + } + }); + mainWindow.loadURL('file://' + __dirname + '/index.html'); + // Something else +}); +``` + +## 使用 `` 标签启用插件 + +在 `` 标签里添加 `plugins` 属性。 + +```html + +``` diff --git a/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md b/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md index c05a3190eea..0a0b29c854f 100644 --- a/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md @@ -1,18 +1,18 @@ -# 使用Selenium和WebDriver +# 使用 Selenium 和 WebDriver 引自[ChromeDriver - WebDriver for Chrome][chrome-driver]: -> WebDriver是一款开源的支持多浏览器的自动化测试工具。它提供了操作网页、用户输入、JavaScript执行等能力。ChromeDriver是一个实现了WebDriver与Chromium联接协议的独立服务。它也是由开发了Chromium和WebDriver的团队开发的。 +> WebDriver 是一款开源的支持多浏览器的自动化测试工具。它提供了操作网页、用户输入、JavaScript 执行等能力。ChromeDriver 是一个实现了 WebDriver 与 Chromium 联接协议的独立服务。它也是由开发了 Chromium 和 WebDriver 的团队开发的。 -为了能够使`chromedriver`和Electron一起正常工作,我们需要告诉它Electron在哪,并且让它相信Electron就是Chrome浏览器。 +为了能够使 `chromedriver` 和 Electron 一起正常工作,我们需要告诉它 Electron 在哪,并且让它相信 Electron 就是 Chrome 浏览器。 -## 通过WebDriverJs配置 +## 通过 WebDriverJs 配置 -[WebDriverJs](https://code.google.com/p/selenium/wiki/WebDriverJs) 是一个可以配合WebDriver做测试的node模块,我们会用它来做个演示。 +[WebDriverJs](https://code.google.com/p/selenium/wiki/WebDriverJs) 是一个可以配合 WebDriver 做测试的 node 模块,我们会用它来做个演示。 -### 1. 启动ChromeDriver +### 1. 启动 ChromeDriver -首先,你要下载`chromedriver`,然后运行以下命令: +首先,你要下载 `chromedriver`,然后运行以下命令: ```bash $ ./chromedriver @@ -20,17 +20,17 @@ Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -记住`9515`这个端口号,我们后面会用到 +记住 `9515` 这个端口号,我们后面会用到 -### 2. 安装WebDriverJS +### 2. 安装 WebDriverJS ```bash $ npm install selenium-webdriver ``` -### 3. 联接到ChromeDriver +### 3. 联接到 ChromeDriver -在Electron下使用`selenium-webdriver`和其平时的用法并没有大的差异,只是你需要手动设置连接ChromeDriver,以及Electron的路径: +在 Electron 下使用 `selenium-webdriver` 和其平时的用法并没有大的差异,只是你需要手动设置连接 ChromeDriver,以及 Electron 的路径: ```javascript const webdriver = require('selenium-webdriver'); @@ -59,13 +59,13 @@ driver.wait(function() { driver.quit(); ``` -## 通过WebdriverIO配置 +## 通过 WebdriverIO 配置 -[WebdriverIO](http://webdriver.io/)也是一个配合WebDriver用来测试的node模块 +[WebdriverIO](http://webdriver.io/) 也是一个配合 WebDriver 用来测试的 node 模块 -### 1. 启动ChromeDriver +### 1. 启动 ChromeDriver -首先,下载`chromedriver`,然后运行以下命令: +首先,下载 `chromedriver`,然后运行以下命令: ```bash $ chromedriver --url-base=wd/hub --port=9515 @@ -73,15 +73,15 @@ Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed. ``` -记住`9515`端口,后面会用到 +记住 `9515` 端口,后面会用到 -### 2. 安装WebdriverIO +### 2. 安装 WebdriverIO ```bash $ npm install webdriverio ``` -### 3. 连接到ChromeDriver +### 3. 连接到 ChromeDriver ```javascript const webdriverio = require('webdriverio'); @@ -112,8 +112,8 @@ client ## 工作流程 -无需重新编译Electron,只要把app的源码放到[Electron的资源目录](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md)里就可直接开始测试了。 +无需重新编译 Electron,只要把 app 的源码放到 [Electron的资源目录](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) 里就可直接开始测试了。 -当然,你也可以在运行Electron时传入参数指定你app的所在文件夹。这步可以免去你拷贝-粘贴你的app到Electron的资源目录。 +当然,你也可以在运行 Electron 时传入参数指定你 app 的所在文件夹。这步可以免去你拷贝-粘贴你的 app 到 Electron 的资源目录。 [chrome-driver]: https://sites.google.com/a/chromium.org/chromedriver/ From fed77d1837b031a666d0d229e26a26f7889d1ad8 Mon Sep 17 00:00:00 2001 From: christoth Date: Thu, 3 Mar 2016 17:22:20 -0500 Subject: [PATCH 0035/1265] Use flexbox layout for browserplugin --- atom/renderer/lib/web-view/web-view.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/atom/renderer/lib/web-view/web-view.js b/atom/renderer/lib/web-view/web-view.js index bd128f6fffe..5b135e0427a 100644 --- a/atom/renderer/lib/web-view/web-view.js +++ b/atom/renderer/lib/web-view/web-view.js @@ -33,6 +33,7 @@ var WebViewImpl = (function() { this.on = {}; this.browserPluginNode = this.createBrowserPluginNode(); shadowRoot = this.webviewNode.createShadowRoot(); + shadowRoot.innerHTML = ''; this.setupWebViewAttributes(); this.setupFocusPropagation(); this.viewInstanceId = getNextId(); @@ -279,9 +280,7 @@ var registerBrowserPluginElement = function() { this.setAttribute('id', 'browser-plugin-' + getNextId()); // The node fills in the container. - this.style.display = 'block'; - this.style.width = '100%'; - return this.style.height = '100%'; + return this.style.flex = '1 1 auto'; }; proto.attributeChangedCallback = function(name, oldValue, newValue) { var internal; From b1eefbdcd93779c932be8b2a0cac7e342997bf79 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Thu, 3 Mar 2016 23:48:30 -0500 Subject: [PATCH 0036/1265] Simplify the isDarkModeEnabled check --- atom/browser/browser_mac.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index affeead255a..f5859df97aa 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -27,7 +27,7 @@ void Browser::Show() { } bool Browser::IsDarkModeEnabled() { - NSString *mode = CFBridgingRelease(CFPreferencesCopyValue((CFStringRef)@"AppleInterfaceStyle", kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost)); + NSString *mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; return [mode isEqualToString: @"Dark"]; } From be67dca686474fc57ff92c341fe5fe3a9dc55a5e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 3 Mar 2016 20:53:58 -0800 Subject: [PATCH 0037/1265] Use _cycleWindows selector to implement cmd-` --- atom/browser/native_window_mac.mm | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 9d9f2a2392d..01073ed73da 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -896,21 +896,11 @@ void NativeWindowMac::HandleKeyboardEvent( // Handle the cmd+~ shortcut. if ((event.os_event.modifierFlags & NSCommandKeyMask) /* cmd */ && (event.os_event.keyCode == 50 /* ~ */)) { - // Switch to next visible window. - NSArray* windows = [NSApp windows]; - NSIndexSet* indexes = [windows indexesOfObjectsPassingTest: - ^BOOL(id window, NSUInteger idx, BOOL* stop) { - return [window isVisible]; - }]; - if ([indexes count] == 0) - return; - NSUInteger current = [windows indexOfObject:event.os_event.window]; - if (current == NSNotFound) // Some faked event. - return; - NSUInteger next = [indexes indexGreaterThanIndex:current]; - if (next == NSNotFound) - next = [indexes firstIndex]; - [[windows objectAtIndex:next] makeKeyAndOrderFront:nil]; + if (event.os_event.modifierFlags & NSShiftKeyMask) { + [NSApp sendAction:@selector(_cycleWindowsReversed:) to:nil from:nil]; + } else { + [NSApp sendAction:@selector(_cycleWindows:) to:nil from:nil]; + } } } } From 63294892f0be54713a2104646291a7e1a6eddb94 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Thu, 3 Mar 2016 23:58:58 -0500 Subject: [PATCH 0038/1265] Rename dark-mode-changed to platform-theme-changed --- atom/browser/api/atom_api_app.cc | 4 ++-- atom/browser/api/atom_api_app.h | 2 +- atom/browser/browser.cc | 4 ++-- atom/browser/browser.h | 3 ++- atom/browser/browser_observer.h | 2 +- atom/browser/mac/atom_application_delegate.mm | 6 +++--- docs/api/app.md | 2 +- 7 files changed, 12 insertions(+), 11 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 76a5f32a245..fc1afb6d35c 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -283,8 +283,8 @@ void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) { } #if defined(OS_MACOSX) -void App::OnDarkModeChanged() { - Emit("dark-mode-changed"); +void App::OnPlatformThemeChanged() { + Emit("platform-theme-changed"); } #endif diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 54d3f9dc743..3d4ac17adf7 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -72,7 +72,7 @@ class App : public AtomBrowserClient::Delegate, void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; #if defined(OS_MACOSX) - void OnDarkModeChanged() override; + void OnPlatformThemeChanged() override; #endif // mate::Wrappable: diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 7fbe01633b0..e89f52283b3 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -181,8 +181,8 @@ void Browser::OnWindowAllClosed() { FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed()); } -void Browser::DarkModeChanged() { - FOR_EACH_OBSERVER(BrowserObserver, observers_, OnDarkModeChanged()); +void Browser::PlatformThemeChanged() { + FOR_EACH_OBSERVER(BrowserObserver, observers_, OnPlatformThemeChanged()); } } // namespace atom diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 04b7a725787..8ea52370027 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -145,7 +145,8 @@ class Browser : public WindowListObserver { // Request basic auth login. void RequestLogin(LoginHandler* login_handler); - void DarkModeChanged(); + // Tell the application that plaform's theme changed. + void PlatformThemeChanged(); void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index 0577712becd..da327eb90a0 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -45,7 +45,7 @@ class BrowserObserver { // The browser requests HTTP login. virtual void OnLogin(LoginHandler* login_handler) {} - virtual void OnDarkModeChanged() {} + virtual void OnPlatformThemeChanged() {} protected: virtual ~BrowserObserver() {} diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index 0b9c60e7d26..f4db929bf57 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -25,7 +25,7 @@ [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"]; // Add observer to monitor the system's Dark Mode theme. - [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(darkModeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; + [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(platformThemeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; atom::Browser::Get()->WillFinishLaunching(); } @@ -62,8 +62,8 @@ return flag; } -- (void)darkModeChanged:(NSNotification *)notify { - atom::Browser::Get()->DarkModeChanged(); +- (void)platformThemeChanged:(NSNotification *)notify { + atom::Browser::Get()->PlatformThemeChanged(); } @end diff --git a/docs/api/app.md b/docs/api/app.md index 3469c6b108d..8cc9c6e3747 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -228,7 +228,7 @@ app.on('login', function(event, webContents, request, authInfo, callback) { Emitted when the gpu process crashes. -### Event: 'dark-mode-changed' _OS X_ +### Event: 'platform-theme-changed' _OS X_ Emitted when the system's Dark Mode theme is toggled. From a4e04e6083a4f40fc8838571490ee00adb9e3596 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 12:29:50 -0800 Subject: [PATCH 0039/1265] Always call done callback --- spec/chromium-spec.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 8477aea776a..0e3a836d39b 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -94,10 +94,13 @@ describe('chromium feature', function() { it('can return labels of enumerated devices', function(done) { navigator.mediaDevices.enumerateDevices().then((devices) => { - const result = devices.some((device) => !!device.label); - if (result) + const labels = devices.map((device) => device.label); + const labelFound = labels.some((label) => !!label); + if (labelFound) done(); - }); + else + done('No device labels found: ' + JSON.stringify(labels)); + }).catch(done); }); }); From 20e9a871589369982b64c4b1c25885dcb34f29ab Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 12:38:39 -0800 Subject: [PATCH 0040/1265] Don't run mediaDevices spec on Linux CI --- spec/chromium-spec.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 0e3a836d39b..67b2d263204 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -7,6 +7,8 @@ const remote = require('electron').remote; const BrowserWindow = remote.require('electron').BrowserWindow; const session = remote.require('electron').session; +const isCI = remote.getGlobal('isCi'); + describe('chromium feature', function() { var fixtures = path.resolve(__dirname, 'fixtures'); var listener = null; @@ -91,6 +93,9 @@ describe('chromium feature', function() { if (process.env.TRAVIS === 'true') { return; } + if (isCI && process.platform === 'linux') { + return; + } it('can return labels of enumerated devices', function(done) { navigator.mediaDevices.enumerateDevices().then((devices) => { From a9e22801e9a4671da2d13b338864b59195dffd70 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 15:43:51 -0800 Subject: [PATCH 0041/1265] Add failing spec for reassigning remote function --- spec/api-ipc-spec.js | 8 ++++++++ spec/fixtures/module/function.js | 1 + 2 files changed, 9 insertions(+) create mode 100644 spec/fixtures/module/function.js diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 1ac717cd9d3..462c7bcf976 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -63,6 +63,14 @@ describe('ipc module', function() { var obj = new call.constructor; assert.equal(obj.test, 'test'); }); + + it('can reassign its member functions', function() { + var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')); + assert.equal(remoteFunctions.aFunction(), 1127); + + remoteFunctions.aFunction = function () { return 1234; }; + assert.equal(remoteFunctions.aFunction(), 1234); + }); }); describe('remote value in browser', function() { diff --git a/spec/fixtures/module/function.js b/spec/fixtures/module/function.js new file mode 100644 index 00000000000..803a2838d37 --- /dev/null +++ b/spec/fixtures/module/function.js @@ -0,0 +1 @@ +exports.aFunction = function() { return 1127; }; From 610a5031885474d320eeda46fdffb03884ccd867 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 15:49:46 -0800 Subject: [PATCH 0042/1265] Make member functions writable --- atom/renderer/api/lib/remote.js | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/renderer/api/lib/remote.js b/atom/renderer/api/lib/remote.js index a9798338faa..6b84f74d354 100644 --- a/atom/renderer/api/lib/remote.js +++ b/atom/renderer/api/lib/remote.js @@ -110,6 +110,7 @@ let setObjectMembers = function(object, metaId, members) { return metaToValue(ret); } }; + descriptor.writable = true; descriptor.value = remoteMemberFunction; } else if (member.type === 'get') { descriptor.get = function() { From f460d81dd09d6bc050574e3018fec372958f854b Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 15:51:17 -0800 Subject: [PATCH 0043/1265] Allow remote member functions to be deleted --- atom/renderer/api/lib/remote.js | 1 + spec/api-ipc-spec.js | 2 ++ 2 files changed, 3 insertions(+) diff --git a/atom/renderer/api/lib/remote.js b/atom/renderer/api/lib/remote.js index 6b84f74d354..07aa2478293 100644 --- a/atom/renderer/api/lib/remote.js +++ b/atom/renderer/api/lib/remote.js @@ -111,6 +111,7 @@ let setObjectMembers = function(object, metaId, members) { } }; descriptor.writable = true; + descriptor.configurable = true; descriptor.value = remoteMemberFunction; } else if (member.type === 'get') { descriptor.get = function() { diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 462c7bcf976..df18835c43d 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -70,6 +70,8 @@ describe('ipc module', function() { remoteFunctions.aFunction = function () { return 1234; }; assert.equal(remoteFunctions.aFunction(), 1234); + + assert.equal(delete remoteFunctions.aFunction, true); }); }); From 3230927f105a9140985eec7505b7d1d9a2c72ea7 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 15:56:18 -0800 Subject: [PATCH 0044/1265] Mention deleting --- spec/api-ipc-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index df18835c43d..641d89270cb 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -64,7 +64,7 @@ describe('ipc module', function() { assert.equal(obj.test, 'test'); }); - it('can reassign its member functions', function() { + it('can reassign and delete its member functions', function() { var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')); assert.equal(remoteFunctions.aFunction(), 1127); From fe9e026f9e9aaf191c9e998493f2d88c4c6f76e7 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 15:57:21 -0800 Subject: [PATCH 0045/1265] getObjectMemebers -> getObjectMembers --- atom/browser/lib/rpc-server.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/browser/lib/rpc-server.js b/atom/browser/lib/rpc-server.js index a31c6e146e8..5399c192e82 100644 --- a/atom/browser/lib/rpc-server.js +++ b/atom/browser/lib/rpc-server.js @@ -16,7 +16,7 @@ const FUNCTION_PROPERTIES = [ let rendererFunctions = {}; // Return the description of object's members: -let getObjectMemebers = function(object) { +let getObjectMembers = function(object) { let names = Object.getOwnPropertyNames(object); // For Function, we should not override following properties even though they // are "own" properties. @@ -46,7 +46,7 @@ let getObjectPrototype = function(object) { if (proto === null || proto === Object.prototype) return null; return { - members: getObjectMemebers(proto), + members: getObjectMembers(proto), proto: getObjectPrototype(proto), }; }; @@ -101,7 +101,7 @@ var valueToMeta = function(sender, value, optimizeSimpleObject) { // passed to renderer we would assume the renderer keeps a reference of // it. meta.id = objectsRegistry.add(sender, value); - meta.members = getObjectMemebers(value); + meta.members = getObjectMembers(value); meta.proto = getObjectPrototype(value); } else if (meta.type === 'buffer') { meta.value = Array.prototype.slice.call(value, 0); From 73f6162f5c6e0889857d27d1470a6742c719f492 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 16:12:14 -0800 Subject: [PATCH 0046/1265] Enable resizable spec on Linux --- spec/api-browser-window-spec.js | 34 +++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 25e92382cca..8c45b43f553 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -527,6 +527,24 @@ describe('browser-window module', function() { }); }); + describe('window states', function () { + describe('resizable state', function() { + it('can be changed with resizable option', function() { + w.destroy(); + w = new BrowserWindow({show: false, resizable: false}); + assert.equal(w.isResizable(), false); + }); + + it('can be changed with setResizable method', function() { + assert.equal(w.isResizable(), true); + w.setResizable(false); + assert.equal(w.isResizable(), false); + w.setResizable(true); + assert.equal(w.isResizable(), true); + }); + }); + }) + describe('window states', function() { // Not implemented on Linux. if (process.platform == 'linux') @@ -625,22 +643,6 @@ describe('browser-window module', function() { }); }); - describe('resizable state', function() { - it('can be changed with resizable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, resizable: false}); - assert.equal(w.isResizable(), false); - }); - - it('can be changed with setResizable method', function() { - assert.equal(w.isResizable(), true); - w.setResizable(false); - assert.equal(w.isResizable(), false); - w.setResizable(true); - assert.equal(w.isResizable(), true); - }); - }); - describe('hasShadow state', function() { // On Window there is no shadow by default and it can not be changed // dynamically. From 67edcc8f9192948498bc36b697e63b494f35ebb2 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 16:12:58 -0800 Subject: [PATCH 0047/1265] Initially set resizable property on Linux --- atom/browser/native_window_views.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 97a2ee05a33..3605abbd3ff 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -120,11 +120,11 @@ NativeWindowViews::NativeWindowViews( minimizable_(true) { options.Get(options::kTitle, &title_); options.Get(options::kAutoHideMenuBar, &menu_bar_autohide_); + options.Get(options::kResizable, &resizable_); #if defined(OS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. - options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); #endif From bda5bb4a74416fed3b0577677e458c5b2e416a02 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 16:15:04 -0800 Subject: [PATCH 0048/1265] Add missing semicolon --- spec/api-browser-window-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 8c45b43f553..c11d177a73e 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -543,7 +543,7 @@ describe('browser-window module', function() { assert.equal(w.isResizable(), true); }); }); - }) + }); describe('window states', function() { // Not implemented on Linux. From 33978455b807647ab75c411639c717f245fe04e8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Mar 2016 12:00:06 +0900 Subject: [PATCH 0049/1265] Bump v0.36.10 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index 0bccc254b1b..7f78bee91b1 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.36.9', + 'version%': '0.36.10', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index b3eb7d8efaa..54b4f4d6179 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.36.9 + 0.36.10 CFBundleShortVersionString - 0.36.9 + 0.36.10 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 2dee1c0e433..9acd36f43a2 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,36,9,0 - PRODUCTVERSION 0,36,9,0 + FILEVERSION 0,36,10,0 + PRODUCTVERSION 0,36,10,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.36.9" + VALUE "FileVersion", "0.36.10" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.36.9" + VALUE "ProductVersion", "0.36.10" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 136c375e2ac..c4291437e5b 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 36 -#define ATOM_PATCH_VERSION 9 +#define ATOM_PATCH_VERSION 10 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 504bdd6a4f7..ca232158068 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.36.9", + "version": "0.36.10", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From d5f5cdb45ab122a1d6b8e9290ef4b3b26764f5b3 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Sat, 5 Mar 2016 01:39:13 -0500 Subject: [PATCH 0050/1265] :apple:Fix 'isMaximized()' for non resizable windows --- atom/browser/native_window_mac.mm | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 9d9f2a2392d..46448594c36 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -583,7 +583,16 @@ void NativeWindowMac::Unmaximize() { } bool NativeWindowMac::IsMaximized() { - return [window_ isZoomed]; + if (([window_ styleMask] & NSResizableWindowMask) != 0) { + return [window_ isZoomed]; + } else { + NSRect rectScreen = [[NSScreen mainScreen] visibleFrame]; + NSRect rectWindow = [window_ frame]; + return (rectScreen.origin.x == rectWindow.origin.x && + rectScreen.origin.y == rectWindow.origin.y && + rectScreen.size.width == rectWindow.size.width && + rectScreen.size.height == rectWindow.size.height); + } } void NativeWindowMac::Minimize() { From 23b92ef9ecc9bf89bd7776068d03fa0458c264c2 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Mar 2016 18:57:46 +0900 Subject: [PATCH 0051/1265] Fix passing certificate to select-client-certificate's callback --- atom/browser/api/atom_api_app.cc | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index e54d7fee176..0c035af49b7 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -132,19 +132,20 @@ void OnClientCertificateSelected( std::shared_ptr delegate, mate::Arguments* args) { mate::Dictionary cert_data; - if (!(args->Length() == 1 && args->GetNext(&cert_data))) { + if (!args->GetNext(&cert_data)) { args->ThrowError(); return; } - std::string encoded_data; - cert_data.Get("data", &encoded_data); + v8::Local data; + if (!cert_data.Get("data", &data)) + return; - auto certs = - net::X509Certificate::CreateCertificateListFromBytes( - encoded_data.data(), encoded_data.size(), - net::X509Certificate::FORMAT_AUTO); - delegate->ContinueWithCertificate(certs[0].get()); + auto certs = net::X509Certificate::CreateCertificateListFromBytes( + node::Buffer::Data(data), node::Buffer::Length(data), + net::X509Certificate::FORMAT_AUTO); + if (certs.size() > 0) + delegate->ContinueWithCertificate(certs[0].get()); } void PassLoginInformation(scoped_refptr login_handler, From 5f95fea3e278b4e6261d9a304a9e313e0c0cf516 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Mar 2016 21:20:02 +0900 Subject: [PATCH 0052/1265] docs: OS X also has progress bar --- docs/tutorial/desktop-environment-integration.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index a72d68b3cf3..c35eea944be 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -246,12 +246,14 @@ __Launcher shortcuts of Audacious:__ ![audacious](https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png) -## Progress Bar in Taskbar (Windows & Unity) +## Progress Bar in Taskbar (Windows, OS X, Unity) On Windows a taskbar button can be used to display a progress bar. This enables a window to provide progress information to the user without the user having to switch to the window itself. +On OS X the progress bar will be displayed as a part of the dock icon. + The Unity DE also has a similar feature that allows you to specify the progress bar in the launcher. @@ -259,10 +261,6 @@ __Progress bar in taskbar button:__ ![Taskbar Progress Bar](https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png) -__Progress bar in Unity launcher:__ - -![Unity Launcher](https://cloud.githubusercontent.com/assets/639601/5081747/4a0a589e-6f0f-11e4-803f-91594716a546.png) - To set the progress bar for a Window, you can use the [BrowserWindow.setProgressBar][setprogressbar] API: From 2be368bded41425fa682381e4e723970a74a2652 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Mar 2016 21:38:06 +0900 Subject: [PATCH 0053/1265] SetFullScreen should not work at all when not fullscreenable This follows the logic of OS X. --- atom/browser/native_window_views.cc | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index a0c2e3f170b..93eb7b88d89 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -363,29 +363,27 @@ bool NativeWindowViews::IsMinimized() { } void NativeWindowViews::SetFullScreen(bool fullscreen) { + if (!IsFullScreenable()) + return; + #if defined(OS_WIN) // There is no native fullscreen state on Windows. if (fullscreen) { - if (IsFullScreenable()) { - last_window_state_ = ui::SHOW_STATE_FULLSCREEN; - NotifyWindowEnterFullScreen(); - } + last_window_state_ = ui::SHOW_STATE_FULLSCREEN; + NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // We set the new value after notifying, so we can handle the size event // correctly. - if (IsFullScreenable()) - window_->SetFullscreen(fullscreen); + window_->SetFullscreen(fullscreen); #else - if (!fullscreen || (fullscreen && IsFullScreenable())) { - if (IsVisible()) - window_->SetFullscreen(fullscreen); - else - window_->native_widget_private()->ShowWithWindowState( - ui::SHOW_STATE_FULLSCREEN); - } + if (IsVisible()) + window_->SetFullscreen(fullscreen); + else + window_->native_widget_private()->ShowWithWindowState( + ui::SHOW_STATE_FULLSCREEN); #endif } From 114801d41242b162af786f9fefc0b646273210e3 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 5 Mar 2016 21:54:41 +0900 Subject: [PATCH 0054/1265] Remove the duplicate logic on OS X --- atom/browser/native_window.cc | 11 +++++------ atom/browser/native_window_mac.mm | 14 ++------------ 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 16154be6bea..20400437fce 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -133,18 +133,17 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(true); } - - // Disable fullscreen button when 'fullscreenable' is false or 'fullscreen' - // is specified to false. + // Disable fullscreen button if 'fullscreen' is specified to false. bool fullscreenable = true; - options.Get(options::kFullScreenable, &fullscreenable); bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) fullscreenable = false; + // Overriden by 'fullscreenable'. + options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); - if (fullscreen) + if (fullscreen) { SetFullScreen(true); - + } bool skip; if (options.Get(options::kSkipTaskbar, &skip) && skip) { SetSkipTaskbar(skip); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 9d9f2a2392d..3fc45478514 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -482,19 +482,9 @@ NativeWindowMac::NativeWindowMac( options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; - // Disable fullscreen button when 'fullscreenable' is false or 'fullscreen' - // is specified to false. - bool fullscreenable = true; - options.Get(options::kFullScreenable, &fullscreenable); - bool fullscreen = false; - if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) - fullscreenable = false; - SetFullScreenable(fullscreenable); - - // Disable zoom button if window is not resizable - if (!maximizable) { + // Disable zoom button if window is not resizable. + if (!maximizable) SetMaximizable(false); - } NSView* view = inspectable_web_contents()->GetView()->GetNativeView(); [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; From 2515425cd5525f2bab4ba6ba3d497a6f7a1c9c09 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Mar 2016 15:04:05 +0900 Subject: [PATCH 0055/1265] Remove duplicated keyboard code --- atom/browser/ui/accelerator_util.cc | 113 ++++------------ atom/common/keyboard_util.cc | 127 +++++++++++++----- atom/common/keyboard_util.h | 9 +- .../native_mate_converters/blink_converter.cc | 21 ++- 4 files changed, 135 insertions(+), 135 deletions(-) diff --git a/atom/browser/ui/accelerator_util.cc b/atom/browser/ui/accelerator_util.cc index 39138d8e49b..f683c99c637 100644 --- a/atom/browser/ui/accelerator_util.cc +++ b/atom/browser/ui/accelerator_util.cc @@ -18,13 +18,12 @@ namespace accelerator_util { -bool StringToAccelerator(const std::string& description, +bool StringToAccelerator(const std::string& shortcut, ui::Accelerator* accelerator) { - if (!base::IsStringASCII(description)) { + if (!base::IsStringASCII(shortcut)) { LOG(ERROR) << "The accelerator string can only contain ASCII characters"; return false; } - std::string shortcut(base::ToLowerASCII(description)); std::vector tokens = base::SplitString( shortcut, "+", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); @@ -33,95 +32,35 @@ bool StringToAccelerator(const std::string& description, int modifiers = ui::EF_NONE; ui::KeyboardCode key = ui::VKEY_UNKNOWN; for (size_t i = 0; i < tokens.size(); i++) { - // We use straight comparing instead of map because the accelerator tends - // to be correct and usually only uses few special tokens. - if (tokens[i].size() == 1) { - bool shifted = false; - key = atom::KeyboardCodeFromCharCode(tokens[i][0], &shifted); - if (shifted) + bool shifted = false; + ui::KeyboardCode code = atom::KeyboardCodeFromStr(tokens[i], &shifted); + if (shifted) + modifiers |= ui::EF_SHIFT_DOWN; + switch (code) { + // The token can be a modifier. + case ui::VKEY_SHIFT: modifiers |= ui::EF_SHIFT_DOWN; - } else if (tokens[i] == "ctrl" || tokens[i] == "control") { - modifiers |= ui::EF_CONTROL_DOWN; - } else if (tokens[i] == "super") { - modifiers |= ui::EF_COMMAND_DOWN; -#if defined(OS_MACOSX) - } else if (tokens[i] == "cmd" || tokens[i] == "command") { - modifiers |= ui::EF_COMMAND_DOWN; -#endif - } else if (tokens[i] == "commandorcontrol" || tokens[i] == "cmdorctrl") { -#if defined(OS_MACOSX) - modifiers |= ui::EF_COMMAND_DOWN; -#else - modifiers |= ui::EF_CONTROL_DOWN; -#endif - } else if (tokens[i] == "alt") { - modifiers |= ui::EF_ALT_DOWN; - } else if (tokens[i] == "shift") { - modifiers |= ui::EF_SHIFT_DOWN; - } else if (tokens[i] == "plus") { - modifiers |= ui::EF_SHIFT_DOWN; - key = ui::VKEY_OEM_PLUS; - } else if (tokens[i] == "tab") { - key = ui::VKEY_TAB; - } else if (tokens[i] == "space") { - key = ui::VKEY_SPACE; - } else if (tokens[i] == "backspace") { - key = ui::VKEY_BACK; - } else if (tokens[i] == "delete") { - key = ui::VKEY_DELETE; - } else if (tokens[i] == "insert") { - key = ui::VKEY_INSERT; - } else if (tokens[i] == "enter" || tokens[i] == "return") { - key = ui::VKEY_RETURN; - } else if (tokens[i] == "up") { - key = ui::VKEY_UP; - } else if (tokens[i] == "down") { - key = ui::VKEY_DOWN; - } else if (tokens[i] == "left") { - key = ui::VKEY_LEFT; - } else if (tokens[i] == "right") { - key = ui::VKEY_RIGHT; - } else if (tokens[i] == "home") { - key = ui::VKEY_HOME; - } else if (tokens[i] == "end") { - key = ui::VKEY_END; - } else if (tokens[i] == "pageup") { - key = ui::VKEY_PRIOR; - } else if (tokens[i] == "pagedown") { - key = ui::VKEY_NEXT; - } else if (tokens[i] == "esc" || tokens[i] == "escape") { - key = ui::VKEY_ESCAPE; - } else if (tokens[i] == "volumemute") { - key = ui::VKEY_VOLUME_MUTE; - } else if (tokens[i] == "volumeup") { - key = ui::VKEY_VOLUME_UP; - } else if (tokens[i] == "volumedown") { - key = ui::VKEY_VOLUME_DOWN; - } else if (tokens[i] == "medianexttrack") { - key = ui::VKEY_MEDIA_NEXT_TRACK; - } else if (tokens[i] == "mediaprevioustrack") { - key = ui::VKEY_MEDIA_PREV_TRACK; - } else if (tokens[i] == "mediastop") { - key = ui::VKEY_MEDIA_STOP; - } else if (tokens[i] == "mediaplaypause") { - key = ui::VKEY_MEDIA_PLAY_PAUSE; - } else if (tokens[i].size() > 1 && tokens[i][0] == 'f') { - // F1 - F24. - int n; - if (base::StringToInt(tokens[i].c_str() + 1, &n) && n > 0 && n < 25) { - key = static_cast(ui::VKEY_F1 + n - 1); - } else { - LOG(WARNING) << tokens[i] << "is not available on keyboard"; - return false; - } - } else { - LOG(WARNING) << "Invalid accelerator token: " << tokens[i]; - return false; + break; + case ui::VKEY_CONTROL: + modifiers |= ui::EF_CONTROL_DOWN; + break; + case ui::VKEY_MENU: + modifiers |= ui::EF_ALT_DOWN; + break; + case ui::VKEY_COMMAND: + modifiers |= ui::EF_COMMAND_DOWN; + break; + case ui::VKEY_ALTGR: + modifiers |= ui::EF_ALTGR_DOWN; + break; + // Or it is a normal key. + default: + key = code; } } if (key == ui::VKEY_UNKNOWN) { - LOG(WARNING) << "The accelerator doesn't contain a valid key"; + LOG(WARNING) << shortcut << " doesn't contain a valid key"; return false; } diff --git a/atom/common/keyboard_util.cc b/atom/common/keyboard_util.cc index 1884246d233..d860bc0c46c 100644 --- a/atom/common/keyboard_util.cc +++ b/atom/common/keyboard_util.cc @@ -3,12 +3,19 @@ // found in the LICENSE file. #include + #include "atom/common/keyboard_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" namespace atom { -// Return key code of the char. +namespace { + +// Return key code of the char, and also determine whether the SHIFT key is +// pressed. ui::KeyboardCode KeyboardCodeFromCharCode(base::char16 c, bool* shifted) { + c = base::ToLowerASCII(c); *shifted = false; switch (c) { case 0x08: return ui::VKEY_BACK; @@ -72,38 +79,98 @@ ui::KeyboardCode KeyboardCodeFromCharCode(base::char16 c, bool* shifted) { } } -// Return key code of the char. -ui::KeyboardCode KeyboardCodeFromKeyIdentifier(const std::string& chr) { - if (chr == "enter") return ui::VKEY_RETURN; - if (chr == "backspace") return ui::VKEY_BACK; - if (chr == "delete") return ui::VKEY_DELETE; - if (chr == "tab") return ui::VKEY_TAB; - if (chr == "escape") return ui::VKEY_ESCAPE; - if (chr == "control") return ui::VKEY_CONTROL; +// Return key code represented by |str|. +ui::KeyboardCode KeyboardCodeFromKeyIdentifier(const std::string& s, + bool* shifted) { + std::string str = base::ToLowerASCII(s); + if (str == "ctrl" || str == "control") { + return ui::VKEY_CONTROL; + } else if (str == "super" || str == "cmd" || str == "command" || + str == "meta") { + return ui::VKEY_COMMAND; + } else if (str == "commandorcontrol" || str == "cmdorctrl") { #if defined(OS_MACOSX) - if (chr == "command" - || chr == "cmd" - || chr == "meta") return ui::VKEY_COMMAND; - if (chr == "option") return ui::VKEY_MENU; + return ui::VKEY_COMMAND; +#else + return ui::VKEY_CONTROL; #endif -#if defined(OS_WIN) - if (chr == "meta") return ui::VKEY_LWIN; - if (chr == "altgr") return ui::VKEY_ALTGR; -#endif - if (chr == "alt") return ui::VKEY_MENU; - if (chr == "shift") return ui::VKEY_SHIFT; - if (chr == "end") return ui::VKEY_END; - if (chr == "home") return ui::VKEY_HOME; - if (chr == "insert") return ui::VKEY_INSERT; - if (chr == "left") return ui::VKEY_LEFT; - if (chr == "up") return ui::VKEY_UP; - if (chr == "right") return ui::VKEY_RIGHT; - if (chr == "down") return ui::VKEY_DOWN; - if (chr == "pageup") return ui::VKEY_PRIOR; - if (chr == "pagedown") return ui::VKEY_NEXT; - if (chr == "printscreen") return ui::VKEY_SNAPSHOT; + } else if (str == "alt" || str == "option") { + return ui::VKEY_MENU; + } else if (str == "shift") { + return ui::VKEY_SHIFT; + } else if (str == "altgr") { + return ui::VKEY_ALTGR; + } else if (str == "plus") { + *shifted = true; + return ui::VKEY_OEM_PLUS; + } else if (str == "tab") { + return ui::VKEY_TAB; + } else if (str == "space") { + return ui::VKEY_SPACE; + } else if (str == "backspace") { + return ui::VKEY_BACK; + } else if (str == "delete") { + return ui::VKEY_DELETE; + } else if (str == "insert") { + return ui::VKEY_INSERT; + } else if (str == "enter" || str == "return") { + return ui::VKEY_RETURN; + } else if (str == "up") { + return ui::VKEY_UP; + } else if (str == "down") { + return ui::VKEY_DOWN; + } else if (str == "left") { + return ui::VKEY_LEFT; + } else if (str == "right") { + return ui::VKEY_RIGHT; + } else if (str == "home") { + return ui::VKEY_HOME; + } else if (str == "end") { + return ui::VKEY_END; + } else if (str == "pageup") { + return ui::VKEY_PRIOR; + } else if (str == "pagedown") { + return ui::VKEY_NEXT; + } else if (str == "esc" || str == "escape") { + return ui::VKEY_ESCAPE; + } else if (str == "volumemute") { + return ui::VKEY_VOLUME_MUTE; + } else if (str == "volumeup") { + return ui::VKEY_VOLUME_UP; + } else if (str == "volumedown") { + return ui::VKEY_VOLUME_DOWN; + } else if (str == "medianexttrack") { + return ui::VKEY_MEDIA_NEXT_TRACK; + } else if (str == "mediaprevioustrack") { + return ui::VKEY_MEDIA_PREV_TRACK; + } else if (str == "mediastop") { + return ui::VKEY_MEDIA_STOP; + } else if (str == "mediaplaypause") { + return ui::VKEY_MEDIA_PLAY_PAUSE; + } else if (str == "printscreen") { + return ui::VKEY_SNAPSHOT; + } else if (str.size() > 1 && str[0] == 'f') { + // F1 - F24. + int n; + if (base::StringToInt(str.c_str() + 1, &n) && n > 0 && n < 25) { + return static_cast(ui::VKEY_F1 + n - 1); + } else { + LOG(WARNING) << str << "is not available on keyboard"; + return ui::VKEY_UNKNOWN; + } + } else { + LOG(WARNING) << "Invalid accelerator token: " << str; + return ui::VKEY_UNKNOWN; + } +} - return ui::VKEY_UNKNOWN; +} // namespace + +ui::KeyboardCode KeyboardCodeFromStr(const std::string& str, bool* shifted) { + if (str.size() == 1) + return KeyboardCodeFromCharCode(str[0], shifted); + else + return KeyboardCodeFromKeyIdentifier(str, shifted); } } // namespace atom diff --git a/atom/common/keyboard_util.h b/atom/common/keyboard_util.h index d3168d4447e..c9d1b809e8f 100644 --- a/atom/common/keyboard_util.h +++ b/atom/common/keyboard_util.h @@ -6,17 +6,14 @@ #define ATOM_COMMON_KEYBOARD_UTIL_H_ #include + #include "ui/events/keycodes/keyboard_codes.h" -#include "base/strings/string_util.h" namespace atom { -// Return key code of the char, and also determine whether the SHIFT key is +// Return key code of the |str|, and also determine whether the SHIFT key is // pressed. -ui::KeyboardCode KeyboardCodeFromCharCode(base::char16 c, bool* shifted); - -// Return key code of the char from a string representation of the char -ui::KeyboardCode KeyboardCodeFromKeyIdentifier(const std::string& chr); +ui::KeyboardCode KeyboardCodeFromStr(const std::string& str, bool* shifted); } // namespace atom diff --git a/atom/common/native_mate_converters/blink_converter.cc b/atom/common/native_mate_converters/blink_converter.cc index fdb894b3346..c58f830eb02 100644 --- a/atom/common/native_mate_converters/blink_converter.cc +++ b/atom/common/native_mate_converters/blink_converter.cc @@ -159,25 +159,22 @@ bool Converter::FromV8( return false; if (!ConvertFromV8(isolate, val, static_cast(out))) return false; - base::char16 code; - std::string identifier; - bool shifted = false; - if (dict.Get("keyCode", &code)) - out->windowsKeyCode = atom::KeyboardCodeFromCharCode(code, &shifted); - else if (dict.Get("keyCode", &identifier)) - out->windowsKeyCode = atom::KeyboardCodeFromKeyIdentifier( - base::ToLowerASCII(identifier)); + std::string str; + bool shifted = false; + if (dict.Get("keyCode", &str)) + out->windowsKeyCode = atom::KeyboardCodeFromStr(str, &shifted); else return false; if (shifted) out->modifiers |= blink::WebInputEvent::ShiftKey; out->setKeyIdentifierFromWindowsKeyCode(); - if (out->type == blink::WebInputEvent::Char || - out->type == blink::WebInputEvent::RawKeyDown) { - out->text[0] = code; - out->unmodifiedText[0] = code; + if ((out->type == blink::WebInputEvent::Char || + out->type == blink::WebInputEvent::RawKeyDown) && + str.size() == 1) { + out->text[0] = str[0]; + out->unmodifiedText[0] = str[0]; } return true; } From b7a40f309761f4a54a2171fbeeab129677a8134e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 6 Mar 2016 15:12:04 +0900 Subject: [PATCH 0056/1265] docs: Add missing key codes --- docs/api/accelerator.md | 3 +++ docs/api/web-contents.md | 10 +++------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/api/accelerator.md b/docs/api/accelerator.md index 8858d18e856..93d1f244c6b 100644 --- a/docs/api/accelerator.md +++ b/docs/api/accelerator.md @@ -23,6 +23,8 @@ The `Super` key is mapped to the `Windows` key on Windows and Linux and * `Control` (or `Ctrl` for short) * `CommandOrControl` (or `CmdOrCtrl` for short) * `Alt` +* `Option` +* `AltGr` * `Shift` * `Super` @@ -44,3 +46,4 @@ The `Super` key is mapped to the `Windows` key on Windows and Linux and * `Escape` (or `Esc` for short) * `VolumeUp`, `VolumeDown` and `VolumeMute` * `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause` +* `PrintScreen` diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 66ab545bf21..8eda16b6860 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -764,13 +764,9 @@ Sends an input `event` to the page. For keyboard events, the `event` object also have following properties: -* `keyCode` Char or String (**required**) - The character that will be sent - as the keyboard event. Can be a single UTF-8 character, or the name of the - key that generates the event. Accepted key names are `enter`, `backspace`, - `delete`, `tab`, `escape`, `control`, `alt`, `altgr` (Windows only), `shift`, - `end`, `home`, `insert`, `left`, `up`, `right`, `down`, `pageUp`, `pageDown`, - `printScreen`, `meta`, `cmd` (OSX only), `command` (OSX only), `option` - (OSX only) +* `keyCode` String (**required**) - The character that will be sent + as the keyboard event. Should only use the valid key codes in + [Accelerator](accelerator.md). For mouse events, the `event` object also have following properties: From f9f20957a4d71be4d2f44ab4626638850735e422 Mon Sep 17 00:00:00 2001 From: Dongjoon Hyun Date: Sat, 5 Mar 2016 23:28:39 -0800 Subject: [PATCH 0057/1265] Fix link name. --- docs/api/synopsis.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index d14d52a39b3..f2009e75520 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -49,7 +49,7 @@ To run your app, read [Run your app](../tutorial/quick-start.md#run-your-app). ## Destructuring assignment If you are using CoffeeScript or Babel, you can also use -[destructuring assignment][desctructuring-assignment] to make it easier to use +[destructuring assignment][destructuring-assignment] to make it easier to use built-in modules: ```javascript @@ -79,5 +79,5 @@ require('electron').hideInternalModules() ``` [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface -[desctructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment +[destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment [issue-387]: https://github.com/atom/electron/issues/387 From 68b453770bc36539f14e19ca94f7726a238c3e79 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Sun, 6 Mar 2016 10:55:47 -0500 Subject: [PATCH 0058/1265] :apple: Rename 'isDarkModeEnabled' to 'isDarkMode' --- atom/browser/api/atom_api_app.cc | 4 ++-- atom/browser/browser.h | 4 ++-- atom/browser/browser_mac.mm | 2 +- docs/api/app.md | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index fc1afb6d35c..961637852be 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -376,8 +376,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) - .SetMethod("isDarkModeEnabled", - base::Bind(&Browser::IsDarkModeEnabled, browser)) + .SetMethod("isDarkMode", + base::Bind(&Browser::IsDarkMode, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 8ea52370027..1d0b4aec8ba 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -83,8 +83,8 @@ class Browser : public WindowListObserver { // Show the application. void Show(); - // Check if Dark Mode enabled. - bool IsDarkModeEnabled(); + // Check if the system is in Dark Mode. + bool IsDarkMode(); // Bounce the dock icon. enum BounceType { diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index f5859df97aa..5988e662043 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -26,7 +26,7 @@ void Browser::Show() { [[AtomApplication sharedApplication] unhide:nil]; } -bool Browser::IsDarkModeEnabled() { +bool Browser::IsDarkMode() { NSString *mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; return [mode isEqualToString: @"Dark"]; } diff --git a/docs/api/app.md b/docs/api/app.md index 8cc9c6e3747..f18c978fadd 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -465,9 +465,9 @@ if (browserOptions.transparent) { } ``` -### `app.isDarkModeEnabled()` _OS X_ +### `app.isDarkMode()` _OS X_ -This method returns `true` if Dark Mode is enabled, and `false` otherwise. +This method returns `true` if the system is in Dark Mode, and `false` otherwise. ### `app.commandLine.appendSwitch(switch[, value])` From 672552304283652f53f0b22f244655f6651cccd5 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:43:04 -0800 Subject: [PATCH 0059/1265] Remove CoffeeScript from styleguide --- docs/development/coding-style.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index a86ee32417d..f28b737921a 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -17,17 +17,23 @@ document. The document mentions some special types, scoped types (that automatically release their memory when going out of scope), logging mechanisms etc. -## CoffeeScript - -For CoffeeScript, we follow GitHub's [Style -Guide](https://github.com/styleguide/javascript) and the following rules: +## JavaScript * Files should **NOT** end with new line, because we want to match Google's styles. * File names should be concatenated with `-` instead of `_`, e.g. - `file-name.coffee` rather than `file_name.coffee`, because in + `file-name.js` rather than `file_name.js`, because in [github/atom](https://github.com/github/atom) module names are usually in - the `module-name` form. This rule only applies to `.coffee` files. + the `module-name` form. This rule only applies to `.js` files. +* Use newer ES6/ES2015 syntax where appropriate + * [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) + for requires and other constants + * [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) + for defining variables + * [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) + instead of `function () { }` + * [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) + instead of string concatenation using `+` ## API Names From 686af28f547b656b703b8ec443dcea92751d64a1 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:45:13 -0800 Subject: [PATCH 0060/1265] Mention indent and semicolons --- docs/development/coding-style.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index f28b737921a..5523c072b11 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -19,6 +19,8 @@ etc. ## JavaScript +* Use a two space indent, no hard tabs. +* End lines with a `;` * Files should **NOT** end with new line, because we want to match Google's styles. * File names should be concatenated with `-` instead of `_`, e.g. From 1c68aae43ecbc02d3b04b1b054f32202de093acc Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:46:05 -0800 Subject: [PATCH 0061/1265] Mention npm run lint --- docs/development/coding-style.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index 5523c072b11..edc18549a72 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -2,6 +2,9 @@ These are the style guidelines for coding in Electron. +You can run `npm run lint` to show all coding style issues detected by `cpplint` +and `eslint`. + ## C++ and Python For C++ and Python, we follow Chromium's [Coding From 4ec79d5d1805e0743010cc8ca155f6075e8090aa Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:53:20 -0800 Subject: [PATCH 0062/1265] Add Linux exclusion to describe --- spec/api-browser-window-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index c11d177a73e..88b897eb449 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -545,7 +545,7 @@ describe('browser-window module', function() { }); }); - describe('window states', function() { + describe('window states (excluding Linux)', function() { // Not implemented on Linux. if (process.platform == 'linux') return; From 38acc7090b8e4dff4612816040e853493328eee5 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 10:11:30 -0800 Subject: [PATCH 0063/1265] Contrain size in ctor on non-resizable windows --- atom/browser/native_window_views.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 3605abbd3ff..78769f252a8 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -218,6 +218,12 @@ NativeWindowViews::NativeWindowViews( std::string window_type; if (options.Get(options::kType, &window_type)) SetWindowType(GetAcceleratedWidget(), window_type); + + if (!resizable_) { + gfx::Size content_size = GetContentSize(); + SetContentSizeConstraints( + extensions::SizeConstraints(content_size, content_size)); + } #endif // Add web view. From 993b878925bf5d6c21493bdb1bf1209b2ab25511 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 10:37:01 -0800 Subject: [PATCH 0064/1265] :art: --- spec/api-browser-window-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 88b897eb449..731ae1cb86f 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -527,7 +527,7 @@ describe('browser-window module', function() { }); }); - describe('window states', function () { + describe('window states', function() { describe('resizable state', function() { it('can be changed with resizable option', function() { w.destroy(); From 7de37859f071d7fa910277097d6092eb116b20c9 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 13:48:33 -0800 Subject: [PATCH 0065/1265] Set resizable on Linux from InitWithOptions --- atom/browser/native_window.cc | 6 ++++++ atom/browser/native_window_views.cc | 7 ------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index c25534f7f18..80679bdb056 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -115,6 +115,12 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { } else { SetSizeConstraints(size_constraints); } +#if defined(USE_X11) + bool resizable; + if (options.Get(options::kResizable, &resizable)) { + SetResizable(resizable); + } +#endif #if defined(OS_WIN) || defined(USE_X11) bool closable; if (options.Get(options::kClosable, &closable)) { diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 78769f252a8..a2c9e8e62d9 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -120,7 +120,6 @@ NativeWindowViews::NativeWindowViews( minimizable_(true) { options.Get(options::kTitle, &title_); options.Get(options::kAutoHideMenuBar, &menu_bar_autohide_); - options.Get(options::kResizable, &resizable_); #if defined(OS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be @@ -218,12 +217,6 @@ NativeWindowViews::NativeWindowViews( std::string window_type; if (options.Get(options::kType, &window_type)) SetWindowType(GetAcceleratedWidget(), window_type); - - if (!resizable_) { - gfx::Size content_size = GetContentSize(); - SetContentSizeConstraints( - extensions::SizeConstraints(content_size, content_size)); - } #endif // Add web view. From ad3f4a26fd38887969abb14a927170ec613d3467 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 13:53:57 -0800 Subject: [PATCH 0066/1265] Restore setting resizable property from ctor on Windows --- atom/browser/native_window_views.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index a2c9e8e62d9..97a2ee05a33 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -124,6 +124,7 @@ NativeWindowViews::NativeWindowViews( #if defined(OS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. + options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); #endif From 04c8bc38b2152b253920223e5e228f4bb20f52b0 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 13:58:49 -0800 Subject: [PATCH 0067/1265] Tweak lint sentence --- docs/development/coding-style.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index edc18549a72..5d70c24c9b0 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -2,8 +2,8 @@ These are the style guidelines for coding in Electron. -You can run `npm run lint` to show all coding style issues detected by `cpplint` -and `eslint`. +You can run `npm run lint` to show any style issues detected by `cpplint` and +`eslint`. ## C++ and Python From 4b65610d40eee32b767891745c912f416d63e6d5 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 15:27:16 -0800 Subject: [PATCH 0068/1265] Add specs for realpath of unpacked asar path --- spec/asar-spec.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 060074390f1..6660ce8979d 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -317,6 +317,13 @@ describe('asar package', function() { assert.equal(r, path.join(parent, 'a.asar', 'dir1')); }); + it('returns real path of an unpacked file', function() { + var parent = fs.realpathSync(path.join(fixtures, 'asar')); + var p = path.join('unpack.asar', 'a.txt'); + var r = fs.realpathSync(path.join(parent, p)); + assert.equal(r, path.join(parent, p)); + }); + it('throws ENOENT error when can not find file', function() { var parent = fs.realpathSync(path.join(fixtures, 'asar')); var p = path.join('a.asar', 'not-exist'); @@ -377,6 +384,17 @@ describe('asar package', function() { done(); }); }); + + it('returns real path of an unpacked file', function() { + var parent = fs.realpathSync(path.join(fixtures, 'asar')); + var p = path.join('unpack.asar', 'a.txt'); + fs.realpath(path.join(parent, p), function(err, r) { + assert.equal(err, null); + assert.equal(r, path.join(parent, p)); + done(); + }); + }); + it('throws ENOENT error when can not find file', function(done) { var parent = fs.realpathSync(path.join(fixtures, 'asar')); var p = path.join('a.asar', 'not-exist'); From 4b6639c9fd49d9c7c2e482e23c127f7c9e691d92 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 15:30:33 -0800 Subject: [PATCH 0069/1265] Add missing done param --- spec/asar-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 6660ce8979d..f6f4bb71dbc 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -385,7 +385,7 @@ describe('asar package', function() { }); }); - it('returns real path of an unpacked file', function() { + it('returns real path of an unpacked file', function(done) { var parent = fs.realpathSync(path.join(fixtures, 'asar')); var p = path.join('unpack.asar', 'a.txt'); fs.realpath(path.join(parent, p), function(err, r) { From 4ded709307e0406afa04e2636104818dc45747a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 15:42:32 -0800 Subject: [PATCH 0070/1265] Map selectors for delete and pasteAndMatchStyle to roles --- atom/browser/ui/cocoa/atom_menu_controller.mm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/atom/browser/ui/cocoa/atom_menu_controller.mm b/atom/browser/ui/cocoa/atom_menu_controller.mm index 9c8c99da9aa..6761c51704f 100644 --- a/atom/browser/ui/cocoa/atom_menu_controller.mm +++ b/atom/browser/ui/cocoa/atom_menu_controller.mm @@ -32,6 +32,8 @@ Role kRolesMap[] = { { @selector(cut:), "cut" }, { @selector(copy:), "copy" }, { @selector(paste:), "paste" }, + { @selector(delete:), "delete"}, + { @selector(pasteAndMatchStyle:), "paste-and-match-style" }, { @selector(selectAll:), "selectall" }, { @selector(performMiniaturize:), "minimize" }, { @selector(performClose:), "close" }, From 03434f45bb7cca242bf196857fcff077d1d0c33f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 15:50:33 -0800 Subject: [PATCH 0071/1265] Map webContents.delete to role --- atom/browser/api/lib/menu-item.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/lib/menu-item.js b/atom/browser/api/lib/menu-item.js index eef8881cf52..4f449ecc015 100644 --- a/atom/browser/api/lib/menu-item.js +++ b/atom/browser/api/lib/menu-item.js @@ -11,7 +11,8 @@ rolesMap = { paste: 'paste', selectall: 'selectAll', minimize: 'minimize', - close: 'close' + close: 'close', + delete: 'delete' }; // Maps methods that should be called directly on the BrowserWindow instance From eae5cc9d2c6da51e239be43053b350b8d2b5d0b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 15:53:09 -0800 Subject: [PATCH 0072/1265] :art: [ci skip] --- atom/browser/ui/cocoa/atom_menu_controller.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/ui/cocoa/atom_menu_controller.mm b/atom/browser/ui/cocoa/atom_menu_controller.mm index 6761c51704f..0754da0cf5e 100644 --- a/atom/browser/ui/cocoa/atom_menu_controller.mm +++ b/atom/browser/ui/cocoa/atom_menu_controller.mm @@ -32,7 +32,7 @@ Role kRolesMap[] = { { @selector(cut:), "cut" }, { @selector(copy:), "copy" }, { @selector(paste:), "paste" }, - { @selector(delete:), "delete"}, + { @selector(delete:), "delete" }, { @selector(pasteAndMatchStyle:), "paste-and-match-style" }, { @selector(selectAll:), "selectall" }, { @selector(performMiniaturize:), "minimize" }, From 2bfc7aa152ec7466b0d151bf5ab93efd016ff8ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 16:01:46 -0800 Subject: [PATCH 0073/1265] Add mapping for performZoom --- atom/browser/ui/cocoa/atom_menu_controller.mm | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/browser/ui/cocoa/atom_menu_controller.mm b/atom/browser/ui/cocoa/atom_menu_controller.mm index 0754da0cf5e..24098914b7c 100644 --- a/atom/browser/ui/cocoa/atom_menu_controller.mm +++ b/atom/browser/ui/cocoa/atom_menu_controller.mm @@ -37,6 +37,7 @@ Role kRolesMap[] = { { @selector(selectAll:), "selectall" }, { @selector(performMiniaturize:), "minimize" }, { @selector(performClose:), "close" }, + { @selector(performZoom:), "zoom" }, }; } // namespace From eb064240f87095df3c6960f0a799d787777e987a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 16:11:58 -0800 Subject: [PATCH 0074/1265] :memo: Link to OS X Cocoa Event Handling guide on actions --- docs/api/menu.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/menu.md b/docs/api/menu.md index 7d05f88aa2b..f62cf0da5b1 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -227,6 +227,8 @@ Sends the `action` to the first responder of application. This is used for emulating default Cocoa menu behaviors, usually you would just use the `role` property of `MenuItem`. +See the [OS X Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) for more information on OS X's native actions. + ### `Menu.buildFromTemplate(template)` * `template` Array From f47851f1e70854627ac3860f3c9be8bfe0e04831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Machist=C3=A9=20N=2E=20Quintana?= Date: Mon, 7 Mar 2016 16:19:00 -0800 Subject: [PATCH 0075/1265] :memo: :art: Hard wrap --- docs/api/menu.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/api/menu.md b/docs/api/menu.md index f62cf0da5b1..529113509f8 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -227,7 +227,8 @@ Sends the `action` to the first responder of application. This is used for emulating default Cocoa menu behaviors, usually you would just use the `role` property of `MenuItem`. -See the [OS X Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) for more information on OS X's native actions. +See the [OS X Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) +for more information on OS X's native actions. ### `Menu.buildFromTemplate(template)` From dda7740399b08516da4eb3ce6a7a5f847090dd63 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 12:03:13 -0800 Subject: [PATCH 0076/1265] Add failing spec for native image path normalization --- spec/native-image-spec.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 spec/native-image-spec.js diff --git a/spec/native-image-spec.js b/spec/native-image-spec.js new file mode 100644 index 00000000000..bdc0a06b424 --- /dev/null +++ b/spec/native-image-spec.js @@ -0,0 +1,13 @@ +const assert = require('assert'); +const nativeImage = require('electron').nativeImage; +const path = require('path'); + +describe('nativeImage module', function () { + describe('createFromPath(path)', function () { + it('normalizes paths', function () { + const nonAbsolutePath = path.join(__dirname, 'fixtures', 'api') + path.sep + '..' + path.sep + path.join('assets', 'logo.png'); + const image = nativeImage.createFromPath(nonAbsolutePath); + assert(!image.isEmpty()); + }); + }); +}); From b90c0c78959b422e50dde8c72714b1f96219ef83 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 12:05:36 -0800 Subject: [PATCH 0077/1265] Use MakeAbsoluteFilePath when creating native image from path --- atom/common/api/atom_api_native_image.cc | 16 ++++++++++++---- spec/native-image-spec.js | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index a810069e71b..b229c4bb398 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -13,6 +13,7 @@ #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/node_includes.h" #include "base/base64.h" +#include "base/files/file_util.h" #include "base/strings/string_util.h" #include "base/strings/pattern.h" #include "native_mate/dictionary.h" @@ -254,17 +255,24 @@ mate::Handle NativeImage::CreateFromJPEG( mate::Handle NativeImage::CreateFromPath( v8::Isolate* isolate, const base::FilePath& path) { gfx::ImageSkia image_skia; - if (path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { + + base::FilePath absolute_path = MakeAbsoluteFilePath(path); + // MakeAbsoluteFilePath returns an empty path on failures + if (absolute_path.empty()) { + absolute_path = path; + } + + if (absolute_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { #if defined(OS_WIN) - ReadImageSkiaFromICO(&image_skia, path); + ReadImageSkiaFromICO(&image_skia, absolute_path); #endif } else { - PopulateImageSkiaRepsFromPath(&image_skia, path); + PopulateImageSkiaRepsFromPath(&image_skia, absolute_path); } gfx::Image image(image_skia); mate::Handle handle = Create(isolate, image); #if defined(OS_MACOSX) - if (IsTemplateFilename(path)) + if (IsTemplateFilename(absolute_path)) handle->SetTemplateImage(true); #endif return handle; diff --git a/spec/native-image-spec.js b/spec/native-image-spec.js index bdc0a06b424..e72682a10a1 100644 --- a/spec/native-image-spec.js +++ b/spec/native-image-spec.js @@ -4,7 +4,7 @@ const path = require('path'); describe('nativeImage module', function () { describe('createFromPath(path)', function () { - it('normalizes paths', function () { + it('normalizes the path', function () { const nonAbsolutePath = path.join(__dirname, 'fixtures', 'api') + path.sep + '..' + path.sep + path.join('assets', 'logo.png'); const image = nativeImage.createFromPath(nonAbsolutePath); assert(!image.isEmpty()); From 145d5abe8007b55fe75403ebec4021199053f4f9 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 12:09:53 -0800 Subject: [PATCH 0078/1265] Mention explicit using original path on failures --- atom/common/api/atom_api_native_image.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index b229c4bb398..b1f0e9c5a6f 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -257,7 +257,7 @@ mate::Handle NativeImage::CreateFromPath( gfx::ImageSkia image_skia; base::FilePath absolute_path = MakeAbsoluteFilePath(path); - // MakeAbsoluteFilePath returns an empty path on failures + // MakeAbsoluteFilePath returns an empty path on failures so use original path if (absolute_path.empty()) { absolute_path = path; } From 8f820e09be43616ffd65ffc00cd43e6153b1a615 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 14:54:12 -0800 Subject: [PATCH 0079/1265] Use template string and arrow functions --- spec/native-image-spec.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/spec/native-image-spec.js b/spec/native-image-spec.js index e72682a10a1..88588eb1922 100644 --- a/spec/native-image-spec.js +++ b/spec/native-image-spec.js @@ -1,11 +1,13 @@ +'use strict'; + const assert = require('assert'); const nativeImage = require('electron').nativeImage; const path = require('path'); -describe('nativeImage module', function () { - describe('createFromPath(path)', function () { - it('normalizes the path', function () { - const nonAbsolutePath = path.join(__dirname, 'fixtures', 'api') + path.sep + '..' + path.sep + path.join('assets', 'logo.png'); +describe('nativeImage module', () => { + describe('createFromPath(path)', () => { + it('normalizes the path', () => { + const nonAbsolutePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(nonAbsolutePath); assert(!image.isEmpty()); }); From 8215d661caee2b02f73a0b9a47024a953f7e0e8a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 4 Mar 2016 14:58:34 -0800 Subject: [PATCH 0080/1265] Add api- prefix to spec --- spec/{native-image-spec.js => api-native-image-spec.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spec/{native-image-spec.js => api-native-image-spec.js} (100%) diff --git a/spec/native-image-spec.js b/spec/api-native-image-spec.js similarity index 100% rename from spec/native-image-spec.js rename to spec/api-native-image-spec.js From 7692edf50ec4805fb362150180a1e6b5249d842e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:28:08 -0800 Subject: [PATCH 0081/1265] Assert image size as well --- spec/api-native-image-spec.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 88588eb1922..688819cab1b 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -10,6 +10,8 @@ describe('nativeImage module', () => { const nonAbsolutePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(nonAbsolutePath); assert(!image.isEmpty()); + assert.equal(image.getSize().height, 190); + assert.equal(image.getSize().width, 538); }); }); }); From 9c88a5c1ab8fb1537418cb5d2c705251d24b56c6 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 09:35:35 -0800 Subject: [PATCH 0082/1265] Check ReferencesParent before calling MakeAbsoluteFilePath --- atom/common/api/atom_api_native_image.cc | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index b1f0e9c5a6f..d26fdab8c60 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -120,6 +120,20 @@ bool PopulateImageSkiaRepsFromPath(gfx::ImageSkia* image, return succeed; } +base::FilePath MakePathAbsolute(const base::FilePath& path) { + if (!path.ReferencesParent()) { + return path; + } + + base::FilePath absolute_path = MakeAbsoluteFilePath(path); + // MakeAbsoluteFilePath returns an empty path on failures so use original path + if (absolute_path.empty()) { + return path; + } else { + return absolute_path; + } +} + #if defined(OS_MACOSX) bool IsTemplateFilename(const base::FilePath& path) { return (base::MatchPattern(path.value(), "*Template.*") || @@ -255,12 +269,7 @@ mate::Handle NativeImage::CreateFromJPEG( mate::Handle NativeImage::CreateFromPath( v8::Isolate* isolate, const base::FilePath& path) { gfx::ImageSkia image_skia; - - base::FilePath absolute_path = MakeAbsoluteFilePath(path); - // MakeAbsoluteFilePath returns an empty path on failures so use original path - if (absolute_path.empty()) { - absolute_path = path; - } + base::FilePath absolute_path = MakePathAbsolute(path); if (absolute_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { #if defined(OS_WIN) From 97930fcd84402674960b1a3503c5ea6df7012492 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 14:19:24 -0800 Subject: [PATCH 0083/1265] Add specs for more image path cases --- spec/api-native-image-spec.js | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 688819cab1b..4b21231e406 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -6,9 +6,30 @@ const path = require('path'); describe('nativeImage module', () => { describe('createFromPath(path)', () => { - it('normalizes the path', () => { - const nonAbsolutePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; - const image = nativeImage.createFromPath(nonAbsolutePath); + it('returns an empty image for invalid paths', () => { + assert(nativeImage.createFromPath('').isEmpty()); + assert(nativeImage.createFromPath('does-not-exist.png').isEmpty()); + }); + + it('loads images from paths relative to the current working directory', () => { + const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`; + const image = nativeImage.createFromPath(imagePath); + assert(!image.isEmpty()); + assert.equal(image.getSize().height, 190); + assert.equal(image.getSize().width, 538); + }) + + it('loads images from paths with `.` segments', () => { + const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; + const image = nativeImage.createFromPath(imagePath); + assert(!image.isEmpty()); + assert.equal(image.getSize().height, 190); + assert.equal(image.getSize().width, 538); + }); + + it('loads images from path with `..` segments', () => { + const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; + const image = nativeImage.createFromPath(imagePath); assert(!image.isEmpty()); assert.equal(image.getSize().height, 190); assert.equal(image.getSize().width, 538); From 0dba0b9cad445eae58bff85dcf3333622a8b4833 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 14:21:24 -0800 Subject: [PATCH 0084/1265] MakePathAbsolute -> NormalizePath --- atom/common/api/atom_api_native_image.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index d26fdab8c60..53f77bd41f8 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -120,7 +120,7 @@ bool PopulateImageSkiaRepsFromPath(gfx::ImageSkia* image, return succeed; } -base::FilePath MakePathAbsolute(const base::FilePath& path) { +base::FilePath NormalizePath(const base::FilePath& path) { if (!path.ReferencesParent()) { return path; } @@ -269,7 +269,7 @@ mate::Handle NativeImage::CreateFromJPEG( mate::Handle NativeImage::CreateFromPath( v8::Isolate* isolate, const base::FilePath& path) { gfx::ImageSkia image_skia; - base::FilePath absolute_path = MakePathAbsolute(path); + base::FilePath absolute_path = NormalizePath(path); if (absolute_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { #if defined(OS_WIN) From 022c2c0d8cb9a52d3939ec64180744632377a8b4 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 14:22:16 -0800 Subject: [PATCH 0085/1265] absolute_path -> normalize_path --- atom/common/api/atom_api_native_image.cc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 53f77bd41f8..3d000b6d5d9 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -269,19 +269,19 @@ mate::Handle NativeImage::CreateFromJPEG( mate::Handle NativeImage::CreateFromPath( v8::Isolate* isolate, const base::FilePath& path) { gfx::ImageSkia image_skia; - base::FilePath absolute_path = NormalizePath(path); + base::FilePath image_path = NormalizePath(path); - if (absolute_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { + if (image_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) { #if defined(OS_WIN) - ReadImageSkiaFromICO(&image_skia, absolute_path); + ReadImageSkiaFromICO(&image_skia, image_path); #endif } else { - PopulateImageSkiaRepsFromPath(&image_skia, absolute_path); + PopulateImageSkiaRepsFromPath(&image_skia, image_path); } gfx::Image image(image_skia); mate::Handle handle = Create(isolate, image); #if defined(OS_MACOSX) - if (IsTemplateFilename(absolute_path)) + if (IsTemplateFilename(image_path)) handle->SetTemplateImage(true); #endif return handle; From 44376374b0010dcbe8830838fb4d8940e3d1ecf7 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 14:22:55 -0800 Subject: [PATCH 0086/1265] path -> paths --- spec/api-native-image-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 4b21231e406..c2950c674b4 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -27,7 +27,7 @@ describe('nativeImage module', () => { assert.equal(image.getSize().width, 538); }); - it('loads images from path with `..` segments', () => { + it('loads images from paths with `..` segments', () => { const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); assert(!image.isEmpty()); From 4c23e3950a2b2d0ef5d311877ab078d1cdaa1548 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 16:45:10 -0800 Subject: [PATCH 0087/1265] Add missing semicolon --- spec/api-native-image-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index c2950c674b4..043a914578c 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -17,7 +17,7 @@ describe('nativeImage module', () => { assert(!image.isEmpty()); assert.equal(image.getSize().height, 190); assert.equal(image.getSize().width, 538); - }) + }); it('loads images from paths with `.` segments', () => { const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; From 11f64b714da79cf959cfbe8a6270ddc7fc87bb34 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 8 Mar 2016 10:47:23 +0800 Subject: [PATCH 0088/1265] menuItem add --- docs-translations/zh-CN/api/menu-item.md | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 docs-translations/zh-CN/api/menu-item.md diff --git a/docs-translations/zh-CN/api/menu-item.md b/docs-translations/zh-CN/api/menu-item.md new file mode 100644 index 00000000000..3d5eceedcb9 --- /dev/null +++ b/docs-translations/zh-CN/api/menu-item.md @@ -0,0 +1,57 @@ +# 菜单项 +菜单项模块允许你向应用或[menu][1]添加选项。 + +查看[menu][1]例子。 + +## 类:MenuItem +使用下面的方法创建一个新的 `MenuItem` + +###new MenuItem(options) +* `options` Object + * `click` Function - 当菜单项被点击的时候,使用 `click(menuItem,browserWindow)` 调用 + * `role` String - 定义菜单项的行为,在指定 `click` 属性时将会被忽略 + * `type` String - 取值 `normal`,`separator`,`checkbox`or`radio` + * `label` String + * `sublabel` String + * `accelerator` [Accelerator][2] + * `icon` [NativeImage][3] + * `enabled` Boolean + * `visible` Boolean + * `checked` Boolean + * `submenu` Menu - 应当作为 `submenu` 菜单项的特定类型,当它作为 `type: 'submenu'` 菜单项的特定类型时可以忽略。如果它的值不是 `Menu`,将自动转为 `Menu.buildFromTemplate`。 + * `id` String - 标志一个菜单的唯一性。如果被定义使用,它将被用作这个菜单项的参考位置属性。 + * `position` String - 定义给定的菜单的具体指定位置信息。 + +在创建菜单项时,如果有匹配的方法,建议指定 `role` 属性,不需要人为操作它的行为,这样菜单使用可以给用户最好的体验。 + + +`role`属性值可以为: + +* `undo` +* `redo` +* `cut` +* `copy` +* `paste` +* `selectall` +* `minimize` - 最小化当前窗口 +* `close` - 关闭当前窗口 + +在 OS X 上,`role` 还可以有以下值: + +* `about` - 匹配 `orderFrontStandardAboutPanel` 行为 +* `hide` - 匹配 `hide` 行为 +* `hideothers` - 匹配 `hideOtherApplications` 行为 +* `unhide` - 匹配 `unhideAllApplications` 行为 +* `front` - 匹配 `arrangeInFront` 行为 +* `window` - "Window" 菜单项 +* `help` - "Help" 菜单项 +* `services` - "Services" 菜单项 + + + + + + + [1]:https://github.com/heyunjiang/electron/blob/master/docs-translations/zh-CN/api/menu.md + [2]:https://github.com/heyunjiang/electron/blob/master/docs/api/accelerator.md + [3]:https://github.com/heyunjiang/electron/blob/master/docs/api/native-image.md \ No newline at end of file From 0c92d440772ea36a521bfb8fb11d436b8f396c73 Mon Sep 17 00:00:00 2001 From: Dongjoon Hyun Date: Mon, 7 Mar 2016 20:22:03 -0800 Subject: [PATCH 0089/1265] Fix typos in comments. --- atom/browser/api/lib/menu.js | 2 +- atom/browser/atom_browser_main_parts.h | 2 +- atom/browser/ui/views/global_menu_bar_x11.h | 2 +- atom/common/crash_reporter/win/crash_service.cc | 2 +- .../chrome/browser/chrome_notification_types.h | 12 ++++++------ 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/atom/browser/api/lib/menu.js b/atom/browser/api/lib/menu.js index 62c771af6c6..5af577872db 100644 --- a/atom/browser/api/lib/menu.js +++ b/atom/browser/api/lib/menu.js @@ -7,7 +7,7 @@ const bindings = process.atomBinding('menu'); // Automatically generated radio menu item's group id. var nextGroupId = 0; -// Search between seperators to find a radio menu item and return its group id, +// Search between separators to find a radio menu item and return its group id, // otherwise generate a group id. var generateGroupId = function(items, pos) { var i, item, j, k, ref1, ref2, ref3; diff --git a/atom/browser/atom_browser_main_parts.h b/atom/browser/atom_browser_main_parts.h index c1c0c89c678..e1053a257b9 100644 --- a/atom/browser/atom_browser_main_parts.h +++ b/atom/browser/atom_browser_main_parts.h @@ -31,7 +31,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts { static AtomBrowserMainParts* Get(); - // Sets the exit code, will fail if the the message loop is not ready. + // Sets the exit code, will fail if the message loop is not ready. bool SetExitCode(int code); // Gets the exit code diff --git a/atom/browser/ui/views/global_menu_bar_x11.h b/atom/browser/ui/views/global_menu_bar_x11.h index d9e818ce3eb..9049fbf606d 100644 --- a/atom/browser/ui/views/global_menu_bar_x11.h +++ b/atom/browser/ui/views/global_menu_bar_x11.h @@ -40,7 +40,7 @@ class GlobalMenuBarX11 { explicit GlobalMenuBarX11(NativeWindowViews* window); virtual ~GlobalMenuBarX11(); - // Creates the object path for DbusemenuServer which is attached to |xid|. + // Creates the object path for DbusmenuServer which is attached to |xid|. static std::string GetPathForWindow(gfx::AcceleratedWidget xid); void SetMenu(ui::MenuModel* menu_model); diff --git a/atom/common/crash_reporter/win/crash_service.cc b/atom/common/crash_reporter/win/crash_service.cc index 67e22381aef..b8032f696fc 100644 --- a/atom/common/crash_reporter/win/crash_service.cc +++ b/atom/common/crash_reporter/win/crash_service.cc @@ -211,7 +211,7 @@ bool CrashService::Initialize(const base::string16& application_name, std::wstring pipe_name = kTestPipeName; int max_reports = -1; - // The checkpoint file allows CrashReportSender to enforce the the maximum + // The checkpoint file allows CrashReportSender to enforce the maximum // reports per day quota. Does not seem to serve any other purpose. base::FilePath checkpoint_path = operating_dir.Append(kCheckPointFile); diff --git a/chromium_src/chrome/browser/chrome_notification_types.h b/chromium_src/chrome/browser/chrome_notification_types.h index eb5ed40342d..05df960c5ea 100644 --- a/chromium_src/chrome/browser/chrome_notification_types.h +++ b/chromium_src/chrome/browser/chrome_notification_types.h @@ -32,7 +32,7 @@ enum NotificationType { NOTIFICATION_BROWSER_CLOSING, // This message is sent after a window has been closed. The source is a - // Source containing the affected Browser. No details are exptected. + // Source containing the affected Browser. No details are expected. NOTIFICATION_BROWSER_CLOSED, // This message is sent when closing a browser has been cancelled, either by @@ -411,7 +411,7 @@ enum NotificationType { // the source is a Profile. NOTIFICATION_EXTENSION_LOADED_DEPRECATED, - // An error occured while attempting to load an extension. The details are a + // An error occurred while attempting to load an extension. The details are a // string with details about why the load failed. NOTIFICATION_EXTENSION_LOAD_ERROR, @@ -434,7 +434,7 @@ enum NotificationType { // The details are an InstalledExtensionInfo, and the source is a Profile. NOTIFICATION_EXTENSION_INSTALLED, - // An error occured during extension install. The details are a string with + // An error occurred during extension install. The details are a string with // details about why the install failed. NOTIFICATION_EXTENSION_INSTALL_ERROR, @@ -625,7 +625,7 @@ enum NotificationType { // TabSpecificContentSettings object, there are no details. NOTIFICATION_COLLECTED_COOKIES_SHOWN, - // Sent when a non-default setting in the the notification content settings + // Sent when a non-default setting in the notification content settings // map has changed. The source is the DesktopNotificationService, the // details are None. NOTIFICATION_DESKTOP_NOTIFICATION_SETTINGS_CHANGED, @@ -776,7 +776,7 @@ enum NotificationType { NOTIFICATION_USER_LIST_CHANGED, // Sent when the screen lock state has changed. The source is - // ScreenLocker and the details is a bool specifing that the + // ScreenLocker and the details is a bool specifying that the // screen is locked. When details is a false, the source object // is being deleted, so the receiver shouldn't use the screen locker // object. @@ -838,7 +838,7 @@ enum NotificationType { // which was installed. NOTIFICATION_APP_INSTALLED_TO_NTP, - // Similar to NOTIFICATION_APP_INSTALLED_TO_NTP but used to nofity ash AppList + // Similar to NOTIFICATION_APP_INSTALLED_TO_NTP but used to notify ash AppList // about installed app. Source is the profile in which the app is installed // and Details is the string ID of the extension. NOTIFICATION_APP_INSTALLED_TO_APPLIST, From 89328c873c6ce6ee379e6cdf69ab064c88aa9373 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 8 Mar 2016 16:30:09 +0800 Subject: [PATCH 0090/1265] add api doc begin 2.5 --- docs-translations/zh-CN/api/synopsis.md | 71 ++++++++ .../tutorial/chrome-command-line-switches.md | 158 ++++++++++++++++++ docs-translations/zh-CN/tutorial/process.md | 48 ++++++ 3 files changed, 277 insertions(+) create mode 100644 docs-translations/zh-CN/api/synopsis.md create mode 100644 docs-translations/zh-CN/tutorial/chrome-command-line-switches.md create mode 100644 docs-translations/zh-CN/tutorial/process.md diff --git a/docs-translations/zh-CN/api/synopsis.md b/docs-translations/zh-CN/api/synopsis.md new file mode 100644 index 00000000000..a1a2a6d0122 --- /dev/null +++ b/docs-translations/zh-CN/api/synopsis.md @@ -0,0 +1,71 @@ +# 简介 + +所有的[Node.js's built-in modules][1]在Electron中都可用,并且所有的node的第三方组件也可以放心使用(包括[自身的模块][2])。 + +Electron也提供了一些额外的内置组件来开发传统桌面应用。一些组件只可以在主进程中使用,一些只可以在渲染进程中使用,但是也有部分可以在这2种进程中都可使用。 + +基本规则:GUI模块或者系统底层的模块只可以在主进程中使用。要使用这些模块,你应当很熟悉[主进程vs渲染进程][3]脚本的概念。 + +主进程脚本看起来像个普通的nodejs脚本 + +```javascript +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; + +var window = null; + +app.on('ready', function() { + window = new BrowserWindow({width: 800, height: 600}); + window.loadURL('https://github.com'); +}); +``` + +渲染进程和传统的web界面一样,除了它具有使用node模块的能力: + +```html + + + + + + +``` + +如果想运行应用,参考 `Run your app` 。 + +## 解构任务 + +如果你使用的是CoffeeScript或Babel,你可以使用[destructuring assignment][4]来让使用内置模块更简单: + +```javascript +const {app, BrowserWindow} = require('electron'); +``` + +然而如果你使用的是普通的JavaScript,你就需要等到Chrome支持ES6了。 + +##使用内置模块时禁用旧样式 + +在版本v0.35.0之前,所有的内置模块都需要按造 `require('module-name')` 形式来使用,虽然它有很多[弊端][5],我们仍然在老的应用中友好的支持它。 + +为了完整的禁用旧样式,你可以设置环境变量 `ELECTRON_HIDE_INTERNAL_MODULES ` : + +```javascript +process.env.ELECTRON_HIDE_INTERNAL_MODULES = 'true' +``` + +或者调用 `hideInternalModules` API: + +```javascript +require('electron').hideInternalModules() +``` + + + [1]:http://nodejs.org/api/ + [2]:https://github.com/heyunjiang/electron/blob/master/docs/tutorial/using-native-node-modules.md + [3]:https://github.com/heyunjiang/electron/blob/master/docs/tutorial/quick-start.md#the-main-process + [4]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment + [5]:https://github.com/atom/electron/issues/387 \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md b/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md new file mode 100644 index 00000000000..14e4a431bcc --- /dev/null +++ b/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md @@ -0,0 +1,158 @@ +# 支持的 Chrome 命令行开关 + +这页列出了Chrome浏览器和Electron支持的命令行开关. 你也可以在[app][app]模块的[ready][ready]事件发出之前使用[app.commandLine.appendSwitch][append-switch] 来添加它们到你应用的main脚本里面: + +```javascript +const app = require('electron').app; +app.commandLine.appendSwitch('remote-debugging-port', '8315'); +app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); + +app.on('ready', function() { + // Your code here +}); +``` + +## --client-certificate=`path` + +设置客户端的证书文件 `path` . + +## --ignore-connections-limit=`domains` + +忽略用 `,` 分隔的 `domains` 列表的连接限制. + +## --disable-http-cache + +禁用 HTTP 请求的 磁盘缓存. + +## --remote-debugging-port=`port` + +在指定的 `端口` 通过 HTTP 开启远程调试. + +## --js-flags=`flags` + +Specifies the flags passed to JS engine. It has to be passed when starting +Electron if you want to enable the `flags` in the main process. + +```bash +$ electron --js-flags="--harmony_proxies --harmony_collections" your-app +``` + +## --proxy-server=`address:port` + +Use a specified proxy server, which overrides the system setting. This switch +only affects requests with HTTP protocol, including HTTPS and WebSocket +requests. It is also noteworthy that not all proxy servers support HTTPS and +WebSocket requests. + +## --proxy-bypass-list=`hosts` + +Instructs Electron to bypass the proxy server for the given semi-colon-separated +list of hosts. This flag has an effect only if used in tandem with +`--proxy-server`. + +For example: + +```javascript +app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') +``` + +Will use the proxy server for all hosts except for local addresses (`localhost`, +`127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix +`foo.com` and anything at `1.2.3.4:5678`. + +## --proxy-pac-url=`url` + +Uses the PAC script at the specified `url`. + +## --no-proxy-server + +Don't use a proxy server and always make direct connections. Overrides any other +proxy server flags that are passed. + +## --host-rules=`rules` + +A comma-separated list of `rules` that control how hostnames are mapped. + +For example: + +* `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 +* `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to + "proxy". +* `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will + also force the port of the resulting socket address to be 77. +* `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for + "www.google.com". + +These mappings apply to the endpoint host in a net request (the TCP connect +and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy +connection, and the endpoint host in a `SOCKS` proxy connection). + +## --host-resolver-rules=`rules` + +Like `--host-rules` but these `rules` only apply to the host resolver. + +## --ignore-certificate-errors + +Ignores certificate related errors. + +## --ppapi-flash-path=`path` + +Sets the `path` of the pepper flash plugin. + +## --ppapi-flash-version=`version` + +Sets the `version` of the pepper flash plugin. + +## --log-net-log=`path` + +Enables net log events to be saved and writes them to `path`. + +## --ssl-version-fallback-min=`version` + +Sets the minimum SSL/TLS version ("tls1", "tls1.1" or "tls1.2") that TLS +fallback will accept. + +## --cipher-suite-blacklist=`cipher_suites` + +Specifies comma-separated list of SSL cipher suites to disable. + +## --disable-renderer-backgrounding + +Prevents Chromium from lowering the priority of invisible pages' renderer +processes. + +This flag is global to all renderer processes, if you only want to disable +throttling in one window, you can take the hack of +[playing silent audio][play-silent-audio]. + +## --enable-logging + +Prints Chromium's logging into console. + +This switch can not be used in `app.commandLine.appendSwitch` since it is parsed +earlier than user's app is loaded, but you can set the `ELECTRON_ENABLE_LOGGING` +environment variable to achieve the same effect. + +## --v=`log_level` + +Gives the default maximal active V-logging level; 0 is the default. Normally +positive values are used for V-logging levels. + +This switch only works when `--enable-logging` is also passed. + +## --vmodule=`pattern` + +Gives the per-module maximal V-logging levels to override the value given by +`--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in +source files `my_module.*` and `foo*.*`. + +Any pattern containing a forward or backward slash will be tested against the +whole pathname and not just the module. E.g. `*/foo/bar/*=2` would change the +logging level for all code in the source files under a `foo/bar` directory. + +This switch only works when `--enable-logging` is also passed. + +[app]: app.md +[append-switch]: app.md#appcommandlineappendswitchswitch-value +[ready]: app.md#event-ready +[play-silent-audio]: https://github.com/atom/atom/pull/9485/files \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/process.md b/docs-translations/zh-CN/tutorial/process.md new file mode 100644 index 00000000000..d07741247aa --- /dev/null +++ b/docs-translations/zh-CN/tutorial/process.md @@ -0,0 +1,48 @@ +# 进程 + +Electron 中的 `process` 对象 与 upstream node 中的有以下的不同点: + +* `process.type` String - 进程类型, 可以是 `browser` (i.e. main process) + 或 `renderer`. +* `process.versions['electron']` String - Electron的版本. +* `process.versions['chrome']` String - Chromium的版本. +* `process.resourcesPath` String - JavaScript源代码路径. +* `process.mas` Boolean - 在Mac App Store 创建, 它的值为 `true`, 在其它的地方值为 `undefined`. + +## 事件 + +### 事件: 'loaded' + +在Electron已经加载了其内部预置脚本和它准备加载主进程或渲染进程的时候触发. + +当node被完全关闭的时候,它可以被预加载脚本使用来添加(原文: removed)与node无关的全局符号来回退到全局范围: + +```js +// preload.js +var _setImmediate = setImmediate; +var _clearImmediate = clearImmediate; +process.once('loaded', function() { + global.setImmediate = _setImmediate; + global.clearImmediate = _clearImmediate; +}); +``` + +## 属性 + +### `process.noAsar` + +设置它为 `true` 可以使 `asar` 文件在node的内置模块中实效. + +## 方法 + +`process` 对象有如下方法: + +### `process.hang()` + +使当前进程的主线成挂起. + +### `process.setFdLimit(maxDescriptors)` _OS X_ _Linux_ + +* `maxDescriptors` Integer + +设置文件描述符软限制于 `maxDescriptors` 或硬限制与os, 无论它是否低于当前进程. \ No newline at end of file From d35996b4a0cfe5388f879f47110d80f235505690 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 8 Mar 2016 19:57:53 +0800 Subject: [PATCH 0091/1265] position modify --- .../zh-CN/api/chrome-command-line-switches.md | 144 ++++++++++++++++ .../zh-CN/{tutorial => api}/process.md | 0 .../tutorial/chrome-command-line-switches.md | 158 ------------------ 3 files changed, 144 insertions(+), 158 deletions(-) create mode 100644 docs-translations/zh-CN/api/chrome-command-line-switches.md rename docs-translations/zh-CN/{tutorial => api}/process.md (100%) delete mode 100644 docs-translations/zh-CN/tutorial/chrome-command-line-switches.md diff --git a/docs-translations/zh-CN/api/chrome-command-line-switches.md b/docs-translations/zh-CN/api/chrome-command-line-switches.md new file mode 100644 index 00000000000..234f3c63b1e --- /dev/null +++ b/docs-translations/zh-CN/api/chrome-command-line-switches.md @@ -0,0 +1,144 @@ +# 支持的 Chrome 命令行开关 + +这页列出了Chrome浏览器和Electron支持的命令行开关. 你也可以在[app][app]模块的[ready][ready]事件发出之前使用[app.commandLine.appendSwitch][append-switch] 来添加它们到你应用的main脚本里面: + +```javascript +const app = require('electron').app; +app.commandLine.appendSwitch('remote-debugging-port', '8315'); +app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); + +app.on('ready', function() { + // Your code here +}); +``` + +## --client-certificate=`path` + +设置客户端的证书文件 `path` . + +## --ignore-connections-limit=`domains` + +忽略用 `,` 分隔的 `domains` 列表的连接限制. + +## --disable-http-cache + +禁用 HTTP 请求. + +## --remote-debugging-port=`port` + +在指定的 `端口` 通过 HTTP 开启远程调试. + +## --js-flags=`flags` + +指定引擎过渡到 JS 引擎. + +在启动Electron时,如果你想在主进程中激活 `flags` ,它将被转换. + +```bash +$ electron --js-flags="--harmony_proxies --harmony_collections" your-app +``` + +## --proxy-server=`address:port` + +使用一个特定的代理服务器,它将比系统设置的优先级更高.这个开关只有在使用 HTTP 协议时有效,它包含 HTTPS 和 WebSocket 请求. 值得注意的是,不是所有的代理服务器都支持 HTTPS 和 WebSocket 请求. + +## --proxy-bypass-list=`hosts` + +让 Electron 使用(原文:bypass) 提供的以 semi-colon 分隔的hosts列表的代理服务器.这个开关只有在使用 `--proxy-server` 时有效. + +例如: + +```javascript +app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') +``` + + +将会为所有的hosts使用代理服务器,除了本地地址 (`localhost`, +`127.0.0.1` etc.), `google.com` 子域, 以 `foo.com` 结尾的hosts,和所有类似 `1.2.3.4:5678`的. + +## --proxy-pac-url=`url` + +在指定的 `url` 上使用 PAC 脚本. + +## --no-proxy-server + +不使用代理服务并且总是使用直接连接.忽略所有的合理代理标志. + +## --host-rules=`rules` + +一个逗号分隔的 `rule` 列表来控制主机名如何映射. + +例如: + +* `MAP * 127.0.0.1` 强制所有主机名映射到 127.0.0.1 +* `MAP *.google.com proxy` 强制所有 google.com 子域 使用 "proxy". +* `MAP test.com [::1]:77` 强制 "test.com" 使用 IPv6 回环地址. 也强制使用端口 77. +* `MAP * baz, EXCLUDE www.google.com` 重新全部映射到 "baz", 除了 + "www.google.com". + +这些映射适用于终端网络请求 +(TCP 连接 +和 主机解析 以直接连接的方式, 和 `CONNECT` 以代理连接, 还有 终端 host 使用 `SOCKS` 代理连接). + +## --host-resolver-rules=`rules` + +类似 `--host-rules` ,但是 `rules` 只适合主机解析. + +## --ignore-certificate-errors + +忽略与证书相关的错误. + +## --ppapi-flash-path=`path` + +设置Pepper Flash插件的路径 `path` . + +## --ppapi-flash-version=`version` + +设置Pepper Flash插件版本号. + +## --log-net-log=`path` + +使网络日志事件能够被读写到 `path`. + +## --ssl-version-fallback-min=`version` + +设置最简化的 SSL/TLS 版本号 ("tls1", "tls1.1" or "tls1.2"),TLS 可接受回退. + +## --cipher-suite-blacklist=`cipher_suites` + +指定逗号分隔的 SSL 密码套件 列表实效. + +## --disable-renderer-backgrounding + +防止 Chromium 降低隐藏的渲染进程优先级. + +这个标志对所有渲染进程全局有效,如果你只想在一个窗口中禁止使用,你可以采用 hack 方法[playing silent audio][play-silent-audio]. + +## --enable-logging + +打印 Chromium 信息输出到控制台. + +如果在用户应用加载完成之前解析`app.commandLine.appendSwitch` ,这个开关将实效,但是你可以设置 `ELECTRON_ENABLE_LOGGING` 环境变量来达到相同的效果. + +## --v=`log_level` + +设置默认最大活跃 V-logging 标准; 默认为 0.通常 V-logging 标准值为肯定值. + +This switch only works when `--enable-logging` is also passed. + +## --vmodule=`pattern` + +Gives the per-module maximal V-logging levels to override the value given by +`--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in +source files `my_module.*` and `foo*.*`. + +Any pattern containing a forward or backward slash will be tested against the +whole pathname and not just the module. E.g. `*/foo/bar/*=2` would change the +logging level for all code in the source files under a `foo/bar` directory. + +This switch only works when `--enable-logging` is also passed. + +[app]: app.md +[append-switch]: app.md#appcommandlineappendswitchswitch-value +[ready]: app.md#event-ready +[play-silent-audio]: https://github.com/atom/atom/pull/9485/files \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/process.md b/docs-translations/zh-CN/api/process.md similarity index 100% rename from docs-translations/zh-CN/tutorial/process.md rename to docs-translations/zh-CN/api/process.md diff --git a/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md b/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md deleted file mode 100644 index 14e4a431bcc..00000000000 --- a/docs-translations/zh-CN/tutorial/chrome-command-line-switches.md +++ /dev/null @@ -1,158 +0,0 @@ -# 支持的 Chrome 命令行开关 - -这页列出了Chrome浏览器和Electron支持的命令行开关. 你也可以在[app][app]模块的[ready][ready]事件发出之前使用[app.commandLine.appendSwitch][append-switch] 来添加它们到你应用的main脚本里面: - -```javascript -const app = require('electron').app; -app.commandLine.appendSwitch('remote-debugging-port', '8315'); -app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); - -app.on('ready', function() { - // Your code here -}); -``` - -## --client-certificate=`path` - -设置客户端的证书文件 `path` . - -## --ignore-connections-limit=`domains` - -忽略用 `,` 分隔的 `domains` 列表的连接限制. - -## --disable-http-cache - -禁用 HTTP 请求的 磁盘缓存. - -## --remote-debugging-port=`port` - -在指定的 `端口` 通过 HTTP 开启远程调试. - -## --js-flags=`flags` - -Specifies the flags passed to JS engine. It has to be passed when starting -Electron if you want to enable the `flags` in the main process. - -```bash -$ electron --js-flags="--harmony_proxies --harmony_collections" your-app -``` - -## --proxy-server=`address:port` - -Use a specified proxy server, which overrides the system setting. This switch -only affects requests with HTTP protocol, including HTTPS and WebSocket -requests. It is also noteworthy that not all proxy servers support HTTPS and -WebSocket requests. - -## --proxy-bypass-list=`hosts` - -Instructs Electron to bypass the proxy server for the given semi-colon-separated -list of hosts. This flag has an effect only if used in tandem with -`--proxy-server`. - -For example: - -```javascript -app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') -``` - -Will use the proxy server for all hosts except for local addresses (`localhost`, -`127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix -`foo.com` and anything at `1.2.3.4:5678`. - -## --proxy-pac-url=`url` - -Uses the PAC script at the specified `url`. - -## --no-proxy-server - -Don't use a proxy server and always make direct connections. Overrides any other -proxy server flags that are passed. - -## --host-rules=`rules` - -A comma-separated list of `rules` that control how hostnames are mapped. - -For example: - -* `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 -* `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to - "proxy". -* `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will - also force the port of the resulting socket address to be 77. -* `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for - "www.google.com". - -These mappings apply to the endpoint host in a net request (the TCP connect -and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy -connection, and the endpoint host in a `SOCKS` proxy connection). - -## --host-resolver-rules=`rules` - -Like `--host-rules` but these `rules` only apply to the host resolver. - -## --ignore-certificate-errors - -Ignores certificate related errors. - -## --ppapi-flash-path=`path` - -Sets the `path` of the pepper flash plugin. - -## --ppapi-flash-version=`version` - -Sets the `version` of the pepper flash plugin. - -## --log-net-log=`path` - -Enables net log events to be saved and writes them to `path`. - -## --ssl-version-fallback-min=`version` - -Sets the minimum SSL/TLS version ("tls1", "tls1.1" or "tls1.2") that TLS -fallback will accept. - -## --cipher-suite-blacklist=`cipher_suites` - -Specifies comma-separated list of SSL cipher suites to disable. - -## --disable-renderer-backgrounding - -Prevents Chromium from lowering the priority of invisible pages' renderer -processes. - -This flag is global to all renderer processes, if you only want to disable -throttling in one window, you can take the hack of -[playing silent audio][play-silent-audio]. - -## --enable-logging - -Prints Chromium's logging into console. - -This switch can not be used in `app.commandLine.appendSwitch` since it is parsed -earlier than user's app is loaded, but you can set the `ELECTRON_ENABLE_LOGGING` -environment variable to achieve the same effect. - -## --v=`log_level` - -Gives the default maximal active V-logging level; 0 is the default. Normally -positive values are used for V-logging levels. - -This switch only works when `--enable-logging` is also passed. - -## --vmodule=`pattern` - -Gives the per-module maximal V-logging levels to override the value given by -`--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in -source files `my_module.*` and `foo*.*`. - -Any pattern containing a forward or backward slash will be tested against the -whole pathname and not just the module. E.g. `*/foo/bar/*=2` would change the -logging level for all code in the source files under a `foo/bar` directory. - -This switch only works when `--enable-logging` is also passed. - -[app]: app.md -[append-switch]: app.md#appcommandlineappendswitchswitch-value -[ready]: app.md#event-ready -[play-silent-audio]: https://github.com/atom/atom/pull/9485/files \ No newline at end of file From c8a2246952eb25eac7aaad43af862cc3303bb9d9 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 8 Mar 2016 20:40:54 +0800 Subject: [PATCH 0092/1265] complete command line switch && add enviroment variables --- .../zh-CN/api/chrome-command-line-switches.md | 12 ++--- .../zh-CN/api/environment-variables.md | 53 +++++++++++++++++++ 2 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 docs-translations/zh-CN/api/environment-variables.md diff --git a/docs-translations/zh-CN/api/chrome-command-line-switches.md b/docs-translations/zh-CN/api/chrome-command-line-switches.md index 234f3c63b1e..e197626302b 100644 --- a/docs-translations/zh-CN/api/chrome-command-line-switches.md +++ b/docs-translations/zh-CN/api/chrome-command-line-switches.md @@ -124,19 +124,15 @@ app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com 设置默认最大活跃 V-logging 标准; 默认为 0.通常 V-logging 标准值为肯定值. -This switch only works when `--enable-logging` is also passed. +这个开关只有在 `--enable-logging` 开启时有效. ## --vmodule=`pattern` -Gives the per-module maximal V-logging levels to override the value given by -`--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in -source files `my_module.*` and `foo*.*`. +赋予每个模块最大的 V-logging levels 来覆盖 `--v` 给的值.E.g. `my_module=2,foo*=3` 会改变所有源文件 `my_module.*` and `foo*.*` 的代码中的 logging level . -Any pattern containing a forward or backward slash will be tested against the -whole pathname and not just the module. E.g. `*/foo/bar/*=2` would change the -logging level for all code in the source files under a `foo/bar` directory. +任何包含向前的(forward slash)或者向后的(backward slash)模式将被测试用于阻止整个路径名,并且不仅是E.g模块.`*/foo/bar/*=2` 将会改变所有在 `foo/bar` 下的源文件代码中的 logging level . -This switch only works when `--enable-logging` is also passed. +这个开关只有在 `--enable-logging` 开启时有效. [app]: app.md [append-switch]: app.md#appcommandlineappendswitchswitch-value diff --git a/docs-translations/zh-CN/api/environment-variables.md b/docs-translations/zh-CN/api/environment-variables.md new file mode 100644 index 00000000000..0a35eb59dfd --- /dev/null +++ b/docs-translations/zh-CN/api/environment-variables.md @@ -0,0 +1,53 @@ +# 环境变量 + +一些 Electron 的行为受到环境变量的控制,因为他们的初始化比命令行和应用代码更早. + +POSIX shells 的例子: + +```bash +$ export ELECTRON_ENABLE_LOGGING=true +$ electron +``` + +Windows 控制台: + +```powershell +> set ELECTRON_ENABLE_LOGGING=true +> electron +``` + +## `ELECTRON_RUN_AS_NODE` + +类似node.js普通进程启动方式. + +## `ELECTRON_ENABLE_LOGGING` + +打印 Chrome 的内部日志到控制台. + +## `ELECTRON_LOG_ASAR_READS` + +当 Electron 读取 ASA 文档,把 read offset 和文档路径做日志记录到系统 `tmpdir`.结果文件将提供给 ASAR 模块来优化文档组织. + +## `ELECTRON_ENABLE_STACK_DUMPING` + +当 Electron 崩溃的时候,打印堆栈记录到控制台. + +如果 `crashReporter` 已经启动那么这个环境变量实效. + +## `ELECTRON_DEFAULT_ERROR_MODE` _Windows_ + +当 Electron 崩溃的时候,显示windows的崩溃对话框. + +如果 `crashReporter` 已经启动那么这个环境变量实效. + +## `ELECTRON_NO_ATTACH_CONSOLE` _Windows_ + +不可使用当前控制台. + +## `ELECTRON_FORCE_WINDOW_MENU_BAR` _Linux_ + +不可再 Linux 上使用全局菜单栏. + +## `ELECTRON_HIDE_INTERNAL_MODULES` + +关闭旧的内置模块如 `require('ipc')` 的通用模块. \ No newline at end of file From 70aa9b06eef549ea66f6b9242043c7be81f0d9d0 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 17:12:09 -0800 Subject: [PATCH 0093/1265] Move JavaScript to root lib/ folder --- {atom/browser/api/lib => lib/browser/api}/app.js | 0 {atom/browser/api/lib => lib/browser/api}/auto-updater.js | 0 .../lib => lib/browser/api}/auto-updater/auto-updater-native.js | 0 .../api/lib => lib/browser/api}/auto-updater/auto-updater-win.js | 0 .../lib => lib/browser/api}/auto-updater/squirrel-update-win.js | 0 {atom/browser/api/lib => lib/browser/api}/browser-window.js | 0 {atom/browser/api/lib => lib/browser/api}/content-tracing.js | 0 {atom/browser/api/lib => lib/browser/api}/dialog.js | 0 {atom/browser/api/lib => lib/browser/api}/exports/electron.js | 0 {atom/browser/api/lib => lib/browser/api}/global-shortcut.js | 0 {atom/browser/api/lib => lib/browser/api}/ipc-main.js | 0 {atom/browser/api/lib => lib/browser/api}/ipc.js | 0 {atom/browser/api/lib => lib/browser/api}/menu-item.js | 0 {atom/browser/api/lib => lib/browser/api}/menu.js | 0 .../browser/api/lib => lib/browser/api}/navigation-controller.js | 0 {atom/browser/api/lib => lib/browser/api}/power-monitor.js | 0 {atom/browser/api/lib => lib/browser/api}/power-save-blocker.js | 0 {atom/browser/api/lib => lib/browser/api}/protocol.js | 0 {atom/browser/api/lib => lib/browser/api}/screen.js | 0 {atom/browser/api/lib => lib/browser/api}/session.js | 0 {atom/browser/api/lib => lib/browser/api}/tray.js | 0 {atom/browser/api/lib => lib/browser/api}/web-contents.js | 0 {atom/browser/lib => lib/browser}/chrome-extension.js | 0 {atom/browser/lib => lib/browser}/desktop-capturer.js | 0 {atom/browser/lib => lib/browser}/guest-view-manager.js | 0 {atom/browser/lib => lib/browser}/guest-window-manager.js | 0 {atom/browser/lib => lib/browser}/init.js | 0 {atom/browser/lib => lib/browser}/objects-registry.js | 0 {atom/browser/lib => lib/browser}/rpc-server.js | 0 {atom/common/api/lib => lib/common/api}/callbacks-registry.js | 0 {atom/common/api/lib => lib/common/api}/clipboard.js | 0 {atom/common/api/lib => lib/common/api}/crash-reporter.js | 0 {atom/common/api/lib => lib/common/api}/deprecate.js | 0 {atom/common/api/lib => lib/common/api}/deprecations.js | 0 {atom/common/api/lib => lib/common/api}/exports/electron.js | 0 {atom/common/api/lib => lib/common/api}/native-image.js | 0 {atom/common/api/lib => lib/common/api}/shell.js | 0 {atom/common/lib => lib/common}/asar.js | 0 {atom/common/lib => lib/common}/asar_init.js | 0 {atom/common/lib => lib/common}/init.js | 0 {atom/common/lib => lib/common}/reset-search-paths.js | 0 {atom/renderer/api/lib => lib/renderer/api}/desktop-capturer.js | 0 {atom/renderer/api/lib => lib/renderer/api}/exports/electron.js | 0 {atom/renderer/api/lib => lib/renderer/api}/ipc-renderer.js | 0 {atom/renderer/api/lib => lib/renderer/api}/ipc.js | 0 {atom/renderer/api/lib => lib/renderer/api}/remote.js | 0 {atom/renderer/api/lib => lib/renderer/api}/screen.js | 0 {atom/renderer/api/lib => lib/renderer/api}/web-frame.js | 0 {atom/renderer/lib => lib/renderer}/chrome-api.js | 0 {atom/renderer/lib => lib/renderer}/init.js | 0 {atom/renderer/lib => lib/renderer}/inspector.js | 0 {atom/renderer/lib => lib/renderer}/override.js | 0 .../renderer/lib => lib/renderer}/web-view/guest-view-internal.js | 0 .../renderer/lib => lib/renderer}/web-view/web-view-attributes.js | 0 .../renderer/lib => lib/renderer}/web-view/web-view-constants.js | 0 {atom/renderer/lib => lib/renderer}/web-view/web-view.js | 0 56 files changed, 0 insertions(+), 0 deletions(-) rename {atom/browser/api/lib => lib/browser/api}/app.js (100%) rename {atom/browser/api/lib => lib/browser/api}/auto-updater.js (100%) rename {atom/browser/api/lib => lib/browser/api}/auto-updater/auto-updater-native.js (100%) rename {atom/browser/api/lib => lib/browser/api}/auto-updater/auto-updater-win.js (100%) rename {atom/browser/api/lib => lib/browser/api}/auto-updater/squirrel-update-win.js (100%) rename {atom/browser/api/lib => lib/browser/api}/browser-window.js (100%) rename {atom/browser/api/lib => lib/browser/api}/content-tracing.js (100%) rename {atom/browser/api/lib => lib/browser/api}/dialog.js (100%) rename {atom/browser/api/lib => lib/browser/api}/exports/electron.js (100%) rename {atom/browser/api/lib => lib/browser/api}/global-shortcut.js (100%) rename {atom/browser/api/lib => lib/browser/api}/ipc-main.js (100%) rename {atom/browser/api/lib => lib/browser/api}/ipc.js (100%) rename {atom/browser/api/lib => lib/browser/api}/menu-item.js (100%) rename {atom/browser/api/lib => lib/browser/api}/menu.js (100%) rename {atom/browser/api/lib => lib/browser/api}/navigation-controller.js (100%) rename {atom/browser/api/lib => lib/browser/api}/power-monitor.js (100%) rename {atom/browser/api/lib => lib/browser/api}/power-save-blocker.js (100%) rename {atom/browser/api/lib => lib/browser/api}/protocol.js (100%) rename {atom/browser/api/lib => lib/browser/api}/screen.js (100%) rename {atom/browser/api/lib => lib/browser/api}/session.js (100%) rename {atom/browser/api/lib => lib/browser/api}/tray.js (100%) rename {atom/browser/api/lib => lib/browser/api}/web-contents.js (100%) rename {atom/browser/lib => lib/browser}/chrome-extension.js (100%) rename {atom/browser/lib => lib/browser}/desktop-capturer.js (100%) rename {atom/browser/lib => lib/browser}/guest-view-manager.js (100%) rename {atom/browser/lib => lib/browser}/guest-window-manager.js (100%) rename {atom/browser/lib => lib/browser}/init.js (100%) rename {atom/browser/lib => lib/browser}/objects-registry.js (100%) rename {atom/browser/lib => lib/browser}/rpc-server.js (100%) rename {atom/common/api/lib => lib/common/api}/callbacks-registry.js (100%) rename {atom/common/api/lib => lib/common/api}/clipboard.js (100%) rename {atom/common/api/lib => lib/common/api}/crash-reporter.js (100%) rename {atom/common/api/lib => lib/common/api}/deprecate.js (100%) rename {atom/common/api/lib => lib/common/api}/deprecations.js (100%) rename {atom/common/api/lib => lib/common/api}/exports/electron.js (100%) rename {atom/common/api/lib => lib/common/api}/native-image.js (100%) rename {atom/common/api/lib => lib/common/api}/shell.js (100%) rename {atom/common/lib => lib/common}/asar.js (100%) rename {atom/common/lib => lib/common}/asar_init.js (100%) rename {atom/common/lib => lib/common}/init.js (100%) rename {atom/common/lib => lib/common}/reset-search-paths.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/desktop-capturer.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/exports/electron.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/ipc-renderer.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/ipc.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/remote.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/screen.js (100%) rename {atom/renderer/api/lib => lib/renderer/api}/web-frame.js (100%) rename {atom/renderer/lib => lib/renderer}/chrome-api.js (100%) rename {atom/renderer/lib => lib/renderer}/init.js (100%) rename {atom/renderer/lib => lib/renderer}/inspector.js (100%) rename {atom/renderer/lib => lib/renderer}/override.js (100%) rename {atom/renderer/lib => lib/renderer}/web-view/guest-view-internal.js (100%) rename {atom/renderer/lib => lib/renderer}/web-view/web-view-attributes.js (100%) rename {atom/renderer/lib => lib/renderer}/web-view/web-view-constants.js (100%) rename {atom/renderer/lib => lib/renderer}/web-view/web-view.js (100%) diff --git a/atom/browser/api/lib/app.js b/lib/browser/api/app.js similarity index 100% rename from atom/browser/api/lib/app.js rename to lib/browser/api/app.js diff --git a/atom/browser/api/lib/auto-updater.js b/lib/browser/api/auto-updater.js similarity index 100% rename from atom/browser/api/lib/auto-updater.js rename to lib/browser/api/auto-updater.js diff --git a/atom/browser/api/lib/auto-updater/auto-updater-native.js b/lib/browser/api/auto-updater/auto-updater-native.js similarity index 100% rename from atom/browser/api/lib/auto-updater/auto-updater-native.js rename to lib/browser/api/auto-updater/auto-updater-native.js diff --git a/atom/browser/api/lib/auto-updater/auto-updater-win.js b/lib/browser/api/auto-updater/auto-updater-win.js similarity index 100% rename from atom/browser/api/lib/auto-updater/auto-updater-win.js rename to lib/browser/api/auto-updater/auto-updater-win.js diff --git a/atom/browser/api/lib/auto-updater/squirrel-update-win.js b/lib/browser/api/auto-updater/squirrel-update-win.js similarity index 100% rename from atom/browser/api/lib/auto-updater/squirrel-update-win.js rename to lib/browser/api/auto-updater/squirrel-update-win.js diff --git a/atom/browser/api/lib/browser-window.js b/lib/browser/api/browser-window.js similarity index 100% rename from atom/browser/api/lib/browser-window.js rename to lib/browser/api/browser-window.js diff --git a/atom/browser/api/lib/content-tracing.js b/lib/browser/api/content-tracing.js similarity index 100% rename from atom/browser/api/lib/content-tracing.js rename to lib/browser/api/content-tracing.js diff --git a/atom/browser/api/lib/dialog.js b/lib/browser/api/dialog.js similarity index 100% rename from atom/browser/api/lib/dialog.js rename to lib/browser/api/dialog.js diff --git a/atom/browser/api/lib/exports/electron.js b/lib/browser/api/exports/electron.js similarity index 100% rename from atom/browser/api/lib/exports/electron.js rename to lib/browser/api/exports/electron.js diff --git a/atom/browser/api/lib/global-shortcut.js b/lib/browser/api/global-shortcut.js similarity index 100% rename from atom/browser/api/lib/global-shortcut.js rename to lib/browser/api/global-shortcut.js diff --git a/atom/browser/api/lib/ipc-main.js b/lib/browser/api/ipc-main.js similarity index 100% rename from atom/browser/api/lib/ipc-main.js rename to lib/browser/api/ipc-main.js diff --git a/atom/browser/api/lib/ipc.js b/lib/browser/api/ipc.js similarity index 100% rename from atom/browser/api/lib/ipc.js rename to lib/browser/api/ipc.js diff --git a/atom/browser/api/lib/menu-item.js b/lib/browser/api/menu-item.js similarity index 100% rename from atom/browser/api/lib/menu-item.js rename to lib/browser/api/menu-item.js diff --git a/atom/browser/api/lib/menu.js b/lib/browser/api/menu.js similarity index 100% rename from atom/browser/api/lib/menu.js rename to lib/browser/api/menu.js diff --git a/atom/browser/api/lib/navigation-controller.js b/lib/browser/api/navigation-controller.js similarity index 100% rename from atom/browser/api/lib/navigation-controller.js rename to lib/browser/api/navigation-controller.js diff --git a/atom/browser/api/lib/power-monitor.js b/lib/browser/api/power-monitor.js similarity index 100% rename from atom/browser/api/lib/power-monitor.js rename to lib/browser/api/power-monitor.js diff --git a/atom/browser/api/lib/power-save-blocker.js b/lib/browser/api/power-save-blocker.js similarity index 100% rename from atom/browser/api/lib/power-save-blocker.js rename to lib/browser/api/power-save-blocker.js diff --git a/atom/browser/api/lib/protocol.js b/lib/browser/api/protocol.js similarity index 100% rename from atom/browser/api/lib/protocol.js rename to lib/browser/api/protocol.js diff --git a/atom/browser/api/lib/screen.js b/lib/browser/api/screen.js similarity index 100% rename from atom/browser/api/lib/screen.js rename to lib/browser/api/screen.js diff --git a/atom/browser/api/lib/session.js b/lib/browser/api/session.js similarity index 100% rename from atom/browser/api/lib/session.js rename to lib/browser/api/session.js diff --git a/atom/browser/api/lib/tray.js b/lib/browser/api/tray.js similarity index 100% rename from atom/browser/api/lib/tray.js rename to lib/browser/api/tray.js diff --git a/atom/browser/api/lib/web-contents.js b/lib/browser/api/web-contents.js similarity index 100% rename from atom/browser/api/lib/web-contents.js rename to lib/browser/api/web-contents.js diff --git a/atom/browser/lib/chrome-extension.js b/lib/browser/chrome-extension.js similarity index 100% rename from atom/browser/lib/chrome-extension.js rename to lib/browser/chrome-extension.js diff --git a/atom/browser/lib/desktop-capturer.js b/lib/browser/desktop-capturer.js similarity index 100% rename from atom/browser/lib/desktop-capturer.js rename to lib/browser/desktop-capturer.js diff --git a/atom/browser/lib/guest-view-manager.js b/lib/browser/guest-view-manager.js similarity index 100% rename from atom/browser/lib/guest-view-manager.js rename to lib/browser/guest-view-manager.js diff --git a/atom/browser/lib/guest-window-manager.js b/lib/browser/guest-window-manager.js similarity index 100% rename from atom/browser/lib/guest-window-manager.js rename to lib/browser/guest-window-manager.js diff --git a/atom/browser/lib/init.js b/lib/browser/init.js similarity index 100% rename from atom/browser/lib/init.js rename to lib/browser/init.js diff --git a/atom/browser/lib/objects-registry.js b/lib/browser/objects-registry.js similarity index 100% rename from atom/browser/lib/objects-registry.js rename to lib/browser/objects-registry.js diff --git a/atom/browser/lib/rpc-server.js b/lib/browser/rpc-server.js similarity index 100% rename from atom/browser/lib/rpc-server.js rename to lib/browser/rpc-server.js diff --git a/atom/common/api/lib/callbacks-registry.js b/lib/common/api/callbacks-registry.js similarity index 100% rename from atom/common/api/lib/callbacks-registry.js rename to lib/common/api/callbacks-registry.js diff --git a/atom/common/api/lib/clipboard.js b/lib/common/api/clipboard.js similarity index 100% rename from atom/common/api/lib/clipboard.js rename to lib/common/api/clipboard.js diff --git a/atom/common/api/lib/crash-reporter.js b/lib/common/api/crash-reporter.js similarity index 100% rename from atom/common/api/lib/crash-reporter.js rename to lib/common/api/crash-reporter.js diff --git a/atom/common/api/lib/deprecate.js b/lib/common/api/deprecate.js similarity index 100% rename from atom/common/api/lib/deprecate.js rename to lib/common/api/deprecate.js diff --git a/atom/common/api/lib/deprecations.js b/lib/common/api/deprecations.js similarity index 100% rename from atom/common/api/lib/deprecations.js rename to lib/common/api/deprecations.js diff --git a/atom/common/api/lib/exports/electron.js b/lib/common/api/exports/electron.js similarity index 100% rename from atom/common/api/lib/exports/electron.js rename to lib/common/api/exports/electron.js diff --git a/atom/common/api/lib/native-image.js b/lib/common/api/native-image.js similarity index 100% rename from atom/common/api/lib/native-image.js rename to lib/common/api/native-image.js diff --git a/atom/common/api/lib/shell.js b/lib/common/api/shell.js similarity index 100% rename from atom/common/api/lib/shell.js rename to lib/common/api/shell.js diff --git a/atom/common/lib/asar.js b/lib/common/asar.js similarity index 100% rename from atom/common/lib/asar.js rename to lib/common/asar.js diff --git a/atom/common/lib/asar_init.js b/lib/common/asar_init.js similarity index 100% rename from atom/common/lib/asar_init.js rename to lib/common/asar_init.js diff --git a/atom/common/lib/init.js b/lib/common/init.js similarity index 100% rename from atom/common/lib/init.js rename to lib/common/init.js diff --git a/atom/common/lib/reset-search-paths.js b/lib/common/reset-search-paths.js similarity index 100% rename from atom/common/lib/reset-search-paths.js rename to lib/common/reset-search-paths.js diff --git a/atom/renderer/api/lib/desktop-capturer.js b/lib/renderer/api/desktop-capturer.js similarity index 100% rename from atom/renderer/api/lib/desktop-capturer.js rename to lib/renderer/api/desktop-capturer.js diff --git a/atom/renderer/api/lib/exports/electron.js b/lib/renderer/api/exports/electron.js similarity index 100% rename from atom/renderer/api/lib/exports/electron.js rename to lib/renderer/api/exports/electron.js diff --git a/atom/renderer/api/lib/ipc-renderer.js b/lib/renderer/api/ipc-renderer.js similarity index 100% rename from atom/renderer/api/lib/ipc-renderer.js rename to lib/renderer/api/ipc-renderer.js diff --git a/atom/renderer/api/lib/ipc.js b/lib/renderer/api/ipc.js similarity index 100% rename from atom/renderer/api/lib/ipc.js rename to lib/renderer/api/ipc.js diff --git a/atom/renderer/api/lib/remote.js b/lib/renderer/api/remote.js similarity index 100% rename from atom/renderer/api/lib/remote.js rename to lib/renderer/api/remote.js diff --git a/atom/renderer/api/lib/screen.js b/lib/renderer/api/screen.js similarity index 100% rename from atom/renderer/api/lib/screen.js rename to lib/renderer/api/screen.js diff --git a/atom/renderer/api/lib/web-frame.js b/lib/renderer/api/web-frame.js similarity index 100% rename from atom/renderer/api/lib/web-frame.js rename to lib/renderer/api/web-frame.js diff --git a/atom/renderer/lib/chrome-api.js b/lib/renderer/chrome-api.js similarity index 100% rename from atom/renderer/lib/chrome-api.js rename to lib/renderer/chrome-api.js diff --git a/atom/renderer/lib/init.js b/lib/renderer/init.js similarity index 100% rename from atom/renderer/lib/init.js rename to lib/renderer/init.js diff --git a/atom/renderer/lib/inspector.js b/lib/renderer/inspector.js similarity index 100% rename from atom/renderer/lib/inspector.js rename to lib/renderer/inspector.js diff --git a/atom/renderer/lib/override.js b/lib/renderer/override.js similarity index 100% rename from atom/renderer/lib/override.js rename to lib/renderer/override.js diff --git a/atom/renderer/lib/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js similarity index 100% rename from atom/renderer/lib/web-view/guest-view-internal.js rename to lib/renderer/web-view/guest-view-internal.js diff --git a/atom/renderer/lib/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js similarity index 100% rename from atom/renderer/lib/web-view/web-view-attributes.js rename to lib/renderer/web-view/web-view-attributes.js diff --git a/atom/renderer/lib/web-view/web-view-constants.js b/lib/renderer/web-view/web-view-constants.js similarity index 100% rename from atom/renderer/lib/web-view/web-view-constants.js rename to lib/renderer/web-view/web-view-constants.js diff --git a/atom/renderer/lib/web-view/web-view.js b/lib/renderer/web-view/web-view.js similarity index 100% rename from atom/renderer/lib/web-view/web-view.js rename to lib/renderer/web-view/web-view.js From 6e3cb9e8eb71282b99b5fcc5ade1edb2f9712fe1 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 17:22:38 -0800 Subject: [PATCH 0094/1265] Update paths for new JS location --- filenames.gypi | 112 ++++++++++++++++++++++++------------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/filenames.gypi b/filenames.gypi index abb11453210..f9e19550c89 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -8,64 +8,64 @@ 'atom/browser/resources/mac/atom.icns', ], 'js_sources': [ - 'atom/browser/api/lib/app.js', - 'atom/browser/api/lib/auto-updater.js', - 'atom/browser/api/lib/auto-updater/auto-updater-native.js', - 'atom/browser/api/lib/auto-updater/auto-updater-win.js', - 'atom/browser/api/lib/auto-updater/squirrel-update-win.js', - 'atom/browser/api/lib/browser-window.js', - 'atom/browser/api/lib/content-tracing.js', - 'atom/browser/api/lib/dialog.js', - 'atom/browser/api/lib/exports/electron.js', - 'atom/browser/api/lib/global-shortcut.js', - 'atom/browser/api/lib/ipc.js', - 'atom/browser/api/lib/ipc-main.js', - 'atom/browser/api/lib/menu.js', - 'atom/browser/api/lib/menu-item.js', - 'atom/browser/api/lib/navigation-controller.js', - 'atom/browser/api/lib/power-monitor.js', - 'atom/browser/api/lib/power-save-blocker.js', - 'atom/browser/api/lib/protocol.js', - 'atom/browser/api/lib/session.js', - 'atom/browser/api/lib/screen.js', - 'atom/browser/api/lib/tray.js', - 'atom/browser/api/lib/web-contents.js', - 'atom/browser/lib/chrome-extension.js', - 'atom/browser/lib/desktop-capturer.js', - 'atom/browser/lib/guest-view-manager.js', - 'atom/browser/lib/guest-window-manager.js', - 'atom/browser/lib/init.js', - 'atom/browser/lib/objects-registry.js', - 'atom/browser/lib/rpc-server.js', - 'atom/common/api/lib/callbacks-registry.js', - 'atom/common/api/lib/clipboard.js', - 'atom/common/api/lib/crash-reporter.js', - 'atom/common/api/lib/deprecate.js', - 'atom/common/api/lib/deprecations.js', - 'atom/common/api/lib/exports/electron.js', - 'atom/common/api/lib/native-image.js', - 'atom/common/api/lib/shell.js', - 'atom/common/lib/init.js', - 'atom/common/lib/reset-search-paths.js', - 'atom/renderer/lib/chrome-api.js', - 'atom/renderer/lib/init.js', - 'atom/renderer/lib/inspector.js', - 'atom/renderer/lib/override.js', - 'atom/renderer/lib/web-view/guest-view-internal.js', - 'atom/renderer/lib/web-view/web-view.js', - 'atom/renderer/lib/web-view/web-view-attributes.js', - 'atom/renderer/lib/web-view/web-view-constants.js', - 'atom/renderer/api/lib/desktop-capturer.js', - 'atom/renderer/api/lib/exports/electron.js', - 'atom/renderer/api/lib/ipc.js', - 'atom/renderer/api/lib/ipc-renderer.js', - 'atom/renderer/api/lib/remote.js', - 'atom/renderer/api/lib/screen.js', - 'atom/renderer/api/lib/web-frame.js', + 'lib/browser/api/app.js', + 'lib/browser/api/auto-updater.js', + 'lib/browser/api/auto-updater/auto-updater-native.js', + 'lib/browser/api/auto-updater/auto-updater-win.js', + 'lib/browser/api/auto-updater/squirrel-update-win.js', + 'lib/browser/api/browser-window.js', + 'lib/browser/api/content-tracing.js', + 'lib/browser/api/dialog.js', + 'lib/browser/api/exports/electron.js', + 'lib/browser/api/global-shortcut.js', + 'lib/browser/api/ipc.js', + 'lib/browser/api/ipc-main.js', + 'lib/browser/api/menu.js', + 'lib/browser/api/menu-item.js', + 'lib/browser/api/navigation-controller.js', + 'lib/browser/api/power-monitor.js', + 'lib/browser/api/power-save-blocker.js', + 'lib/browser/api/protocol.js', + 'lib/browser/api/session.js', + 'lib/browser/api/screen.js', + 'lib/browser/api/tray.js', + 'lib/browser/api/web-contents.js', + 'lib/browser/chrome-extension.js', + 'lib/browser/desktop-capturer.js', + 'lib/browser/guest-view-manager.js', + 'lib/browser/guest-window-manager.js', + 'lib/browser/init.js', + 'lib/browser/objects-registry.js', + 'lib/browser/rpc-server.js', + 'lib/common/api/callbacks-registry.js', + 'lib/common/api/clipboard.js', + 'lib/common/api/crash-reporter.js', + 'lib/common/api/deprecate.js', + 'lib/common/api/deprecations.js', + 'lib/common/api/exports/electron.js', + 'lib/common/api/native-image.js', + 'lib/common/api/shell.js', + 'lib/common/init.js', + 'lib/common/reset-search-paths.js', + 'lib/renderer/chrome-api.js', + 'lib/renderer/init.js', + 'lib/renderer/inspector.js', + 'lib/renderer/override.js', + 'lib/renderer/web-view/guest-view-internal.js', + 'lib/renderer/web-view/web-view.js', + 'lib/renderer/web-view/web-view-attributes.js', + 'lib/renderer/web-view/web-view-constants.js', + 'lib/renderer/api/desktop-capturer.js', + 'lib/renderer/api/exports/electron.js', + 'lib/renderer/api/ipc.js', + 'lib/renderer/api/ipc-renderer.js', + 'lib/renderer/api/remote.js', + 'lib/renderer/api/screen.js', + 'lib/renderer/api/web-frame.js', ], 'js2c_sources': [ - 'atom/common/lib/asar.js', - 'atom/common/lib/asar_init.js', + 'lib/common/asar.js', + 'lib/common/asar_init.js', ], 'lib_sources': [ 'atom/app/atom_content_client.cc', From c47ad29124de46b6838e633b15510b10b29c700a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 7 Mar 2016 17:25:01 -0800 Subject: [PATCH 0095/1265] Move default_app to root of repo --- atom.gyp | 6 +++--- {atom/browser/default_app => default_app}/default_app.js | 0 {atom/browser/default_app => default_app}/index.html | 0 {atom/browser/default_app => default_app}/main.js | 0 {atom/browser/default_app => default_app}/package.json | 0 5 files changed, 3 insertions(+), 3 deletions(-) rename {atom/browser/default_app => default_app}/default_app.js (100%) rename {atom/browser/default_app => default_app}/index.html (100%) rename {atom/browser/default_app => default_app}/main.js (100%) rename {atom/browser/default_app => default_app}/package.json (100%) diff --git a/atom.gyp b/atom.gyp index 7f78bee91b1..b7075301894 100644 --- a/atom.gyp +++ b/atom.gyp @@ -69,7 +69,7 @@ { 'destination': '<(PRODUCT_DIR)/<(product_name).app/Contents/Resources', 'files': [ - 'atom/browser/default_app', + 'default_app', ], }, ], @@ -171,7 +171,7 @@ { 'destination': '<(PRODUCT_DIR)/resources', 'files': [ - 'atom/browser/default_app', + 'default_app', ] }, ], @@ -212,7 +212,7 @@ { 'destination': '<(PRODUCT_DIR)/resources', 'files': [ - 'atom/browser/default_app', + 'default_app', ] }, ], diff --git a/atom/browser/default_app/default_app.js b/default_app/default_app.js similarity index 100% rename from atom/browser/default_app/default_app.js rename to default_app/default_app.js diff --git a/atom/browser/default_app/index.html b/default_app/index.html similarity index 100% rename from atom/browser/default_app/index.html rename to default_app/index.html diff --git a/atom/browser/default_app/main.js b/default_app/main.js similarity index 100% rename from atom/browser/default_app/main.js rename to default_app/main.js diff --git a/atom/browser/default_app/package.json b/default_app/package.json similarity index 100% rename from atom/browser/default_app/package.json rename to default_app/package.json From f109591d030801f96d33beb7c5e6bd3e1edb20a3 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:03:25 -0800 Subject: [PATCH 0096/1265] Look for JS in lib dir --- tools/js2asar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/js2asar.py b/tools/js2asar.py index a17212419e1..cb02e33de65 100755 --- a/tools/js2asar.py +++ b/tools/js2asar.py @@ -29,7 +29,7 @@ def copy_js(js_source_files, output_dir): def call_asar(archive, output_dir): - js_dir = os.path.join(output_dir, 'atom') + js_dir = os.path.join(output_dir, 'lib') asar = os.path.join(SOURCE_ROOT, 'node_modules', 'asar', 'bin', 'asar') subprocess.check_call([find_node(), asar, 'pack', js_dir, archive]) From 006c77a00fb26572592af51e5201fc7a602e1e3c Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:07:42 -0800 Subject: [PATCH 0097/1265] Update requires paths --- atom/common/node_bindings.cc | 1 - lib/browser/api/exports/electron.js | 2 +- lib/browser/init.js | 8 ++++---- lib/renderer/api/exports/electron.js | 2 +- lib/renderer/api/remote.js | 2 +- lib/renderer/init.js | 8 ++++---- 6 files changed, 11 insertions(+), 12 deletions(-) diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index 69e7906ffbb..608cc94b09a 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -165,7 +165,6 @@ node::Environment* NodeBindings::CreateEnvironment( base::FilePath script_path = resources_path.Append(FILE_PATH_LITERAL("atom.asar")) .Append(process_type) - .Append(FILE_PATH_LITERAL("lib")) .Append(FILE_PATH_LITERAL("init.js")); std::string script_path_str = script_path.AsUTF8Unsafe(); args.insert(args.begin() + 1, script_path_str.c_str()); diff --git a/lib/browser/api/exports/electron.js b/lib/browser/api/exports/electron.js index 7f97fcdbc4c..ea9dd6eb5a2 100644 --- a/lib/browser/api/exports/electron.js +++ b/lib/browser/api/exports/electron.js @@ -1,4 +1,4 @@ -const common = require('../../../../common/api/lib/exports/electron'); +const common = require('../../../common/api/exports/electron'); // Import common modules. diff --git a/lib/browser/init.js b/lib/browser/init.js index 4769faee0a3..d6a18361d69 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -11,19 +11,19 @@ var slice = [].slice; process.argv.splice(1, 1); // Clear search paths. -require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths')); +require(path.resolve(__dirname, '..', 'common', 'reset-search-paths')); // Import common settings. -require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init')); +require(path.resolve(__dirname, '..', 'common', 'init')); var globalPaths = Module.globalPaths; if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { - globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); + globalPaths.push(path.resolve(__dirname, 'api')); } // Expose public APIs. -globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports')); +globalPaths.push(path.resolve(__dirname, 'api', 'exports')); if (process.platform === 'win32') { // Redirect node's console to use our own implementations, since node can not diff --git a/lib/renderer/api/exports/electron.js b/lib/renderer/api/exports/electron.js index 3f0d3254cb8..34a498fcc06 100644 --- a/lib/renderer/api/exports/electron.js +++ b/lib/renderer/api/exports/electron.js @@ -1,4 +1,4 @@ -const common = require('../../../../common/api/lib/exports/electron'); +const common = require('../../../common/api/exports/electron'); // Import common modules. common.defineProperties(exports); diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 07aa2478293..42435d8304c 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -244,7 +244,7 @@ ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function(event, id) { }); // List all built-in modules in browser process. -const browserModules = require('../../../browser/api/lib/exports/electron'); +const browserModules = require('../../browser/api/exports/electron'); // And add a helper receiver for each one. var fn = function(name) { diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 166e64237de..334aebda9cf 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -9,19 +9,19 @@ const Module = require('module'); process.argv.splice(1, 1); // Clear search paths. -require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'reset-search-paths')); +require(path.resolve(__dirname, '..', 'common', 'reset-search-paths')); // Import common settings. -require(path.resolve(__dirname, '..', '..', 'common', 'lib', 'init')); +require(path.resolve(__dirname, '..','common', 'init')); var globalPaths = Module.globalPaths; if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { - globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); + globalPaths.push(path.resolve(__dirname, 'api')); } // Expose public APIs. -globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib', 'exports')); +globalPaths.push(path.resolve(__dirname, 'api', 'exports')); // The global variable will be used by ipc for event dispatching var v8Util = process.atomBinding('v8_util'); From 418efbe6608ca3710a6edf684fb1d11eac74defa Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:10:31 -0800 Subject: [PATCH 0098/1265] Remove unneeded resolve calls --- lib/browser/init.js | 8 ++++---- lib/renderer/init.js | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/browser/init.js b/lib/browser/init.js index d6a18361d69..e1105df9b13 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -11,19 +11,19 @@ var slice = [].slice; process.argv.splice(1, 1); // Clear search paths. -require(path.resolve(__dirname, '..', 'common', 'reset-search-paths')); +require('../common/reset-search-paths'); // Import common settings. -require(path.resolve(__dirname, '..', 'common', 'init')); +require('../common/init'); var globalPaths = Module.globalPaths; if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { - globalPaths.push(path.resolve(__dirname, 'api')); + globalPaths.push(path.join(__dirname, 'api')); } // Expose public APIs. -globalPaths.push(path.resolve(__dirname, 'api', 'exports')); +globalPaths.push(path.join(__dirname, 'api', 'exports')); if (process.platform === 'win32') { // Redirect node's console to use our own implementations, since node can not diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 334aebda9cf..45ea2d45654 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -9,19 +9,19 @@ const Module = require('module'); process.argv.splice(1, 1); // Clear search paths. -require(path.resolve(__dirname, '..', 'common', 'reset-search-paths')); +require('../common/reset-search-paths'); // Import common settings. -require(path.resolve(__dirname, '..','common', 'init')); +require('../common/init'); var globalPaths = Module.globalPaths; if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { - globalPaths.push(path.resolve(__dirname, 'api')); + globalPaths.push(path.join(__dirname, 'api')); } // Expose public APIs. -globalPaths.push(path.resolve(__dirname, 'api', 'exports')); +globalPaths.push(path.join(__dirname, 'api', 'exports')); // The global variable will be used by ipc for event dispatching var v8Util = process.atomBinding('v8_util'); From 4c9f5b71f7ecaea2436bc647f4491d3974b89e44 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:11:35 -0800 Subject: [PATCH 0099/1265] Run eslint over lib folder --- script/eslint.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/eslint.py b/script/eslint.py index 7b912e0e1d6..4fbc5788570 100755 --- a/script/eslint.py +++ b/script/eslint.py @@ -24,7 +24,7 @@ def main(): settings = ['--quiet', '--config'] sourceConfig = os.path.join('script', 'eslintrc-base.json') - sourceFiles = ['atom'] + sourceFiles = ['lib'] execute([eslint] + settings + [sourceConfig] + sourceFiles) specConfig = os.path.join('script', 'eslintrc-spec.json') From 2e9fd7ce77faf451526464eaeb06521d31b9150d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:22:13 -0800 Subject: [PATCH 0100/1265] Update common api path --- lib/common/init.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/init.js b/lib/common/init.js index a4766c4a7f9..923ef910886 100644 --- a/lib/common/init.js +++ b/lib/common/init.js @@ -14,7 +14,7 @@ process.atomBinding = function(name) { if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { // Add common/api/lib to module search paths. - Module.globalPaths.push(path.resolve(__dirname, '..', 'api', 'lib')); + Module.globalPaths.push(path.join(__dirname, 'api')); } From c3b058cea37eae064532ebac036eb67ed5db41e1 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 8 Mar 2016 11:22:58 -0800 Subject: [PATCH 0101/1265] Update path to ipc.js --- spec/asar-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/asar-spec.js b/spec/asar-spec.js index f6f4bb71dbc..0e0a7f89f17 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -17,7 +17,7 @@ describe('asar package', function() { it('does not leak fd', function() { var readCalls = 1; while(readCalls <= 10000) { - fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'lib', 'ipc.js')); + fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'ipc.js')); readCalls++; } }); From 937668097aabfe200b3c3324c84cfb49a96b14a2 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 9 Mar 2016 17:00:01 +0800 Subject: [PATCH 0102/1265] web-view-tag first finish --- docs-translations/zh-CN/api/web-view-tag.md | 690 ++++++++++++++++++++ 1 file changed, 690 insertions(+) create mode 100644 docs-translations/zh-CN/api/web-view-tag.md diff --git a/docs-translations/zh-CN/api/web-view-tag.md b/docs-translations/zh-CN/api/web-view-tag.md new file mode 100644 index 00000000000..819d57cb459 --- /dev/null +++ b/docs-translations/zh-CN/api/web-view-tag.md @@ -0,0 +1,690 @@ +# `` 标签 + +使用 `webview` 标签来把 'guest' 内容(例如 web pages )嵌入到你的 Electron app 中. guest内容包含在 `webview` 容器中.一个嵌入你的应用的page控制着guest内容如何布局摆放和表达含义. + +与 `iframe` 不同, `webview` 和你的应用运行的是不同的进程. 它不拥有渲染进程的权限,并且应用和嵌入内容之间的交互全部都是异步的.因为这能保证应用的安全性不受嵌入内容的影响. + +## 例子 + +把一个 web page 嵌入到你的app,首先添加 `webview` 标签到你的app待嵌入page(展示 guest content). 在一个最简单的 `webview` 中,它包含了 web page 的文件路径和一个控制 `webview` 容器展示效果的css样式: + +```html + +``` + +如果想随时控制 guest 内容,可以添加 JavaScript 脚本来监听 `webview` 事件使用 `webview` 方法来做出响应. 这里是2个事件监听的例子:一个监听 web page 准备加载,另一个监听 web page 停止加载,并且在加载的时候显示一条 "loading..." 信息: + +```html + +``` + +## 标签属性 + +`webview` 标签有下面一些属性 : + +### `src` + +```html + +``` + +将一个可用的url做为这个属性的初始值添加到顶部导航. + +如果把当前页的src添加进去将加载当前page. + + `src`同样可以填 data urls,例如 +`data:text/plain,Hello, world!`. + +### `autosize` + +```html + +``` + +如果这个属性的值为 "on" , `webview` 容器将会根据属性`minwidth`, `minheight`, `maxwidth`, 和 +`maxheight` 的值在它们之间自适应. 只有在 `autosize` 开启的时候这个约束才会有效. 当 `autosize` 开启的时候, `webview` 容器的 size 只能在上面那四个属性值之间. + +### `nodeintegration` + +```html + +``` + +如果这个属性的值为 "on" , `webview` 中的 guest page 将整合node,并且拥有可以使用系统底层的资源,例如 `require` 和 `process` . + +### `plugins` + +```html + +``` + +如果这个属性的值为 "on" , `webview` 中的 guest page 就可以使用浏览器插件。 + +### `preload` + +```html + +``` + +在 guest page 中的其他脚本执行之前预加载一个指定的脚本。规定预加载脚本的url须如 `file:` 或者 `asar:`,因为它在是 guest page 中通过通过 `require` 命令加载的。 + +如果 guest page 没有整合 node ,这个脚本将试图使用真个 Node APIs ,但是在这个脚本执行完毕时,之前由node插入的全局对象会被删除。 + + +### `httpreferrer` + +```html + +``` + +为 guest page 设置 referrer URL。 + +### `useragent` + +```html + +``` + +在 guest page 加载之前为其设置用户代理。如果页面已经加载了,可以使用 `setUserAgent` 方法来改变用户代理。 + +### `disablewebsecurity` + +```html + +``` + +如果这个属性的值为 "on" , guest page会禁用web安全控制. + +### partition + +```html + + +``` + +为page设置session。如果初始值为 `partition` ,这个 page 将会为app中的所有 page 应用同一个持续有效的 session。如果没有 `persist:` 前缀, 这个 page 将会使用一个历史 session 。通过分配使用相同的 `partition`, 所有的page都可以分享相同的session。如果 `partition` 没有设置,那app将使用默认的session. + +这个值只能在在第一个渲染进程之前设置修改,之后修改的话会无效并且抛出一个DOM异常. + +### `allowpopups` + +```html + +``` + +如果这个属性的值为 "on" ,将允许 guest page 打开一个新窗口。 + +### `blinkfeatures` + +```html + +``` + +这个属性的值为一个用逗号分隔的列表,它的值指定特性被启用。你可以从[setFeatureEnabledFromString][blink-feature-string]函数找到完整的支持特性。 + +## 方法 + + `webview` 的方法集合: + +**注意:** webview 元素必须在使用这些方法之前加载完毕。 + +**例如** + +```javascript +webview.addEventListener("dom-ready", function() { + webview.openDevTools(); +}); +``` + +### `.loadURL(url[, options])` + +* `url` URL +* `options` Object (可选) + * `httpReferrer` String - 一个http类型的url. + * `userAgent` String -用于发起请求的用户代理. + * `extraHeaders` String - 额外的headers,用 "\n"分隔. + +加载 webview 中的 `url`,`url` 必须包含协议前缀,例如 `http://` 或 `file://`. + +### `.getURL()` + +从 guest page 中返回 url. + +### `.getTitle()` + +从 guest page 中返回 title. + +### `.isLoading()` + +返回一个 guest page 是否仍在加载资源的布尔值. + +### `.isWaitingForResponse()` + +返回一个 guest page 是否正在等待page的主要资源做出回应的布尔值. + + +### `.stop()` + +停止渲染. + +### `.reload()` + +重新加载 guest page. + +### `.reloadIgnoringCache()` + +忽视缓存,重新加载 guest page. + +### `.canGoBack()` + +返回一个 guest page 是否能够回退的布尔值. + +### `.canGoForward()` + +返回一个 guest page 是否能够前进的布尔值. + +### `.canGoToOffset(offset)` + +* `offset` Integer + +返回一个 guest page 是否能够前进到 `offset` 的布尔值. + +### `.clearHistory()` + +清除导航历史. + +### `.goBack()` + +guest page 回退. + +### `.goForward()` + +guest page 前进. + +### `.goToIndex(index)` + +* `index` Integer + +guest page 导航到指定的绝对位置. + +### `.goToOffset(offset)` + +* `offset` Integer + +guest page 导航到指定的相对位置. + +### `.isCrashed()` + +返回一个 渲染进程是否崩溃 的布尔值. + +### `.setUserAgent(userAgent)` + +* `userAgent` String + +重新设置用户代理. + +### `.getUserAgent()` + +返回用户代理名字,返回类型:`String`. + +### `.insertCSS(css)` + +* `css` String + +插入css. + +### `.executeJavaScript(code, userGesture, callback)` + +* `code` String +* `userGesture` Boolean - 默认 `false`. +* `callback` Function (可选) - 回调函数. + * `result` + +评估 `code` ,如果 `userGesture` 值为 true ,它将在这个page里面创建用户手势. HTML APIs ,如 `requestFullScreen`,它需要用户响应,那么将自动通过这个参数优化. + +### `.openDevTools()` + +为 guest page 打开开发工具调试窗口. + +### `.closeDevTools()` + +为 guest page 关闭开发工具调试窗口. + +### `.isDevToolsOpened()` + +返回一个 guest page 是否打开了开发工具调试窗口的布尔值. + +### `.isDevToolsFocused()` + +返回一个 guest page 是否聚焦了开发工具调试窗口的布尔值. + +### `.inspectElement(x, y)` + +* `x` Integer +* `y` Integer + +开始检查 guest page 在 (`x`, `y`) 位置的元素. + +### `.inspectServiceWorker()` + +在 guest page 中为服务人员打开开发工具. + +### `.setAudioMuted(muted)` + +* `muted` Boolean +设置 guest page 流畅(muted). + +### `.isAudioMuted()` + +返回一个 guest page 是否流畅的布尔值. + +### `.undo()` + +在page中编辑执行 `undo` 命令. + +### `.redo()` + +在page中编辑执行 `redo` 命令. + +### `.cut()` + +在page中编辑执行 `cut` 命令. + +### `.copy()` + +在page中编辑执行 `copy` 命令. + +### `.paste()` + +在page中编辑执行 `paste` 命令. + +### `.pasteAndMatchStyle()` + +在page中编辑执行 `pasteAndMatchStyle` 命令. + +### `.delete()` + +在page中编辑执行 `delete` 命令. + +### `.selectAll()` + +在page中编辑执行 `selectAll` 命令. + +### `.unselect()` + +在page中编辑执行 `unselect` 命令. + +### `.replace(text)` + +* `text` String + +在page中编辑执行 `replace` 命令. + +### `.replaceMisspelling(text)` + +* `text` String + +在page中编辑执行 `replaceMisspelling` 命令. + +### `.insertText(text)` + +* `text` String + +插入文本. + +### `.findInPage(text[, options])` + +* `text` String - 搜索内容,不能为空. +* `options` Object (可选) + * `forward` Boolean - 向前或向后, 默认为 `true`. + * `findNext` Boolean - 是否查找的第一个结果, + 默认为 `false`. + * `matchCase` Boolean - 是否区分大小写, + 默认为 `false`. + * `wordStart` Boolean - 是否只查找首字母. + 默认为 `false`. + * `medialCapitalAsWordStart` Boolean - 当配合 `wordStart`的时候,接受一个文字中的匹配项,要求匹配项是以大写字母开头后面跟小写字母或者没有字母。可以接受一些其他单词内部匹配, 默认为 `false`. + +发起一个请求来寻找页面中的所有匹配 `text` 的地方并且返回一个 `Integer`来表示这个请求用的请求Id. 这个请求结果可以通过订阅[`found-in-page`](web-view-tag.md#event-found-in-page) 事件来取得. + +### `.stopFindInPage(action)` + +* `action` String - 指定一个行为来接替停止 + [`.findInPage`](web-view-tag.md#webviewtagfindinpage) 请求. + * `clearSelection` - 转变为一个普通的 selection. + * `keepSelection` - 清除 selection. + * `activateSelection` - 聚焦并点击 selection node. + +使用 `action` 停止 `findInPage` 请求. + +### `.print([options])` + +打印输出 `webview` 的 web page. 类似 `webContents.print([options])`. + +### `.printToPDF(options, callback)` + +以pdf格式打印输出 `webview` 的 web page. 类似 `webContents.printToPDF(options, callback)`. + +### `.send(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (可选) + +通过 `channel` 向渲染进程发出异步消息,你也可以发送任意的参数。 +渲染进程通过`ipcRenderer` 模块监听 `channel` 事件来控制消息. + +例子 +[webContents.send](web-contents.md#webcontentssendchannel-args). + +### `.sendInputEvent(event)` + +* `event` Object + +向 page 发送输入事件. + +查看 [webContents.sendInputEvent](web-contents.md##webcontentssendinputeventevent) +关于 `event` 对象的相信介绍. + +### `.getWebContents()` + +返回和这个 `webview` 相关的 [WebContents](web-contents.md). + +## DOM 事件 + +`webview` 可用下面的 DOM 事件: + +### Event: 'load-commit' + +返回: + +* `url` String +* `isMainFrame` Boolean + +加载完成触发. 这个包含当前文档的导航和副框架的文档加载,但是不包含异步资源加载. + +### Event: 'did-finish-load' + +在导航加载完成时触发,也就是tab 的 spinner停止spinning,并且加载事件处理. + +### Event: 'did-fail-load' + +Returns: + +* `errorCode` Integer +* `errorDescription` String +* `validatedURL` String + +类似 `did-finish-load` ,在加载失败或取消是触发,例如提出 `window.stop()`. + +### Event: 'did-frame-finish-load' + +返回: + +* `isMainFrame` Boolean + +当一个 frame 完成 加载时触发. + +### Event: 'did-start-loading' + +开始加载时触发. + +### Event: 'did-stop-loading' + +停止家在时触发. + +### Event: 'did-get-response-details' + +返回: + +* `status` Boolean +* `newURL` String +* `originalURL` String +* `httpResponseCode` Integer +* `requestMethod` String +* `referrer` String +* `headers` Object + +当获得返回详情的时候触发. + +`status` 指示 socket 连接来下载资源. + +### Event: 'did-get-redirect-request' + +返回: + +* `oldURL` String +* `newURL` String +* `isMainFrame` Boolean + +当重定向请求资源被接收的时候触发. + +### Event: 'dom-ready' + +当指定的frame文档加载完毕时触发. + +### Event: 'page-title-updated' + +返回: + +* `title` String +* `explicitSet` Boolean + +当导航中的页面title被设置时触发. +在title通过文档路径异步加载时`explicitSet`为false. + +### Event: 'page-favicon-updated' + +返回: + +* `favicons` Array - Array of URLs. + +当page收到了图标url时触发. + +### Event: 'enter-html-full-screen' + +当通过HTML API使界面进入全屏时触发. + +### Event: 'leave-html-full-screen' + +当通过HTML API使界面退出全屏时触发. + +### Event: 'console-message' + +返回: + +* `level` Integer +* `message` String +* `line` Integer +* `sourceId` String + +当客户端输出控制台信息的时候触发. + +下面示例代码将所有信息输出到内置控制台,没有考虑到输出等级和其他属性。 + +```javascript +webview.addEventListener('console-message', function(e) { + console.log('Guest page logged a message:', e.message); +}); +``` + +### Event: 'found-in-page' + +返回: + +* `result` Object + * `requestId` Integer + * `finalUpdate` Boolean - 指明下面是否还有更多的回应. + * `matches` Integer (optional) - 匹配数量. + * `selectionArea` Object (optional) - 整合第一个匹配域. + +在请求[`webview.findInPage`](web-view-tag.md#webviewtagfindinpage)结果有效时触发. + +```javascript +webview.addEventListener('found-in-page', function(e) { + if (e.result.finalUpdate) + webview.stopFindInPage("keepSelection"); +}); + +const rquestId = webview.findInPage("test"); +``` + +### Event: 'new-window' + +返回: + +* `url` String +* `frameName` String +* `disposition` String - 可以为 `default`, `foreground-tab`, `background-tab`, + `new-window` 和 `other`. +* `options` Object - 参数应该被用作创建新的 + `BrowserWindow`. + +在 guest page 试图打开一个新的浏览器窗口时触发. + +下面示例代码在系统默认浏览器中打开了一个新的url. + +```javascript +webview.addEventListener('new-window', function(e) { + require('electron').shell.openExternal(e.url); +}); +``` + +### Event: 'will-navigate' + +返回: + +* `url` String + +当用户或page尝试开始导航时触发. +它能在 `window.location` 变化或者用户点击连接的时候触发. + +这个事件在以 APIS 编程方式开始导航时不会触发,例如 `.loadURL` 和 `.back`. + +在页面内部导航跳转也将不回触发这个事件,例如点击锚链接或更新 `window.location.hash`.使用 `did-navigate-in-page` 来实现页内跳转事件. + +使用 `event.preventDefault()` 并不会起什么用. + +### Event: 'did-navigate' + +返回: + +* `url` String + +当导航结束时触发. + +在页面内部导航跳转也将不回触发这个事件,例如点击锚链接或更新 `window.location.hash`.使用 `did-navigate-in-page` 来实现页内跳转事件. + +### Event: 'did-navigate-in-page' + +返回: + +* `url` String + +当页内导航发生时触发. +当业内导航发生时,page url改变了,但是不会跳出 page . 例如在锚链接被电击或DOM `hashchange` 事件发生时触发. + +### Event: 'close' + +在 guest page试图关闭自己的时候触发. + +下面的示例代码指示了在客户端试图关闭自己的时候将改变导航连接为`about:blank`. + +```javascript +webview.addEventListener('close', function() { + webview.src = 'about:blank'; +}); +``` + +### Event: 'ipc-message' + +返回: + +* `channel` String +* `args` Array + +在 guest page 向嵌入页发送一个异步消息的时候触发. + +你可以很简单的使用 `sendToHost` 方法和 `ipc-message` 事件在 guest page 和 嵌入页(embedder page)之间通信: + +```javascript +// In embedder page. +webview.addEventListener('ipc-message', function(event) { + console.log(event.channel); + // Prints "pong" +}); +webview.send('ping'); +``` + +```javascript +// In guest page. +var ipcRenderer = require('electron').ipcRenderer; +ipcRenderer.on('ping', function() { + ipcRenderer.sendToHost('pong'); +}); +``` + +### Event: 'crashed' + +在渲染进程崩溃的时候触发. + +### Event: 'gpu-crashed' + +在GPU进程崩溃的时候触发. + +### Event: 'plugin-crashed' + +返回: + +* `name` String +* `version` String + +在插件进程崩溃的时候触发. + +### Event: 'destroyed' + +在界面内容销毁的时候触发. + +### Event: 'media-started-playing' + +在媒体准备播放的时候触发. + +### Event: 'media-paused' + +在媒体暂停播放或播放放毕的时候触发. + +### Event: 'did-change-theme-color' + +在页面的主体色改变的时候触发. +在使用 meta 标签的时候这就很常见了: + +```html + +``` + +### Event: 'devtools-opened' + +在开发者工具打开的时候触发. + +### Event: 'devtools-closed' + +在开发者工具关闭的时候触发. + +### Event: 'devtools-focused' + +在开发者工具获取焦点的时候触发. + +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 \ No newline at end of file From 0b8c2545b98435654a3a437efad1ff43655ad623 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Tue, 8 Mar 2016 22:31:13 -0500 Subject: [PATCH 0103/1265] :memo: Document 'app.focus()' [ci skip] --- docs/api/app.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index f18c978fadd..36b55244a4d 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -248,14 +248,6 @@ This method guarantees that all `beforeunload` and `unload` event handlers are correctly executed. It is possible that a window cancels the quitting by returning `false` in the `beforeunload` event handler. -### `app.hide()` _OS X_ - -Hides all application windows without minimizing them. - -### `app.show()` _OS X_ - -Shows application windows after they were hidden. Does not automatically focus them. - ### `app.exit(exitCode)` * `exitCode` Integer @@ -265,6 +257,18 @@ Exits immediately with `exitCode`. All windows will be closed immediately without asking user and the `before-quit` and `will-quit` events will not be emitted. +### `app.focus()` + +On Linux, focuses on the first visible window. On OS X, makes the application the active app. On Windows, focuses on the application's first window. + +### `app.hide()` _OS X_ + +Hides all application windows without minimizing them. + +### `app.show()` _OS X_ + +Shows application windows after they were hidden. Does not automatically focus them. + ### `app.getAppPath()` Returns the current application directory. From 51f60d8d73c4d01c8c00a8ee87fd807da31a0cad Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 9 Mar 2016 23:23:22 +0800 Subject: [PATCH 0104/1265] add window.open --- docs-translations/zh-CN/api/web-view-tag.md | 4 +- docs-translations/zh-CN/api/window-open.md | 60 +++++++++++++++++++++ 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 docs-translations/zh-CN/api/window-open.md diff --git a/docs-translations/zh-CN/api/web-view-tag.md b/docs-translations/zh-CN/api/web-view-tag.md index 819d57cb459..f1f3ef9080c 100644 --- a/docs-translations/zh-CN/api/web-view-tag.md +++ b/docs-translations/zh-CN/api/web-view-tag.md @@ -1,6 +1,6 @@ # `` 标签 -使用 `webview` 标签来把 'guest' 内容(例如 web pages )嵌入到你的 Electron app 中. guest内容包含在 `webview` 容器中.一个嵌入你的应用的page控制着guest内容如何布局摆放和表达含义. +使用 `webview` 标签来把 'guest' 内容(例如 web pages )嵌入到你的 Electron app 中. guest内容包含在 `webview` 容器中.一个嵌入你应用的page控制着guest内容如何布局摆放和表达含义. 与 `iframe` 不同, `webview` 和你的应用运行的是不同的进程. 它不拥有渲染进程的权限,并且应用和嵌入内容之间的交互全部都是异步的.因为这能保证应用的安全性不受嵌入内容的影响. @@ -64,7 +64,7 @@ ``` -如果这个属性的值为 "on" , `webview` 中的 guest page 将整合node,并且拥有可以使用系统底层的资源,例如 `require` 和 `process` . +如果设置了这个属性, `webview` 中的 guest page 将整合node,并且拥有可以使用系统底层的资源,例如 `require` 和 `process` . ### `plugins` diff --git a/docs-translations/zh-CN/api/window-open.md b/docs-translations/zh-CN/api/window-open.md new file mode 100644 index 00000000000..a8ef042b0e3 --- /dev/null +++ b/docs-translations/zh-CN/api/window-open.md @@ -0,0 +1,60 @@ +# `window.open` 函数 + +当在界面中使用 `window.open` 来创建一个新的窗口时候,将会创建一个 `BrowserWindow` 的实例,并且将返回一个标识,这个界面通过标识来对这个新的窗口进行有限的控制. + +这个标识对传统的web界面来说,通过它能对子窗口进行有限的功能性兼容控制. +想要完全的控制这个窗口,可以直接创建一个 `BrowserWindow` . + +新创建的 `BrowserWindow` 默认为继承父窗口的属性参数,想重写属性的话可以在 `features` 中设置他们. + +### `window.open(url[, frameName][, features])` + +* `url` String +* `frameName` String (可选) +* `features` String (可选) + +创建一个新的window并且返回一个 `BrowserWindowProxy` 类的实例. + + `features` 遵循标准浏览器的格式,但是每个feature 应该作为 `BrowserWindow` 参数的一个字段. + +### `window.opener.postMessage(message, targetOrigin)` + +* `message` String +* `targetOrigin` String + +通过指定位置或用 `*` 来代替没有明确位置来向父窗口发送信息. + +## Class: BrowserWindowProxy + +`BrowserWindowProxy` 由`window.open` 创建返回,并且提供了对子窗口的有限功能性控制. + +### `BrowserWindowProxy.blur()` + +取消对子窗口的聚焦. +### `BrowserWindowProxy.close()` + +强行关闭子窗口,忽略卸载事件. + +### `BrowserWindowProxy.closed` + +在子窗口关闭之后恢复正常. + +### `BrowserWindowProxy.eval(code)` + +* `code` String + +评估子窗口的代码. + +### `BrowserWindowProxy.focus()` + +聚焦子窗口(让其现实在最前). + +### `BrowserWindowProxy.postMessage(message, targetOrigin)` + +* `message` String +* `targetOrigin` String + + +通过指定位置或用 `*` 来代替没有明确位置来向子窗口发送信息. + +除了这些方法,子窗口还可以无特性和使用单一方法来实现 `window.opener` 对象. \ No newline at end of file From 4c45c80fb4c373186b70c7c96fee37e3f01d654e Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 10 Mar 2016 00:20:52 +0900 Subject: [PATCH 0105/1265] :memo: Update as upstream --- docs-translations/ko-KR/api/accelerator.md | 3 +++ docs-translations/ko-KR/api/app.md | 9 +++++++ docs-translations/ko-KR/api/browser-window.md | 12 +++++----- docs-translations/ko-KR/api/menu.md | 4 +++- docs-translations/ko-KR/api/synopsis.md | 4 ++-- docs-translations/ko-KR/api/web-contents.md | 8 ++----- .../ko-KR/development/coding-style.md | 24 +++++++++++++------ .../desktop-environment-integration.md | 14 +++++------ 8 files changed, 48 insertions(+), 30 deletions(-) diff --git a/docs-translations/ko-KR/api/accelerator.md b/docs-translations/ko-KR/api/accelerator.md index 99b549bbb70..90adf414dc3 100644 --- a/docs-translations/ko-KR/api/accelerator.md +++ b/docs-translations/ko-KR/api/accelerator.md @@ -22,6 +22,8 @@ Linux와 Windows에서는 `Command`키가 없으므로 작동하지 않습니다 * `Control` (단축어 `Ctrl`) * `CommandOrControl` (단축어 `CmdOrCtrl`) * `Alt` +* `Option` +* `AltGr` * `Shift` * `Super` @@ -43,5 +45,6 @@ Linux와 Windows에서는 `Command`키가 없으므로 작동하지 않습니다 * `Escape` (단축어 `Esc`) * `VolumeUp`, `VolumeDown` 그리고 `VolumeMute` * `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` 그리고 `MediaPlayPause` +* `PrintScreen` __키코드는 `단축어`로도 사용할 수 있습니다__ diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 048026e0d59..72da6862741 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -236,6 +236,10 @@ app.on('login', function(event, webContents, request, authInfo, callback) { GPU가 작동하던 중 크래시가 일어났을 때 발생하는 이벤트입니다. +### Event: 'platform-theme-changed' _OS X_ + +시스템의 다크 모드 테마가 토글되면 발생하는 이벤트입니다. + ## Methods `app` 객체는 다음과 같은 메서드를 가지고 있습니다: @@ -471,6 +475,11 @@ if (browserOptions.transparent) { } ``` +### `app.isDarkMode()` _OS X_ + +이 메서드는 시스템이 다크 모드 상태인 경우 `true`를 반환하고 아닐 경우 `false`를 +반환합니다. + ### `app.commandLine.appendSwitch(switch[, value])` Chrominum의 명령줄에 스위치를 추가합니다. `value`는 추가적인 값을 뜻하며 옵션입니다. diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 8bc4a1545fc..3517f3d500c 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -59,8 +59,8 @@ win.show(); * `alwaysOnTop` Boolean - 윈도우이 언제나 다른 창들 위에 유지되는지 여부. 기본값은 `false`입니다. * `fullscreen` Boolean - 윈도우의 전체화면 활성화 여부. 이 속성을 명시적으로 - `false`로 지정했을 경우, OS X에선 전체화면 버튼이 숨겨지거나 비활성화되고, - Windows에선 최대화 버튼이 비활성화됩니다. 기본값은 `false` 입니다. + `false`로 지정했을 경우, OS X에선 전체화면 버튼이 숨겨지거나 비활성됩니다. 기본값은 + `false` 입니다. * `fullscreenable` Boolean - OS X의 최대화/줌 버튼이 전체화면 모드 또는 윈도우 최대화를 토글할 수 있게 할지 여부입니다. 기본값은 `true` 입니다. * `skipTaskbar` Boolean - 작업표시줄 어플리케이션 아이콘 표시 스킵 여부. 기본값은 @@ -575,17 +575,17 @@ var win = new BrowserWindow({ width: 800, height: 600 }); 사용자에 의해 윈도우를 최대화시킬 수 있는지 여부를 반환합니다. Linux에선 항상 `true`를 반환합니다. -### `win.setFullScreenable(fullscreenable)` _OS X_ +### `win.setFullScreenable(fullscreenable)` * `fullscreenable` Boolean 최대화/줌 버튼이 전체화면 모드 또는 윈도우 최대화를 토글할 수 있게 할지 여부를 -지정합니다. Windows와 Linux에선 아무 일도 일어나지 않습니다. +지정합니다. -### `win.isFullScreenable()` _OS X_ +### `win.isFullScreenable()` 최대화/줌 버튼이 전체화면 모드 또는 윈도우 최대화를 토글할 수 있게 할지 여부를 -반환합니다. Windows와 Linux에선 항상 `true`를 반환합니다. +반환합니다. ### `win.setClosable(closable)` _OS X_ _Windows_ diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 61c68023b07..1ea8289a9ce 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -223,7 +223,9 @@ Linux에선 각 창의 상단에 표시됩니다. `action`을 어플리케이션의 first responder에 전달합니다. 이 메서드는 Cocoa 메뉴 동작을 에뮬레이트 하는데 사용되며 보통 `MenuItem`의 `role` 속성에 사용됩니다. -**참고:** 이 메서드는 OS X에서만 사용할 수 있습니다. +OS X의 네이티브 액션에 대해 자세히 알아보려면 +[OS X Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) +문서를 참고하세요. ### `Menu.buildFromTemplate(template)` diff --git a/docs-translations/ko-KR/api/synopsis.md b/docs-translations/ko-KR/api/synopsis.md index e70dfbb3349..8f59d12c1ce 100644 --- a/docs-translations/ko-KR/api/synopsis.md +++ b/docs-translations/ko-KR/api/synopsis.md @@ -49,7 +49,7 @@ app.on('ready', function() { ## 분리 할당 만약 CoffeeScript나 Babel을 사용하고 있다면, 빌트인 모듈을 사용할 때 -[분리 할당][desctructuring-assignment]을 통해 직관적으로 사용할 수 있습니다: +[분리 할당][destructuring-assignment]을 통해 직관적으로 사용할 수 있습니다: ```javascript const {app, BrowserWindow} = require('electron') @@ -78,5 +78,5 @@ require('electron').hideInternalModules() ``` [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface -[desctructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment +[destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment [issue-387]: https://github.com/atom/electron/issues/387 diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index ed2f05f1d5a..96b5eacc544 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -758,12 +758,8 @@ Input `event`를 웹 페이지로 전송합니다. 키보드 이벤트들에 대해서는 `event` 객체는 다음 속성들을 사용할 수 있습니다: -* `keyCode` Char or String (**required**) - 키보드 이벤트로 보내지는 문자. 단일 - UTF-8 문자를 사용할 수 있고 이벤트를 발생시키는 다음 키 중 하나를 포함할 수 있습니다: - `enter`, `backspace`, `delete`, `tab`, `escape`, `control`, `alt`, `altgr` - (Windows 전용), `shift`, `end`, `home`, `insert`, `left`, `up`, `right`, - `down`, `pageUp`, `pageDown`, `printScreen`, `meta`, `cmd` (OSX 전용), - `command` (OSX 전용), `option` (OSX 전용) +* `keyCode` String (**required**) - 키보드 이벤트가 발생할 때 보내질 문자. + [Accelerator](accelerator.md)의 올바른 키 코드만 사용해야 합니다. 마우스 이벤트들에 대해서는 `event` 객체는 다음 속성들을 사용할 수 있습니다: diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index 21ee03fd0a1..dd64e724517 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -2,6 +2,9 @@ 이 가이드는 Electron의 코딩 스타일에 관해 설명합니다. +`npm run lint`를 실행하여 `cpplint`와 `eslint`를 통해 어떤 코딩 스타일 이슈를 확인할 +수 있습니다. + ## C++과 Python C++과 Python 스크립트는 Chromium의 @@ -18,17 +21,24 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 자동으로 메모리에서 할당을 해제합니다. 스마트 포인터와 같습니다) 그리고 로깅 메커니즘 등을 언급하고 있습니다. -## CoffeeScript - -CoffeeScript의 경우 GitHub의 -[스타일 가이드](https://github.com/styleguide/javascript)를 기본으로 따릅니다. -그리고 추가로 다음 규칙을 따릅니다: +## JavaScript +* 하드 탭(hard tabs) 대신 소프트 탭(2 spaces) 들여쓰기를 사용합니다. +* 항상 구문의 끝은 `;`으로 마쳐야 합니다. * Google의 코딩 스타일에도 맞추기 위해 파일의 끝에는 **절대** 개행을 삽입해선 안됩니다. * 파일 이름의 공백은 `_`대신에 `-`을 사용하여야 합니다. 예를 들어 -`file_name.coffee`를 `file-name.coffee`로 고쳐야합니다. 왜냐하면 +`file_name.js`를 `file-name.js`로 고쳐야합니다. 왜냐하면 [github/atom](https://github.com/github/atom)에서 사용되는 모듈의 이름은 보통 -`module-name` 형식이기 때문입니다. 이 규칙은 '.coffee' 파일에만 적용됩니다. +`module-name` 형식이기 때문입니다. 이 규칙은 '.js' 파일에만 적용됩니다. +* 적절한 곳에 새로운 ES6/ES2015 문법을 사용해도 됩니다. + * [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) + 는 requires와 다른 상수에 사용합니다 + * [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) + 은 변수를 정의할 때 사용합니다 + * [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) + 는 `function () { }` 표현 대신에 사용합니다 + * [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) + 는 `+`로 문자열을 합치는 대신 사용합니다. ## API 이름 diff --git a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md index 38830b91e82..c72af78a278 100644 --- a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md +++ b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md @@ -239,22 +239,20 @@ __Audacious의 런처 숏컷:__ ![audacious](https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png) -## Taskbar progress 기능 (Windows & Unity) +## 작업 표시줄 안의 프로그래스 바 (Windows, OS X, Unity) -Windows에선 태스크바의 어플리케이션 버튼에 progress bar를 추가할 수 있습니다. +Windows에선 작업 표시줄의 어플리케이션 버튼에 프로그래스 바를 추가할 수 있습니다. 이 기능은 사용자가 어플리케이션의 창을 열지 않고도 어플리케이션의 작업의 상태 정보를 시각적으로 보여줄 수 있도록 해줍니다. -또한 Unity DE도 런처에 progress bar를 부착할 수 있습니다. +OS X에선 프로그래스바가 dock 아이콘의 일부에 표시됩니다. -__태스크바 버튼의 progress bar:__ +또한 Unity DE도 런처에 프로그래스 바를 부착할 수 있습니다. + +__작업 표시줄 버튼의 프로그래스 바:__ ![Taskbar Progress Bar](https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png) -__Unity 런처의 progress bar:__ - -![Unity Launcher](https://cloud.githubusercontent.com/assets/639601/5081747/4a0a589e-6f0f-11e4-803f-91594716a546.png) - 이 기능은 [BrowserWindow.setProgressBar][setprogressbar] API를 사용하여 구현할 수 있습니다: From ebf509bbe406bc04b97dde4b4581edfb0b5b35c3 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 10 Mar 2016 16:54:07 +0900 Subject: [PATCH 0106/1265] :memo: Adjust 80 chars per line [ci skip] --- docs/api/app.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/api/app.md b/docs/api/app.md index 36b55244a4d..8935ed894f0 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -259,7 +259,8 @@ and `will-quit` events will not be emitted. ### `app.focus()` -On Linux, focuses on the first visible window. On OS X, makes the application the active app. On Windows, focuses on the application's first window. +On Linux, focuses on the first visible window. On OS X, makes the application +the active app. On Windows, focuses on the application's first window. ### `app.hide()` _OS X_ From 9bc9a1a2bde2b141788f536ec7aaca2cf8091913 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 10:05:44 +0900 Subject: [PATCH 0107/1265] Upgrade to Chrome 49 --- atom/common/chrome_version.h | 2 +- script/lib/config.py | 2 +- vendor/brightray | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/common/chrome_version.h b/atom/common/chrome_version.h index 37a5c64979e..604e0161c3a 100644 --- a/atom/common/chrome_version.h +++ b/atom/common/chrome_version.h @@ -8,7 +8,7 @@ #ifndef ATOM_COMMON_CHROME_VERSION_H_ #define ATOM_COMMON_CHROME_VERSION_H_ -#define CHROME_VERSION_STRING "47.0.2526.110" +#define CHROME_VERSION_STRING "49.0.2623.64" #define CHROME_VERSION "v" CHROME_VERSION_STRING #endif // ATOM_COMMON_CHROME_VERSION_H_ diff --git a/script/lib/config.py b/script/lib/config.py index d4a055912e4..10319a2df4e 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'ff714bf7ad79b0d278bcd20c3081a69b40be8bb8' +LIBCHROMIUMCONTENT_COMMIT = 'a661ccb38f21859309cc97c1fc313f1360101462' PLATFORM = { 'cygwin': 'win32', diff --git a/vendor/brightray b/vendor/brightray index d06de26dff8..b409ed14a17 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit d06de26dff8b641d9aee4c78ee830b416710f554 +Subproject commit b409ed14a17b9efc9f184e102a1b94e9d573760f From 30643cf1189f37df1215210620353090e9e174cf Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 17:58:59 +0900 Subject: [PATCH 0108/1265] Update crashpad to lastest branch --- common.gypi | 2 ++ vendor/brightray | 2 +- vendor/crashpad | 2 +- vendor/native_mate | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/common.gypi b/common.gypi index 7c41c3616df..d8c7ee30935 100644 --- a/common.gypi +++ b/common.gypi @@ -4,6 +4,8 @@ 'vendor/brightray/brightray.gypi', ], 'variables': { + # Tell crashpad to build as external project. + 'crashpad_dependencies': 'external', # Required by breakpad. 'os_bsd': 0, 'chromeos': 0, diff --git a/vendor/brightray b/vendor/brightray index b409ed14a17..bde67658749 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit b409ed14a17b9efc9f184e102a1b94e9d573760f +Subproject commit bde67658749c6f947e2dc505cce19e621d2ad2eb diff --git a/vendor/crashpad b/vendor/crashpad index 5b777419c30..60f6e1964d0 160000 --- a/vendor/crashpad +++ b/vendor/crashpad @@ -1 +1 @@ -Subproject commit 5b777419c303d8aa7930239d8ef755475f1ede57 +Subproject commit 60f6e1964d02b5818f038ba618f9cf040fdce962 diff --git a/vendor/native_mate b/vendor/native_mate index e719eab878c..38834cb9974 160000 --- a/vendor/native_mate +++ b/vendor/native_mate @@ -1 +1 @@ -Subproject commit e719eab878c264bb03188d0cd6eb9ad6882bc13a +Subproject commit 38834cb9974da9ddbc06c36f9ff23d7fa1918b03 From 3600645575bdcda35447bd78ef1625dad29dc754 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 21:00:37 +0900 Subject: [PATCH 0109/1265] Fix the compilation errors from brightray and crashpad --- vendor/brightray | 2 +- vendor/crashpad | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vendor/brightray b/vendor/brightray index bde67658749..2a29ea6c1de 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit bde67658749c6f947e2dc505cce19e621d2ad2eb +Subproject commit 2a29ea6c1de3accd01f1883ac94326220349bbe1 diff --git a/vendor/crashpad b/vendor/crashpad index 60f6e1964d0..db713da7554 160000 --- a/vendor/crashpad +++ b/vendor/crashpad @@ -1 +1 @@ -Subproject commit 60f6e1964d02b5818f038ba618f9cf040fdce962 +Subproject commit db713da7554f565e43c6dcf9a51b59ccc4f06066 From 8d021f25964c79317ed7b3bde3cde18eba59b6e7 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 7 Mar 2016 20:21:47 -0800 Subject: [PATCH 0110/1265] Goodbye pdf.dll --- atom.gyp | 1 - 1 file changed, 1 deletion(-) diff --git a/atom.gyp b/atom.gyp index b7075301894..f4c6976050e 100644 --- a/atom.gyp +++ b/atom.gyp @@ -143,7 +143,6 @@ ], }, { 'copied_libraries': [ - '<(libchromiumcontent_dir)/pdf.dll', '<(libchromiumcontent_dir)/ffmpeg.dll', ], }], From 7f15a77f3c1c8d59197f8ab0997dff0c108859b7 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 7 Mar 2016 20:32:54 -0800 Subject: [PATCH 0111/1265] startup helper is renamed --- atom/app/atom_main.cc | 2 +- filenames.gypi | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/atom/app/atom_main.cc b/atom/app/atom_main.cc index 1ffab8d9225..cbd0a85d576 100644 --- a/atom/app/atom_main.cc +++ b/atom/app/atom_main.cc @@ -16,7 +16,7 @@ #include "atom/common/crash_reporter/win/crash_service_main.h" #include "base/environment.h" #include "base/win/windows_version.h" -#include "content/public/app/startup_helper_win.h" +#include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #include "ui/gfx/win/dpi.h" #elif defined(OS_LINUX) // defined(OS_WIN) diff --git a/filenames.gypi b/filenames.gypi index f9e19550c89..baf0202f3ec 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -534,7 +534,6 @@ 'atom/browser/resources/win/resource.h', 'atom/browser/resources/win/atom.ico', 'atom/browser/resources/win/atom.rc', - '<(libchromiumcontent_src_dir)/content/app/startup_helper_win.cc', # Cursors. '<(libchromiumcontent_src_dir)/ui/resources/cursors/aliasb.cur', '<(libchromiumcontent_src_dir)/ui/resources/cursors/cell.cur', From d2944c62a5dd58de13ebed4e7b55529c9c309b74 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 7 Mar 2016 20:38:49 -0800 Subject: [PATCH 0112/1265] basictypes.h => macros.h --- atom/app/atom_library_main.h | 2 +- atom/browser/auto_updater.h | 2 +- atom/browser/browser.h | 2 +- atom/browser/javascript_environment.h | 2 +- atom/browser/ui/views/global_menu_bar_x11.h | 2 +- atom/browser/ui/win/notify_icon.h | 2 +- atom/browser/window_list.h | 2 +- atom/common/api/object_life_monitor.h | 2 +- atom/common/atom_command_line.h | 2 +- atom/common/crash_reporter/crash_reporter.h | 2 +- atom/common/crash_reporter/linux/crash_dump_handler.h | 2 +- atom/common/crash_reporter/win/crash_service.h | 2 +- atom/common/native_mate_converters/v8_value_converter.h | 2 +- atom/common/node_bindings.h | 2 +- atom/renderer/node_array_buffer_bridge.cc | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/atom/app/atom_library_main.h b/atom/app/atom_library_main.h index 899861f610b..b45e27a4a99 100644 --- a/atom/app/atom_library_main.h +++ b/atom/app/atom_library_main.h @@ -5,7 +5,7 @@ #ifndef ATOM_APP_ATOM_LIBRARY_MAIN_H_ #define ATOM_APP_ATOM_LIBRARY_MAIN_H_ -#include "base/basictypes.h" +#include "base/macros.h" #if defined(OS_MACOSX) extern "C" { diff --git a/atom/browser/auto_updater.h b/atom/browser/auto_updater.h index 9e479d4220d..637545e877f 100644 --- a/atom/browser/auto_updater.h +++ b/atom/browser/auto_updater.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" namespace base { class Time; diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 1d0b4aec8ba..d976fae675c 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -8,7 +8,7 @@ #include #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/compiler_specific.h" #include "base/observer_list.h" #include "base/strings/string16.h" diff --git a/atom/browser/javascript_environment.h b/atom/browser/javascript_environment.h index 20f1667c3b8..07cd602cf00 100644 --- a/atom/browser/javascript_environment.h +++ b/atom/browser/javascript_environment.h @@ -5,7 +5,7 @@ #ifndef ATOM_BROWSER_JAVASCRIPT_ENVIRONMENT_H_ #define ATOM_BROWSER_JAVASCRIPT_ENVIRONMENT_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "gin/public/isolate_holder.h" namespace atom { diff --git a/atom/browser/ui/views/global_menu_bar_x11.h b/atom/browser/ui/views/global_menu_bar_x11.h index 9049fbf606d..89b2680cabe 100644 --- a/atom/browser/ui/views/global_menu_bar_x11.h +++ b/atom/browser/ui/views/global_menu_bar_x11.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/compiler_specific.h" #include "ui/base/glib/glib_signal.h" #include "ui/gfx/native_widget_types.h" diff --git a/atom/browser/ui/win/notify_icon.h b/atom/browser/ui/win/notify_icon.h index 23608c7c7ab..53ed49b937c 100644 --- a/atom/browser/ui/win/notify_icon.h +++ b/atom/browser/ui/win/notify_icon.h @@ -11,7 +11,7 @@ #include #include "atom/browser/ui/tray_icon.h" -#include "base/basictypes.h" +#include "base/macros.h" #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "base/win/scoped_gdi_object.h" diff --git a/atom/browser/window_list.h b/atom/browser/window_list.h index bfb9a2b0aec..3dd87b2c34c 100644 --- a/atom/browser/window_list.h +++ b/atom/browser/window_list.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/lazy_instance.h" #include "base/observer_list.h" diff --git a/atom/common/api/object_life_monitor.h b/atom/common/api/object_life_monitor.h index 90216d8227a..4c932b94c7b 100644 --- a/atom/common/api/object_life_monitor.h +++ b/atom/common/api/object_life_monitor.h @@ -5,7 +5,7 @@ #ifndef ATOM_COMMON_API_OBJECT_LIFE_MONITOR_H_ #define ATOM_COMMON_API_OBJECT_LIFE_MONITOR_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "v8/include/v8.h" diff --git a/atom/common/atom_command_line.h b/atom/common/atom_command_line.h index 7c8840f7075..56ecb8fbd49 100644 --- a/atom/common/atom_command_line.h +++ b/atom/common/atom_command_line.h @@ -8,7 +8,7 @@ #include #include -#include "base/basictypes.h" +#include "base/macros.h" namespace atom { diff --git a/atom/common/crash_reporter/crash_reporter.h b/atom/common/crash_reporter/crash_reporter.h index 98832fea45d..eebbe16dca8 100644 --- a/atom/common/crash_reporter/crash_reporter.h +++ b/atom/common/crash_reporter/crash_reporter.h @@ -10,7 +10,7 @@ #include #include -#include "base/basictypes.h" +#include "base/macros.h" namespace crash_reporter { diff --git a/atom/common/crash_reporter/linux/crash_dump_handler.h b/atom/common/crash_reporter/linux/crash_dump_handler.h index f600c9e0d1b..00161f02ee5 100644 --- a/atom/common/crash_reporter/linux/crash_dump_handler.h +++ b/atom/common/crash_reporter/linux/crash_dump_handler.h @@ -6,7 +6,7 @@ #ifndef ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_ #define ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "vendor/breakpad/src/common/simple_string_dictionary.h" namespace crash_reporter { diff --git a/atom/common/crash_reporter/win/crash_service.h b/atom/common/crash_reporter/win/crash_service.h index 7195ec2a958..c05e0d5bf6e 100644 --- a/atom/common/crash_reporter/win/crash_service.h +++ b/atom/common/crash_reporter/win/crash_service.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/files/file_path.h" #include "base/synchronization/lock.h" diff --git a/atom/common/native_mate_converters/v8_value_converter.h b/atom/common/native_mate_converters/v8_value_converter.h index 95840c01ba7..632587022d1 100644 --- a/atom/common/native_mate_converters/v8_value_converter.h +++ b/atom/common/native_mate_converters/v8_value_converter.h @@ -5,7 +5,7 @@ #ifndef ATOM_COMMON_NATIVE_MATE_CONVERTERS_V8_VALUE_CONVERTER_H_ #define ATOM_COMMON_NATIVE_MATE_CONVERTERS_V8_VALUE_CONVERTER_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "base/compiler_specific.h" #include "v8/include/v8.h" diff --git a/atom/common/node_bindings.h b/atom/common/node_bindings.h index 93ad7714916..16d512d3bed 100644 --- a/atom/common/node_bindings.h +++ b/atom/common/node_bindings.h @@ -5,7 +5,7 @@ #ifndef ATOM_COMMON_NODE_BINDINGS_H_ #define ATOM_COMMON_NODE_BINDINGS_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "v8/include/v8.h" #include "vendor/node/deps/uv/include/uv.h" diff --git a/atom/renderer/node_array_buffer_bridge.cc b/atom/renderer/node_array_buffer_bridge.cc index 80f2530524d..c4b8d26adaa 100644 --- a/atom/renderer/node_array_buffer_bridge.cc +++ b/atom/renderer/node_array_buffer_bridge.cc @@ -4,7 +4,7 @@ #include "atom/renderer/node_array_buffer_bridge.h" -#include "base/basictypes.h" +#include "base/macros.h" #include "atom/common/node_includes.h" #include "native_mate/converter.h" #include "third_party/WebKit/public/web/WebArrayBuffer.h" From 4503aafe6467e0fd2d1d2e8c2234cbc4b663a8d3 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 7 Mar 2016 20:40:10 -0800 Subject: [PATCH 0113/1265] int32 => int32_t --- atom/browser/api/atom_api_download_item.cc | 2 +- atom/browser/api/atom_api_session.cc | 12 ++++++------ atom/browser/api/atom_api_web_contents.cc | 8 ++++---- atom/browser/api/atom_api_web_contents.h | 10 +++++----- atom/browser/atom_download_manager_delegate.cc | 4 ++-- atom/browser/atom_download_manager_delegate.h | 2 +- atom/common/api/atom_api_clipboard.cc | 4 ++-- atom/common/asar/archive.cc | 8 ++++---- atom/common/asar/archive.h | 4 ++-- .../native_mate_converters/v8_value_converter.cc | 10 +++++----- atom/renderer/api/atom_api_spell_check_client.cc | 2 +- 11 files changed, 33 insertions(+), 33 deletions(-) diff --git a/atom/browser/api/atom_api_download_item.cc b/atom/browser/api/atom_api_download_item.cc index 5a8befc9d1d..de3a5b348ee 100644 --- a/atom/browser/api/atom_api_download_item.cc +++ b/atom/browser/api/atom_api_download_item.cc @@ -53,7 +53,7 @@ namespace { using WrapDownloadItemCallback = base::Callback)>; WrapDownloadItemCallback g_wrap_download_item; -std::map>> g_download_item_objects; +std::map>> g_download_item_objects; } // namespace diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index e5c5198f034..0f104c76072 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -49,12 +49,12 @@ namespace { struct ClearStorageDataOptions { GURL origin; - uint32 storage_types = StoragePartition::REMOVE_DATA_MASK_ALL; - uint32 quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL; + uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL; + uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL; }; -uint32 GetStorageMask(const std::vector& storage_types) { - uint32 storage_mask = 0; +uint32_t GetStorageMask(const std::vector& storage_types) { + uint32_t storage_mask = 0; for (const auto& it : storage_types) { auto type = base::ToLowerASCII(it); if (type == "appcache") @@ -77,8 +77,8 @@ uint32 GetStorageMask(const std::vector& storage_types) { return storage_mask; } -uint32 GetQuotaMask(const std::vector& quota_types) { - uint32 quota_mask = 0; +uint32_t GetQuotaMask(const std::vector& quota_types) { + uint32_t quota_mask = 0; for (const auto& it : quota_types) { auto type = base::ToLowerASCII(it); if (type == "temporary") diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 12e0c56ceb6..1f4c9f92b35 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -303,9 +303,9 @@ WebContents::~WebContents() { } bool WebContents::AddMessageToConsole(content::WebContents* source, - int32 level, + int32_t level, const base::string16& message, - int32 line_no, + int32_t line_no, const base::string16& source_id) { if (type_ == BROWSER_WINDOW) { return false; @@ -998,8 +998,8 @@ void WebContents::ReplaceMisspelling(const base::string16& word) { web_contents()->ReplaceMisspelling(word); } -uint32 WebContents::FindInPage(mate::Arguments* args) { - uint32 request_id = GetNextRequestId(); +uint32_t WebContents::FindInPage(mate::Arguments* args) { + uint32_t request_id = GetNextRequestId(); base::string16 search_text; blink::WebFindOptions options; if (!args->GetNext(&search_text) || search_text.empty()) { diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index a785e1c070d..a008a84913b 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -110,7 +110,7 @@ class WebContents : public mate::TrackableObject, void Unselect(); void Replace(const base::string16& word); void ReplaceMisspelling(const base::string16& word); - uint32 FindInPage(mate::Arguments* args); + uint32_t FindInPage(mate::Arguments* args); void StopFindInPage(content::StopFindAction action); // Focus. @@ -162,9 +162,9 @@ class WebContents : public mate::TrackableObject, // content::WebContentsDelegate: bool AddMessageToConsole(content::WebContents* source, - int32 level, + int32_t level, const base::string16& message, - int32 line_no, + int32_t line_no, const base::string16& source_id) override; bool ShouldCreateWebContents( content::WebContents* web_contents, @@ -270,7 +270,7 @@ class WebContents : public mate::TrackableObject, AtomBrowserContext* GetBrowserContext() const; - uint32 GetNextRequestId() { + uint32_t GetNextRequestId() { return ++request_id_; } @@ -299,7 +299,7 @@ class WebContents : public mate::TrackableObject, Type type_; // Request id used for findInPage request. - uint32 request_id_; + uint32_t request_id_; DISALLOW_COPY_AND_ASSIGN(WebContents); }; diff --git a/atom/browser/atom_download_manager_delegate.cc b/atom/browser/atom_download_manager_delegate.cc index f5bdbbd8598..16c0cf708b8 100644 --- a/atom/browser/atom_download_manager_delegate.cc +++ b/atom/browser/atom_download_manager_delegate.cc @@ -60,7 +60,7 @@ void AtomDownloadManagerDelegate::CreateDownloadPath( } void AtomDownloadManagerDelegate::OnDownloadPathGenerated( - uint32 download_id, + uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -160,7 +160,7 @@ bool AtomDownloadManagerDelegate::ShouldOpenDownload( void AtomDownloadManagerDelegate::GetNextId( const content::DownloadIdCallback& callback) { - static uint32 next_id = content::DownloadItem::kInvalidId + 1; + static uint32_t next_id = content::DownloadItem::kInvalidId + 1; callback.Run(next_id++); } diff --git a/atom/browser/atom_download_manager_delegate.h b/atom/browser/atom_download_manager_delegate.h index 2df3a7d45a6..5ea3d50d5ae 100644 --- a/atom/browser/atom_download_manager_delegate.h +++ b/atom/browser/atom_download_manager_delegate.h @@ -31,7 +31,7 @@ class AtomDownloadManagerDelegate : public content::DownloadManagerDelegate { const std::string& mime_type, const base::FilePath& path, const CreateDownloadPathCallback& callback); - void OnDownloadPathGenerated(uint32 download_id, + void OnDownloadPathGenerated(uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& default_path); diff --git a/atom/common/api/atom_api_clipboard.cc b/atom/common/api/atom_api_clipboard.cc index 5186e22c8d9..1f75f2cd3fe 100644 --- a/atom/common/api/atom_api_clipboard.cc +++ b/atom/common/api/atom_api_clipboard.cc @@ -109,8 +109,8 @@ base::string16 ReadHtml(mate::Arguments* args) { base::string16 data; base::string16 html; std::string url; - uint32 start; - uint32 end; + uint32_t start; + uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end); data = html.substr(start, end - start); diff --git a/atom/common/asar/archive.cc b/atom/common/asar/archive.cc index 35451410a8d..b5a9603acb1 100644 --- a/atom/common/asar/archive.cc +++ b/atom/common/asar/archive.cc @@ -90,12 +90,12 @@ bool GetNodeFromPath(std::string path, } bool FillFileInfoWithNode(Archive::FileInfo* info, - uint32 header_size, + uint32_t header_size, const base::DictionaryValue* node) { int size; if (!node->GetInteger("size", &size)) return false; - info->size = static_cast(size); + info->size = static_cast(size); if (node->GetBoolean("unpacked", &info->unpacked) && info->unpacked) return true; @@ -157,8 +157,8 @@ bool Archive::Init() { return false; } - uint32 size; - if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUInt32( + uint32_t size; + if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUint32_t( &size)) { LOG(ERROR) << "Failed to parse header size from " << path_.value(); return false; diff --git a/atom/common/asar/archive.h b/atom/common/asar/archive.h index de5b9de605a..6bde7bd1ff2 100644 --- a/atom/common/asar/archive.h +++ b/atom/common/asar/archive.h @@ -28,7 +28,7 @@ class Archive { FileInfo() : unpacked(false), executable(false), size(0), offset(0) {} bool unpacked; bool executable; - uint32 size; + uint32_t size; uint64 offset; }; @@ -71,7 +71,7 @@ class Archive { base::FilePath path_; base::File file_; int fd_; - uint32 header_size_; + uint32_t header_size_; scoped_ptr header_; // Cached external temporary files. diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index 1a729dda535..b35f1eb6a0b 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -169,7 +169,7 @@ v8::Local V8ValueConverter::ToV8Array( CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch; - result->Set(static_cast(i), child_v8); + result->Set(static_cast(i), child_v8); if (try_catch.HasCaught()) LOG(ERROR) << "Setter for index " << i << " threw an exception."; } @@ -222,8 +222,8 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsBoolean()) return new base::FundamentalValue(val->ToBoolean()->Value()); - if (val->IsInt32()) - return new base::FundamentalValue(val->ToInt32()->Value()); + if (val->Isint32_t()) + return new base::FundamentalValue(val->Toint32_t()->Value()); if (val->IsNumber()) return new base::FundamentalValue(val->ToNumber()->Value()); @@ -298,7 +298,7 @@ base::Value* V8ValueConverter::FromV8Array( base::ListValue* result = new base::ListValue(); // Only fields with integer keys are carried over to the ListValue. - for (uint32 i = 0; i < val->Length(); ++i) { + for (uint32_t i = 0; i < val->Length(); ++i) { v8::TryCatch try_catch; v8::Local child_v8 = val->Get(i); if (try_catch.HasCaught()) { @@ -345,7 +345,7 @@ base::Value* V8ValueConverter::FromV8Object( scoped_ptr result(new base::DictionaryValue()); v8::Local property_names(val->GetOwnPropertyNames()); - for (uint32 i = 0; i < property_names->Length(); ++i) { + for (uint32_t i = 0; i < property_names->Length(); ++i) { v8::Local key(property_names->Get(i)); // Extend this test to cover more types as necessary and if sensible. diff --git a/atom/renderer/api/atom_api_spell_check_client.cc b/atom/renderer/api/atom_api_spell_check_client.cc index 25d1e30b0aa..51c5f721f02 100644 --- a/atom/renderer/api/atom_api_spell_check_client.cc +++ b/atom/renderer/api/atom_api_spell_check_client.cc @@ -27,7 +27,7 @@ bool HasWordCharacters(const base::string16& text, int index) { const base::char16* data = text.data(); int length = text.length(); while (index < length) { - uint32 code = 0; + uint32_t code = 0; U16_NEXT(data, index, length, code); UErrorCode error = U_ZERO_ERROR; if (uscript_getScript(code, &error) != USCRIPT_COMMON) From 5fae63a2f5d030ddb49d032bab7c50cc25d20d05 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 23:28:53 +0900 Subject: [PATCH 0114/1265] Fix compilation errors on OS X --- atom/app/atom_library_main.h | 2 +- atom/app/atom_main_delegate.cc | 2 +- atom/browser/api/atom_api_app.cc | 6 +- atom/browser/api/atom_api_app.h | 3 +- atom/browser/api/atom_api_content_tracing.cc | 15 +--- atom/browser/api/atom_api_cookies.cc | 3 +- atom/browser/api/atom_api_desktop_capturer.cc | 7 +- atom/browser/api/atom_api_download_item.cc | 4 +- atom/browser/api/atom_api_download_item.h | 4 +- atom/browser/api/atom_api_protocol.h | 4 +- atom/browser/api/atom_api_web_contents.cc | 14 ++-- atom/browser/api/atom_api_web_contents.h | 9 +-- atom/browser/api/frame_subscriber.cc | 2 +- atom/browser/atom_browser_client.cc | 7 +- atom/browser/atom_browser_client.h | 3 +- atom/browser/atom_browser_context.cc | 7 +- atom/browser/atom_permission_manager.cc | 20 ++++++ atom/browser/atom_permission_manager.h | 7 ++ .../atom_resource_dispatcher_host_delegate.cc | 4 +- .../atom_resource_dispatcher_host_delegate.h | 13 ++-- ...atom_speech_recognition_manager_delegate.h | 1 + atom/browser/common_web_contents_delegate.cc | 7 +- atom/browser/javascript_environment.cc | 1 + atom/browser/native_window.cc | 9 +-- atom/browser/net/asar/url_request_asar_job.cc | 72 +++++++++---------- atom/browser/net/asar/url_request_asar_job.h | 12 ++-- atom/browser/net/atom_network_delegate.cc | 8 +-- atom/browser/net/js_asker.h | 2 +- atom/browser/net/url_request_fetch_job.cc | 16 ++--- atom/browser/net/url_request_fetch_job.h | 4 +- atom/browser/node_debugger.cc | 2 +- atom/browser/ui/accelerator_util_mac.mm | 2 +- atom/browser/ui/message_box_mac.mm | 2 +- atom/browser/web_view_guest_delegate.cc | 11 +-- atom/common/api/atom_api_asar.cc | 4 +- atom/common/api/atom_bindings.h | 1 + atom/common/asar/archive.cc | 4 +- atom/common/asar/archive.h | 2 +- atom/common/asar/scoped_temporary_file.cc | 2 +- atom/common/asar/scoped_temporary_file.h | 2 +- .../crash_reporter/crash_reporter_mac.mm | 3 +- .../native_mate_converters/net_converter.cc | 8 +-- .../v8_value_converter.cc | 4 +- atom/common/node_bindings.cc | 2 +- .../api/atom_api_spell_check_client.cc | 60 +--------------- .../api/atom_api_spell_check_client.h | 2 - chromium_src/chrome/browser/browser_process.h | 2 +- .../extensions/global_shortcut_listener.h | 2 +- .../chrome/browser/media/desktop_media_list.h | 1 - .../media/native_desktop_media_list.cc | 17 ++--- .../browser/media/native_desktop_media_list.h | 1 - .../browser/printing/pdf_to_emf_converter.cc | 2 +- .../chrome/browser/printing/print_job.cc | 2 +- .../chrome/browser/printing/print_job.h | 1 - .../printing/print_preview_message_handler.cc | 2 +- .../printing/print_preview_message_handler.h | 2 +- .../printing/print_view_manager_base.cc | 10 +-- .../printing/printing_message_filter.cc | 2 +- .../printing/printing_message_filter.h | 2 +- .../printing_ui_web_contents_observer.h | 1 - .../chrome/browser/process_singleton.h | 1 - .../chrome/browser/process_singleton_posix.cc | 10 +-- .../pepper/pepper_flash_browser_host.h | 1 - .../pepper_flash_clipboard_message_filter.cc | 4 +- .../pepper_flash_clipboard_message_filter.h | 2 - .../browser/ui/cocoa/color_chooser_mac.mm | 6 +- .../browser/ui/views/color_chooser_aura.h | 2 - .../frame/global_menu_bar_registrar_x11.h | 1 - chromium_src/chrome/common/print_messages.cc | 1 - chromium_src/chrome/common/print_messages.h | 4 +- .../chrome/common/tts_utterance_request.h | 4 +- .../chrome/common/widevine_cdm_constants.cc | 4 +- .../chrome/common/widevine_cdm_constants.h | 4 +- .../chrome_renderer_pepper_host_factory.h | 2 - .../pepper/pepper_flash_font_file_host.h | 2 - .../pepper/pepper_flash_fullscreen_host.h | 2 - .../pepper/pepper_flash_renderer_host.h | 1 - .../pepper_shared_memory_message_filter.cc | 5 +- .../pepper_shared_memory_message_filter.h | 2 - .../printing/print_web_view_helper.cc | 24 +++---- .../printing/print_web_view_helper_linux.cc | 2 +- .../printing/print_web_view_helper_mac.mm | 4 +- .../printing/print_web_view_helper_pdf_win.cc | 4 +- .../spellchecker/spellcheck_worditerator.cc | 3 +- .../spellchecker/spellcheck_worditerator.h | 2 +- .../chrome/renderer/tts_dispatcher.cc | 3 +- chromium_src/chrome/renderer/tts_dispatcher.h | 4 +- .../chrome/utility/printing_handler_win.cc | 2 +- .../stream_listen_socket.cc | 4 +- .../stream_listen_socket.h | 2 +- .../embedded_test_server/tcp_listen_socket.cc | 11 +-- .../embedded_test_server/tcp_listen_socket.h | 8 +-- vendor/brightray | 2 +- 93 files changed, 242 insertions(+), 317 deletions(-) diff --git a/atom/app/atom_library_main.h b/atom/app/atom_library_main.h index b45e27a4a99..e1603fa5942 100644 --- a/atom/app/atom_library_main.h +++ b/atom/app/atom_library_main.h @@ -5,7 +5,7 @@ #ifndef ATOM_APP_ATOM_LIBRARY_MAIN_H_ #define ATOM_APP_ATOM_LIBRARY_MAIN_H_ -#include "base/macros.h" +#include "build/build_config.h" #if defined(OS_MACOSX) extern "C" { diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index 698da4f4def..221d59c1619 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -135,7 +135,7 @@ content::ContentUtilityClient* AtomMainDelegate::CreateContentUtilityClient() { } scoped_ptr AtomMainDelegate::CreateContentClient() { - return scoped_ptr(new AtomContentClient).Pass(); + return scoped_ptr(new AtomContentClient); } } // namespace atom diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 0c235a56cb4..d728d9dd546 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -230,8 +230,7 @@ void App::OnLogin(LoginHandler* login_handler) { } void App::AllowCertificateError( - int pid, - int fid, + content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, @@ -241,9 +240,6 @@ void App::AllowCertificateError( bool expired_previous_decision, const base::Callback& callback, content::CertificateRequestResultType* request) { - auto rfh = content::RenderFrameHost::FromID(pid, fid); - auto web_contents = content::WebContents::FromRenderFrameHost(rfh); - v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); bool prevent_default = Emit("certificate-error", diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 3d4ac17adf7..5faf8ebb10e 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -52,8 +52,7 @@ class App : public AtomBrowserClient::Delegate, // content::ContentBrowserClient: void AllowCertificateError( - int render_process_id, - int render_frame_id, + content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, diff --git a/atom/browser/api/atom_api_content_tracing.cc b/atom/browser/api/atom_api_content_tracing.cc index f29946d1f46..937a87ea213 100644 --- a/atom/browser/api/atom_api_content_tracing.cc +++ b/atom/browser/api/atom_api_content_tracing.cc @@ -53,13 +53,7 @@ scoped_refptr GetTraceDataSink( void StopRecording(const base::FilePath& path, const CompletionCallback& callback) { - TracingController::GetInstance()->DisableRecording( - GetTraceDataSink(path, callback)); -} - -void CaptureMonitoringSnapshot(const base::FilePath& path, - const CompletionCallback& callback) { - TracingController::GetInstance()->CaptureMonitoringSnapshot( + TracingController::GetInstance()->StopTracing( GetTraceDataSink(path, callback)); } @@ -70,13 +64,8 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("getCategories", base::Bind( &TracingController::GetCategories, controller)); dict.SetMethod("startRecording", base::Bind( - &TracingController::EnableRecording, controller)); + &TracingController::StartTracing, controller)); dict.SetMethod("stopRecording", &StopRecording); - dict.SetMethod("startMonitoring", base::Bind( - &TracingController::EnableMonitoring, controller)); - dict.SetMethod("stopMonitoring", base::Bind( - &TracingController::DisableMonitoring, controller)); - dict.SetMethod("captureMonitoringSnapshot", &CaptureMonitoringSnapshot); dict.SetMethod("getTraceBufferUsage", base::Bind( &TracingController::GetTraceBufferUsage, controller)); dict.SetMethod("setWatchEvent", base::Bind( diff --git a/atom/browser/api/atom_api_cookies.cc b/atom/browser/api/atom_api_cookies.cc index 6323e5110c1..e49a2ee2f67 100644 --- a/atom/browser/api/atom_api_cookies.cc +++ b/atom/browser/api/atom_api_cookies.cc @@ -180,7 +180,8 @@ void SetCookieOnIO(scoped_refptr getter, GetCookieStore(getter)->GetCookieMonster()->SetCookieWithDetailsAsync( GURL(url), name, value, domain, path, expiration_time, secure, http_only, - false, net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback)); + false, false, false, net::COOKIE_PRIORITY_DEFAULT, + base::Bind(OnSetCookie, callback)); } } // namespace diff --git a/atom/browser/api/atom_api_desktop_capturer.cc b/atom/browser/api/atom_api_desktop_capturer.cc index ceb69deca45..cdae6f0c44c 100644 --- a/atom/browser/api/atom_api_desktop_capturer.cc +++ b/atom/browser/api/atom_api_desktop_capturer.cc @@ -5,7 +5,6 @@ #include "atom/browser/api/atom_api_desktop_capturer.h" #include "atom/common/api/atom_api_native_image.h" -#include "atom/common/node_includes.h" #include "atom/common/native_mate_converters/gfx_converter.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/media/desktop_media_list.h" @@ -14,6 +13,8 @@ #include "third_party/webrtc/modules/desktop_capture/screen_capturer.h" #include "third_party/webrtc/modules/desktop_capture/window_capturer.h" +#include "atom/common/node_includes.h" + namespace mate { template<> @@ -63,8 +64,8 @@ void DesktopCapturer::StartHandling(bool capture_window, capture_screen ? webrtc::ScreenCapturer::Create(options) : nullptr); scoped_ptr window_capturer( capture_window ? webrtc::WindowCapturer::Create(options) : nullptr); - media_list_.reset(new NativeDesktopMediaList(screen_capturer.Pass(), - window_capturer.Pass())); + media_list_.reset(new NativeDesktopMediaList( + std::move(screen_capturer), std::move(window_capturer))); media_list_->SetThumbnailSize(thumbnail_size); media_list_->StartUpdating(this); diff --git a/atom/browser/api/atom_api_download_item.cc b/atom/browser/api/atom_api_download_item.cc index de3a5b348ee..3edd5f9c254 100644 --- a/atom/browser/api/atom_api_download_item.cc +++ b/atom/browser/api/atom_api_download_item.cc @@ -106,11 +106,11 @@ void DownloadItem::Cancel() { download_item_->Remove(); } -int64 DownloadItem::GetReceivedBytes() const { +int64_t DownloadItem::GetReceivedBytes() const { return download_item_->GetReceivedBytes(); } -int64 DownloadItem::GetTotalBytes() const { +int64_t DownloadItem::GetTotalBytes() const { return download_item_->GetTotalBytes(); } diff --git a/atom/browser/api/atom_api_download_item.h b/atom/browser/api/atom_api_download_item.h index 5806c018176..64469b9b34d 100644 --- a/atom/browser/api/atom_api_download_item.h +++ b/atom/browser/api/atom_api_download_item.h @@ -30,8 +30,8 @@ class DownloadItem : public mate::TrackableObject, void Pause(); void Resume(); void Cancel(); - int64 GetReceivedBytes() const; - int64 GetTotalBytes() const; + int64_t GetReceivedBytes() const; + int64_t GetTotalBytes() const; std::string GetMimeType() const; bool HasUserGesture() const; std::string GetFilename() const; diff --git a/atom/browser/api/atom_api_protocol.h b/atom/browser/api/atom_api_protocol.h index 8aef406fbc3..107fbf1ce71 100644 --- a/atom/browser/api/atom_api_protocol.h +++ b/atom/browser/api/atom_api_protocol.h @@ -117,7 +117,7 @@ class Protocol : public mate::Wrappable { scoped_ptr> protocol_handler( new CustomProtocolHandler( isolate(), request_context_getter_, handler)); - if (job_factory_->SetProtocolHandler(scheme, protocol_handler.Pass())) + if (job_factory_->SetProtocolHandler(scheme, std::move(protocol_handler))) return PROTOCOL_OK; else return PROTOCOL_FAIL; @@ -161,7 +161,7 @@ class Protocol : public mate::Wrappable { isolate(), request_context_getter_, handler)); original_protocols_.set( scheme, - job_factory_->ReplaceProtocol(scheme, protocol_handler.Pass())); + job_factory_->ReplaceProtocol(scheme, std::move(protocol_handler))); return PROTOCOL_OK; } diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 1f4c9f92b35..c8b597704cd 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -44,6 +44,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/resource_request_details.h" #include "content/public/browser/service_worker_context.h" @@ -150,7 +151,7 @@ struct Converter { } else { scoped_ptr values(new base::ListValue()); values->AppendString(value); - response_headers.Set(key, values.Pass()); + response_headers.Set(key, std::move(values)); } } } @@ -317,8 +318,9 @@ bool WebContents::AddMessageToConsole(content::WebContents* source, bool WebContents::ShouldCreateWebContents( content::WebContents* web_contents, - int route_id, - int main_frame_route_id, + int32_t route_id, + int32_t main_frame_route_id, + int32_t main_frame_widget_route_id, WindowContainerType window_container_type, const std::string& frame_name, const GURL& target_url, @@ -509,11 +511,11 @@ void WebContents::PluginCrashed(const base::FilePath& plugin_path, Emit("plugin-crashed", info.name, info.version); } -void WebContents::MediaStartedPlaying() { +void WebContents::MediaStartedPlaying(const MediaPlayerId& id) { Emit("media-started-playing"); } -void WebContents::MediaPaused() { +void WebContents::MediaStoppedPlaying(const MediaPlayerId& id) { Emit("media-paused"); } @@ -1070,7 +1072,7 @@ void WebContents::BeginFrameSubscription( if (view) { scoped_ptr frame_subscriber(new FrameSubscriber( isolate(), view, callback)); - view->BeginFrameSubscription(frame_subscriber.Pass()); + view->BeginFrameSubscription(std::move(frame_subscriber)); } } diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index a008a84913b..d98b838fb46 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -168,8 +168,9 @@ class WebContents : public mate::TrackableObject, const base::string16& source_id) override; bool ShouldCreateWebContents( content::WebContents* web_contents, - int route_id, - int main_frame_route_id, + int32_t route_id, + int32_t main_frame_route_id, + int32_t main_frame_widget_route_id, WindowContainerType window_container_type, const std::string& frame_name, const GURL& target_url, @@ -252,8 +253,8 @@ class WebContents : public mate::TrackableObject, const std::vector& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; - void MediaStartedPlaying() override; - void MediaPaused() override; + void MediaStartedPlaying(const MediaPlayerId& id) override; + void MediaStoppedPlaying(const MediaPlayerId& id) override; void DidChangeThemeColor(SkColor theme_color) override; // brightray::InspectableWebContentsViewDelegate: diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index c76d5ffc87d..f81a8bea8b1 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -54,7 +54,7 @@ void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback, return; bitmap.copyPixelsTo( - reinterpret_cast(node::Buffer::Data(buffer.ToLocalChecked())), + reinterpret_cast(node::Buffer::Data(buffer.ToLocalChecked())), rgb_arr_size); callback_.Run(buffer.ToLocalChecked()); diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index 1fe435673db..876be2b1d00 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -230,8 +230,7 @@ content::QuotaPermissionContext* } void AtomBrowserClient::AllowCertificateError( - int render_process_id, - int render_frame_id, + content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, @@ -243,7 +242,7 @@ void AtomBrowserClient::AllowCertificateError( content::CertificateRequestResultType* request) { if (delegate_) { delegate_->AllowCertificateError( - render_process_id, render_frame_id, cert_error, ssl_info, request_url, + web_contents, cert_error, ssl_info, request_url, resource_type, overridable, strict_enforcement, expired_previous_decision, callback, request); } @@ -265,7 +264,7 @@ void AtomBrowserClient::SelectClientCertificate( if (!cert_request_info->client_certs.empty() && delegate_) { delegate_->SelectClientCertificate( - web_contents, cert_request_info, delegate.Pass()); + web_contents, cert_request_info, std::move(delegate)); } } diff --git a/atom/browser/atom_browser_client.h b/atom/browser/atom_browser_client.h index 4af66cc041a..8f62887ff68 100644 --- a/atom/browser/atom_browser_client.h +++ b/atom/browser/atom_browser_client.h @@ -61,8 +61,7 @@ class AtomBrowserClient : public brightray::BrowserClient, void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override; content::QuotaPermissionContext* CreateQuotaPermissionContext() override; void AllowCertificateError( - int render_process_id, - int render_frame_id, + content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index be004c8f6db..2ff9a510db4 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -134,14 +134,15 @@ AtomBrowserContext::CreateURLRequestJobFactory( new net::FtpNetworkLayer(host_resolver)))); // Set up interceptors in the reverse order. - scoped_ptr top_job_factory = job_factory.Pass(); + scoped_ptr top_job_factory = + std::move(job_factory); content::URLRequestInterceptorScopedVector::reverse_iterator it; for (it = interceptors->rbegin(); it != interceptors->rend(); ++it) top_job_factory.reset(new net::URLRequestInterceptingJobFactory( - top_job_factory.Pass(), make_scoped_ptr(*it))); + std::move(top_job_factory), make_scoped_ptr(*it))); interceptors->weak_clear(); - return top_job_factory.Pass(); + return top_job_factory; } net::HttpCache::BackendFactory* diff --git a/atom/browser/atom_permission_manager.cc b/atom/browser/atom_permission_manager.cc index e7fdaaffea7..bd005869aa2 100644 --- a/atom/browser/atom_permission_manager.cc +++ b/atom/browser/atom_permission_manager.cc @@ -80,6 +80,26 @@ int AtomPermissionManager::RequestPermission( return kNoPendingOperation; } +int AtomPermissionManager::RequestPermissions( + const std::vector& permissions, + content::RenderFrameHost* render_frame_host, + const GURL& requesting_origin, + bool user_gesture, + const base::Callback&)>& callback) { + // FIXME(zcbenz): Just ignore multiple permissions request for now. + std::vector permissionStatuses; + for (auto permission : permissions) { + if (permission == content::PermissionType::MIDI_SYSEX) { + content::ChildProcessSecurityPolicy::GetInstance()-> + GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID()); + } + permissionStatuses.push_back(content::PERMISSION_STATUS_GRANTED); + } + callback.Run(permissionStatuses); + return kNoPendingOperation; +} + void AtomPermissionManager::OnPermissionResponse( int request_id, const GURL& origin, diff --git a/atom/browser/atom_permission_manager.h b/atom/browser/atom_permission_manager.h index 4bebbbc84f2..58c23723bfb 100644 --- a/atom/browser/atom_permission_manager.h +++ b/atom/browser/atom_permission_manager.h @@ -38,6 +38,13 @@ class AtomPermissionManager : public content::PermissionManager { const GURL& requesting_origin, bool user_gesture, const ResponseCallback& callback) override; + int RequestPermissions( + const std::vector& permissions, + content::RenderFrameHost* render_frame_host, + const GURL& requesting_origin, + bool user_gesture, + const base::Callback&)>& callback) override; protected: void OnPermissionResponse(int request_id, diff --git a/atom/browser/atom_resource_dispatcher_host_delegate.cc b/atom/browser/atom_resource_dispatcher_host_delegate.cc index 4d969786c19..68576a52f24 100644 --- a/atom/browser/atom_resource_dispatcher_host_delegate.cc +++ b/atom/browser/atom_resource_dispatcher_host_delegate.cc @@ -19,8 +19,8 @@ AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() { bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol( const GURL& url, - int render_process_id, - int render_view_id, + int child_id, + const content::ResourceRequestInfo::WebContentsGetter&, bool is_main_frame, ui::PageTransition transition, bool has_user_gesture) { diff --git a/atom/browser/atom_resource_dispatcher_host_delegate.h b/atom/browser/atom_resource_dispatcher_host_delegate.h index a90b366bc75..408b83c92d9 100644 --- a/atom/browser/atom_resource_dispatcher_host_delegate.h +++ b/atom/browser/atom_resource_dispatcher_host_delegate.h @@ -15,12 +15,13 @@ class AtomResourceDispatcherHostDelegate AtomResourceDispatcherHostDelegate(); // content::ResourceDispatcherHostDelegate: - bool HandleExternalProtocol(const GURL& url, - int render_process_id, - int render_view_id, - bool is_main_frame, - ui::PageTransition transition, - bool has_user_gesture) override; + bool HandleExternalProtocol( + const GURL& url, + int child_id, + const content::ResourceRequestInfo::WebContentsGetter&, + bool is_main_frame, + ui::PageTransition transition, + bool has_user_gesture) override; content::ResourceDispatcherHostLoginDelegate* CreateLoginDelegate( net::AuthChallengeInfo* auth_info, net::URLRequest* request) override; diff --git a/atom/browser/atom_speech_recognition_manager_delegate.h b/atom/browser/atom_speech_recognition_manager_delegate.h index ec31e227baf..4c78e0eead1 100644 --- a/atom/browser/atom_speech_recognition_manager_delegate.h +++ b/atom/browser/atom_speech_recognition_manager_delegate.h @@ -7,6 +7,7 @@ #include +#include "base/macros.h" #include "content/public/browser/speech_recognition_event_listener.h" #include "content/public/browser/speech_recognition_manager_delegate.h" diff --git a/atom/browser/common_web_contents_delegate.cc b/atom/browser/common_web_contents_delegate.cc index 1fd6f782de5..07cc20c7d10 100644 --- a/atom/browser/common_web_contents_delegate.cc +++ b/atom/browser/common_web_contents_delegate.cc @@ -19,6 +19,7 @@ #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" #include "storage/browser/fileapi/isolated_context.h" #if defined(TOOLKIT_VIEWS) @@ -173,8 +174,6 @@ content::WebContents* CommonWebContentsDelegate::OpenURLFromTab( load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; - load_url_params.transferred_global_request_id = - params.transferred_global_request_id; load_url_params.should_clear_history_list = true; source->GetController().LoadURLWithParams(load_url_params); @@ -223,7 +222,7 @@ void CommonWebContentsDelegate::EnterFullscreenModeForTab( return; SetHtmlApiFullscreen(true); owner_window_->NotifyWindowEnterHtmlFullScreen(); - source->GetRenderViewHost()->WasResized(); + source->GetRenderViewHost()->GetWidget()->WasResized(); } void CommonWebContentsDelegate::ExitFullscreenModeForTab( @@ -232,7 +231,7 @@ void CommonWebContentsDelegate::ExitFullscreenModeForTab( return; SetHtmlApiFullscreen(false); owner_window_->NotifyWindowLeaveHtmlFullScreen(); - source->GetRenderViewHost()->WasResized(); + source->GetRenderViewHost()->GetWidget()->WasResized(); } bool CommonWebContentsDelegate::IsFullscreenForTabOrPending( diff --git a/atom/browser/javascript_environment.cc b/atom/browser/javascript_environment.cc index dc27cedee56..970132b47c1 100644 --- a/atom/browser/javascript_environment.cc +++ b/atom/browser/javascript_environment.cc @@ -37,6 +37,7 @@ bool JavascriptEnvironment::Initialize() { v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size()); gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, + gin::IsolateHolder::kStableV8Extras, gin::ArrayBufferAllocator::SharedInstance()); return true; } diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 98b3d725a9a..d66b6ebf3fe 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -27,6 +27,7 @@ #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/content_switches.h" #include "ipc/ipc_message_macros.h" @@ -275,15 +276,15 @@ bool NativeWindow::HasModalDialog() { } void NativeWindow::FocusOnWebView() { - web_contents()->GetRenderViewHost()->Focus(); + web_contents()->GetRenderViewHost()->GetWidget()->Focus(); } void NativeWindow::BlurWebView() { - web_contents()->GetRenderViewHost()->Blur(); + web_contents()->GetRenderViewHost()->GetWidget()->Blur(); } bool NativeWindow::IsWebViewFocused() { - auto host_view = web_contents()->GetRenderViewHost()->GetView(); + auto host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView(); return host_view && host_view->HasFocus(); } @@ -511,7 +512,7 @@ scoped_ptr NativeWindow::DraggableRegionsToSkRegion( region.bounds.bottom(), region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op); } - return sk_region.Pass(); + return sk_region; } void NativeWindow::RenderViewCreated( diff --git a/atom/browser/net/asar/url_request_asar_job.cc b/atom/browser/net/asar/url_request_asar_job.cc index d926d111172..39e55a35cbc 100644 --- a/atom/browser/net/asar/url_request_asar_job.cc +++ b/atom/browser/net/asar/url_request_asar_job.cc @@ -44,6 +44,7 @@ URLRequestAsarJob::URLRequestAsarJob( : net::URLRequestJob(request, network_delegate), type_(TYPE_ERROR), remaining_bytes_(0), + range_parse_result_(net::OK), weak_ptr_factory_(this) {} URLRequestAsarJob::~URLRequestAsarJob() {} @@ -99,7 +100,7 @@ void URLRequestAsarJob::InitializeFileJob( void URLRequestAsarJob::Start() { if (type_ == TYPE_ASAR) { - remaining_bytes_ = static_cast(file_info_.size); + remaining_bytes_ = static_cast(file_info_.size); int flags = base::File::FLAG_OPEN | base::File::FLAG_READ | @@ -131,18 +132,14 @@ void URLRequestAsarJob::Kill() { URLRequestJob::Kill(); } -bool URLRequestAsarJob::ReadRawData(net::IOBuffer* dest, - int dest_size, - int* bytes_read) { +int URLRequestAsarJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (remaining_bytes_ < dest_size) dest_size = static_cast(remaining_bytes_); // If we should copy zero bytes because |remaining_bytes_| is zero, short // circuit here. - if (!dest_size) { - *bytes_read = 0; - return true; - } + if (!dest_size) + return 0; int rv = stream_->Read(dest, dest_size, @@ -150,20 +147,11 @@ bool URLRequestAsarJob::ReadRawData(net::IOBuffer* dest, weak_ptr_factory_.GetWeakPtr(), make_scoped_refptr(dest))); if (rv >= 0) { - // Data is immediately available. - *bytes_read = rv; remaining_bytes_ -= rv; DCHECK_GE(remaining_bytes_, 0); - return true; } - // Otherwise, a read error occured. We may just need to wait... - if (rv == net::ERR_IO_PENDING) { - SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); - } else { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, rv)); - } - return false; + return rv; } bool URLRequestAsarJob::IsRedirectResponse(GURL* location, @@ -214,15 +202,16 @@ void URLRequestAsarJob::SetExtraRequestHeaders( const net::HttpRequestHeaders& headers) { std::string range_header; if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) { - // We only care about "Range" header here. + // This job only cares about the Range header. This method stashes the value + // for later use in DidOpen(), which is responsible for some of the range + // validation as well. NotifyStartError is not legal to call here since + // the job has not started. std::vector ranges; if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) { if (ranges.size() == 1) { byte_range_ = ranges[0]; } else { - NotifyDone(net::URLRequestStatus( - net::URLRequestStatus::FAILED, - net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); + range_parse_result_ = net::ERR_REQUEST_RANGE_NOT_SATISFIABLE; } } } @@ -274,7 +263,14 @@ void URLRequestAsarJob::DidFetchMetaInfo(const FileMetaInfo* meta_info) { void URLRequestAsarJob::DidOpen(int result) { if (result != net::OK) { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result)); + NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, + result)); + return; + } + + if (range_parse_result_ != net::OK) { + NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, + range_parse_result_)); return; } @@ -289,8 +285,9 @@ void URLRequestAsarJob::DidOpen(int result) { } } else { if (!byte_range_.ComputeBounds(meta_info_.file_size)) { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); + NotifyStartError( + net::URLRequestStatus(net::URLRequestStatus::FAILED, + net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } @@ -315,17 +312,19 @@ void URLRequestAsarJob::DidOpen(int result) { } } -void URLRequestAsarJob::DidSeek(int64 result) { +void URLRequestAsarJob::DidSeek(int64_t result) { if (type_ == TYPE_ASAR) { - if (result != static_cast(file_info_.offset)) { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); + if (result != static_cast(file_info_.offset)) { + NotifyStartError( + net::URLRequestStatus(net::URLRequestStatus::FAILED, + net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } } else { if (result != byte_range_.first_byte_position()) { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, - net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); + NotifyStartError( + net::URLRequestStatus(net::URLRequestStatus::FAILED, + net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); return; } } @@ -334,21 +333,14 @@ void URLRequestAsarJob::DidSeek(int64 result) { } void URLRequestAsarJob::DidRead(scoped_refptr buf, int result) { - if (result > 0) { - SetStatus(net::URLRequestStatus()); // Clear the IO_PENDING status + if (result >= 0) { remaining_bytes_ -= result; DCHECK_GE(remaining_bytes_, 0); } buf = NULL; - if (result == 0) { - NotifyDone(net::URLRequestStatus()); - } else if (result < 0) { - NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, result)); - } - - NotifyReadComplete(result); + ReadRawDataComplete(result); } } // namespace asar diff --git a/atom/browser/net/asar/url_request_asar_job.h b/atom/browser/net/asar/url_request_asar_job.h index 29d1afc521d..7103abc4139 100644 --- a/atom/browser/net/asar/url_request_asar_job.h +++ b/atom/browser/net/asar/url_request_asar_job.h @@ -54,9 +54,7 @@ class URLRequestAsarJob : public net::URLRequestJob { // net::URLRequestJob: void Start() override; void Kill() override; - bool ReadRawData(net::IOBuffer* buf, - int buf_size, - int* bytes_read) override; + int ReadRawData(net::IOBuffer* buf, int buf_size) override; bool IsRedirectResponse(GURL* location, int* http_status_code) override; net::Filter* SetupFilter() const override; bool GetMimeType(std::string* mime_type) const override; @@ -72,7 +70,7 @@ class URLRequestAsarJob : public net::URLRequestJob { FileMetaInfo(); // Size of the file. - int64 file_size; + int64_t file_size; // Mime type associated with the file. std::string mime_type; // Result returned from GetMimeTypeFromFile(), i.e. flag showing whether @@ -97,7 +95,7 @@ class URLRequestAsarJob : public net::URLRequestJob { // Callback after seeking to the beginning of |byte_range_| in the file // on a background thread. - void DidSeek(int64 result); + void DidSeek(int64_t result); // Callback after data is asynchronously read from the file into |buf|. void DidRead(scoped_refptr buf, int result); @@ -119,7 +117,9 @@ class URLRequestAsarJob : public net::URLRequestJob { scoped_refptr file_task_runner_; net::HttpByteRange byte_range_; - int64 remaining_bytes_; + int64_t remaining_bytes_; + + net::Error range_parse_result_; base::WeakPtrFactory weak_ptr_factory_; diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index f993138ccc5..91b63fada35 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -78,7 +78,7 @@ void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) { scoped_ptr list(new base::ListValue); GetUploadData(list.get(), request); if (!list->empty()) - details->Set("uploadData", list.Pass()); + details->Set("uploadData", std::move(list)); } void ToDictionary(base::DictionaryValue* details, @@ -87,7 +87,7 @@ void ToDictionary(base::DictionaryValue* details, net::HttpRequestHeaders::Iterator it(headers); while (it.GetNext()) dict->SetString(it.name(), it.value()); - details->Set("requestHeaders", dict.Pass()); + details->Set("requestHeaders", std::move(dict)); } void ToDictionary(base::DictionaryValue* details, @@ -107,10 +107,10 @@ void ToDictionary(base::DictionaryValue* details, } else { scoped_ptr values(new base::ListValue); values->AppendString(value); - dict->Set(key, values.Pass()); + dict->Set(key, std::move(values)); } } - details->Set("responseHeaders", dict.Pass()); + details->Set("responseHeaders", std::move(dict)); details->SetString("statusLine", headers->GetStatusLine()); details->SetInteger("statusCode", headers->response_code()); } diff --git a/atom/browser/net/js_asker.h b/atom/browser/net/js_asker.h index 8ec245ee8c4..061a9cb859e 100644 --- a/atom/browser/net/js_asker.h +++ b/atom/browser/net/js_asker.h @@ -81,7 +81,7 @@ class JsAsker : public RequestJob { void OnResponse(bool success, scoped_ptr value) { int error = net::ERR_NOT_IMPLEMENTED; if (success && value && !internal::IsErrorOptions(value.get(), &error)) { - StartAsync(value.Pass()); + StartAsync(std::move(value)); } else { RequestJob::NotifyStartError( net::URLRequestStatus(net::URLRequestStatus::FAILED, error)); diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index 6f418290175..b176aef378a 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -181,7 +181,7 @@ int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) { pending_buffer_ = nullptr; pending_buffer_size_ = 0; - NotifyReadComplete(bytes_read); + ReadRawDataComplete(bytes_read); return bytes_read; } @@ -190,18 +190,15 @@ void URLRequestFetchJob::Kill() { fetcher_.reset(); } -bool URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, - int dest_size, - int* bytes_read) { +int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { - *bytes_read = 0; request()->set_received_response_content_length(prefilter_bytes_read()); - return true; + return 0; } pending_buffer_ = dest; pending_buffer_size_ = dest_size; SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); - return false; + return dest_size; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { @@ -234,9 +231,10 @@ void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { pending_buffer_ = nullptr; pending_buffer_size_ = 0; - NotifyDone(fetcher_->GetStatus()); if (fetcher_->GetStatus().is_success()) - NotifyReadComplete(0); + ReadRawDataComplete(0); + else + NotifyStartError(fetcher_->GetStatus()); } } // namespace atom diff --git a/atom/browser/net/url_request_fetch_job.h b/atom/browser/net/url_request_fetch_job.h index 399f78ae396..d9a247c5db8 100644 --- a/atom/browser/net/url_request_fetch_job.h +++ b/atom/browser/net/url_request_fetch_job.h @@ -31,9 +31,7 @@ class URLRequestFetchJob : public JsAsker, // net::URLRequestJob: void Kill() override; - bool ReadRawData(net::IOBuffer* buf, - int buf_size, - int* bytes_read) override; + int ReadRawData(net::IOBuffer* buf, int buf_size) override; bool GetMimeType(std::string* mime_type) const override; void GetResponseInfo(net::HttpResponseInfo* info) override; int GetResponseCode() const override; diff --git a/atom/browser/node_debugger.cc b/atom/browser/node_debugger.cc index 2cfcdb222ae..50aa454fe75 100644 --- a/atom/browser/node_debugger.cc +++ b/atom/browser/node_debugger.cc @@ -152,7 +152,7 @@ void NodeDebugger::DidAccept( return; } - accepted_socket_ = socket.Pass(); + accepted_socket_ = std::move(socket); SendConnectMessage(); } diff --git a/atom/browser/ui/accelerator_util_mac.mm b/atom/browser/ui/accelerator_util_mac.mm index 2075b1041f6..be631b02124 100644 --- a/atom/browser/ui/accelerator_util_mac.mm +++ b/atom/browser/ui/accelerator_util_mac.mm @@ -28,7 +28,7 @@ void SetPlatformAccelerator(ui::Accelerator* accelerator) { scoped_ptr platform_accelerator( new ui::PlatformAcceleratorCocoa(characters, modifiers)); - accelerator->set_platform_accelerator(platform_accelerator.Pass()); + accelerator->set_platform_accelerator(std::move(platform_accelerator)); } } // namespace accelerator_util diff --git a/atom/browser/ui/message_box_mac.mm b/atom/browser/ui/message_box_mac.mm index 9380f01e384..d553a6a7dfb 100644 --- a/atom/browser/ui/message_box_mac.mm +++ b/atom/browser/ui/message_box_mac.mm @@ -96,7 +96,7 @@ NSAlert* CreateNSAlert(NativeWindow* parent_window, } if (!icon.isNull()) { - NSImage* image = gfx::SkBitmapToNSImageWithColorSpace( + NSImage* image = skia::SkBitmapToNSImageWithColorSpace( *icon.bitmap(), base::mac::GetGenericRGBColorSpace()); [alert setIcon:image]; } diff --git a/atom/browser/web_view_guest_delegate.cc b/atom/browser/web_view_guest_delegate.cc index 8e1810c4a39..38f0fb1783f 100644 --- a/atom/browser/web_view_guest_delegate.cc +++ b/atom/browser/web_view_guest_delegate.cc @@ -9,6 +9,7 @@ #include "content/public/browser/guest_host.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" namespace atom { @@ -101,13 +102,14 @@ void WebViewGuestDelegate::SetAllowTransparency(bool allow) { auto render_view_host = web_contents()->GetRenderViewHost(); guest_opaque_ = !allow; - if (!render_view_host->GetView()) + if (!render_view_host->GetWidget()->GetView()) return; if (guest_opaque_) { - render_view_host->GetView()->SetBackgroundColorToDefault(); + render_view_host->GetWidget()->GetView()->SetBackgroundColorToDefault(); } else { - render_view_host->GetView()->SetBackgroundColor(SK_ColorTRANSPARENT); + render_view_host->GetWidget()->GetView()->SetBackgroundColor( + SK_ColorTRANSPARENT); } } @@ -123,7 +125,8 @@ void WebViewGuestDelegate::RenderViewReady() { // WebContents::GetRenderWidgetHostView will return the RWHV of an // interstitial page if one is showing at this time. We only want opacity // to apply to web pages. - auto render_view_host_view = web_contents()->GetRenderViewHost()->GetView(); + auto render_view_host_view = + web_contents()->GetRenderViewHost()->GetWidget()->GetView(); if (guest_opaque_) render_view_host_view->SetBackgroundColorToDefault(); else diff --git a/atom/common/api/atom_api_asar.cc b/atom/common/api/atom_api_asar.cc index 7aee71fc329..8f5190fecaa 100644 --- a/atom/common/api/atom_api_asar.cc +++ b/atom/common/api/atom_api_asar.cc @@ -27,12 +27,12 @@ class Archive : public mate::Wrappable { scoped_ptr archive(new asar::Archive(path)); if (!archive->Init()) return v8::False(isolate); - return (new Archive(archive.Pass()))->GetWrapper(isolate); + return (new Archive(std::move(archive)))->GetWrapper(isolate); } protected: explicit Archive(scoped_ptr archive) - : archive_(archive.Pass()) {} + : archive_(std::move(archive)) {} // Reads the offset and size of file. v8::Local GetFileInfo(v8::Isolate* isolate, diff --git a/atom/common/api/atom_bindings.h b/atom/common/api/atom_bindings.h index b3536c23403..9460145d239 100644 --- a/atom/common/api/atom_bindings.h +++ b/atom/common/api/atom_bindings.h @@ -7,6 +7,7 @@ #include +#include "base/macros.h" #include "base/strings/string16.h" #include "v8/include/v8.h" #include "vendor/node/deps/uv/include/uv.h" diff --git a/atom/common/asar/archive.cc b/atom/common/asar/archive.cc index b5a9603acb1..01fe23a8892 100644 --- a/atom/common/asar/archive.cc +++ b/atom/common/asar/archive.cc @@ -158,7 +158,7 @@ bool Archive::Init() { } uint32_t size; - if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUint32_t( + if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUInt32( &size)) { LOG(ERROR) << "Failed to parse header size from " << path_.value(); return false; @@ -296,7 +296,7 @@ bool Archive::CopyFileOut(const base::FilePath& path, base::FilePath* out) { #endif *out = temp_file->path(); - external_files_.set(path, temp_file.Pass()); + external_files_.set(path, std::move(temp_file)); return true; } diff --git a/atom/common/asar/archive.h b/atom/common/asar/archive.h index 6bde7bd1ff2..79b848623c9 100644 --- a/atom/common/asar/archive.h +++ b/atom/common/asar/archive.h @@ -29,7 +29,7 @@ class Archive { bool unpacked; bool executable; uint32_t size; - uint64 offset; + uint64_t offset; }; struct Stats : public FileInfo { diff --git a/atom/common/asar/scoped_temporary_file.cc b/atom/common/asar/scoped_temporary_file.cc index 6dd12782d8e..8578d90d907 100644 --- a/atom/common/asar/scoped_temporary_file.cc +++ b/atom/common/asar/scoped_temporary_file.cc @@ -51,7 +51,7 @@ bool ScopedTemporaryFile::Init(const base::FilePath::StringType& ext) { bool ScopedTemporaryFile::InitFromFile(base::File* src, const base::FilePath::StringType& ext, - uint64 offset, uint64 size) { + uint64_t offset, uint64_t size) { if (!src->IsValid()) return false; diff --git a/atom/common/asar/scoped_temporary_file.h b/atom/common/asar/scoped_temporary_file.h index 23660a23901..5931d9b87af 100644 --- a/atom/common/asar/scoped_temporary_file.h +++ b/atom/common/asar/scoped_temporary_file.h @@ -28,7 +28,7 @@ class ScopedTemporaryFile { // Init an temporary file and fill it with content of |path|. bool InitFromFile(base::File* src, const base::FilePath::StringType& ext, - uint64 offset, uint64 size); + uint64_t offset, uint64_t size); base::FilePath path() const { return path_; } diff --git a/atom/common/crash_reporter/crash_reporter_mac.mm b/atom/common/crash_reporter/crash_reporter_mac.mm index 74ac70125b7..130a421665f 100644 --- a/atom/common/crash_reporter/crash_reporter_mac.mm +++ b/atom/common/crash_reporter/crash_reporter_mac.mm @@ -48,7 +48,8 @@ void CrashReporterMac::InitBreakpad(const std::string& product_name, if (crashpad_client.StartHandler(handler_path, database_path, submit_url, StringMap(), - std::vector())) { + std::vector(), + true)) { crashpad_client.UseHandler(); } } // @autoreleasepool diff --git a/atom/common/native_mate_converters/net_converter.cc b/atom/common/native_mate_converters/net_converter.cc index 184f1c3fecf..5223709ae58 100644 --- a/atom/common/native_mate_converters/net_converter.cc +++ b/atom/common/native_mate_converters/net_converter.cc @@ -34,7 +34,7 @@ v8::Local Converter::ToV8( scoped_ptr list(new base::ListValue); atom::GetUploadData(list.get(), val); if (!list->empty()) - dict->Set("uploadData", list.Pass()); + dict->Set("uploadData", std::move(list)); return mate::ConvertToV8(isolate, *(dict.get())); } @@ -74,7 +74,7 @@ void GetUploadData(base::ListValue* upload_data_list, const net::UploadDataStream* upload_data = request->get_upload(); if (!upload_data) return; - const ScopedVector* readers = + const std::vector>* readers = upload_data->GetElementReaders(); for (const auto& reader : *readers) { scoped_ptr upload_data_dict( @@ -85,14 +85,14 @@ void GetUploadData(base::ListValue* upload_data_list, scoped_ptr bytes( base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(), bytes_reader->length())); - upload_data_dict->Set("bytes", bytes.Pass()); + upload_data_dict->Set("bytes", std::move(bytes)); } else if (reader->AsFileReader()) { const net::UploadFileElementReader* file_reader = reader->AsFileReader(); auto file_path = file_reader->path().AsUTF8Unsafe(); upload_data_dict->SetStringWithoutPathExpansion("file", file_path); } - upload_data_list->Append(upload_data_dict.Pass()); + upload_data_list->Append(std::move(upload_data_dict)); } } diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index b35f1eb6a0b..99873cd1c4f 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -222,8 +222,8 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsBoolean()) return new base::FundamentalValue(val->ToBoolean()->Value()); - if (val->Isint32_t()) - return new base::FundamentalValue(val->Toint32_t()->Value()); + if (val->IsInt32()) + return new base::FundamentalValue(val->ToInt32()->Value()); if (val->IsNumber()) return new base::FundamentalValue(val->ToNumber()->Value()); diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index 608cc94b09a..950a2cd786a 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -85,7 +85,7 @@ scoped_ptr StringVectorToArgArray( for (size_t i = 0; i < vector.size(); ++i) { array[i] = vector[i].c_str(); } - return array.Pass(); + return array; } base::FilePath GetResourcesPath(bool is_browser) { diff --git a/atom/renderer/api/atom_api_spell_check_client.cc b/atom/renderer/api/atom_api_spell_check_client.cc index 51c5f721f02..08f36efce58 100644 --- a/atom/renderer/api/atom_api_spell_check_client.cc +++ b/atom/renderer/api/atom_api_spell_check_client.cc @@ -21,8 +21,6 @@ namespace api { namespace { -const int kMaxAutoCorrectWordSize = 8; - bool HasWordCharacters(const base::string16& text, int index) { const base::char16* data = text.data(); int length = text.length(); @@ -42,8 +40,7 @@ SpellCheckClient::SpellCheckClient(const std::string& language, bool auto_spell_correct_turned_on, v8::Isolate* isolate, v8::Local provider) - : auto_spell_correct_turned_on_(auto_spell_correct_turned_on), - isolate_(isolate), + : isolate_(isolate), provider_(isolate, provider) { character_attributes_.SetDefaultLanguage(language); @@ -96,14 +93,6 @@ void SpellCheckClient::requestCheckingOfText( completionCallback->didFinishCheckingText(results); } -blink::WebString SpellCheckClient::autoCorrectWord( - const blink::WebString& misspelledWord) { - if (auto_spell_correct_turned_on_) - return GetAutoCorrectionWord(base::string16(misspelledWord)); - else - return blink::WebString(); -} - void SpellCheckClient::showSpellingUI(bool show) { } @@ -170,53 +159,6 @@ bool SpellCheckClient::SpellCheckWord(const base::string16& word_to_check) { return true; } -base::string16 SpellCheckClient::GetAutoCorrectionWord( - const base::string16& word) { - base::string16 autocorrect_word; - - int word_length = static_cast(word.size()); - if (word_length < 2 || word_length > kMaxAutoCorrectWordSize) - return autocorrect_word; - - base::char16 misspelled_word[kMaxAutoCorrectWordSize + 1]; - const base::char16* word_char = word.c_str(); - for (int i = 0; i <= kMaxAutoCorrectWordSize; ++i) { - if (i >= word_length) - misspelled_word[i] = 0; - else - misspelled_word[i] = word_char[i]; - } - - // Swap adjacent characters and spellcheck. - int misspelling_start, misspelling_len; - for (int i = 0; i < word_length - 1; i++) { - // Swap. - std::swap(misspelled_word[i], misspelled_word[i + 1]); - - // Check spelling. - misspelling_start = misspelling_len = 0; - spellCheck(blink::WebString(misspelled_word, word_length), - misspelling_start, - misspelling_len, - NULL); - - // Make decision: if only one swap produced a valid word, then we want to - // return it. If we found two or more, we don't do autocorrection. - if (misspelling_len == 0) { - if (autocorrect_word.empty()) { - autocorrect_word.assign(misspelled_word); - } else { - autocorrect_word.clear(); - break; - } - } - - // Restore the swapped characters. - std::swap(misspelled_word[i], misspelled_word[i + 1]); - } - return autocorrect_word; -} - // Returns whether or not the given string is a valid contraction. // This function is a fall-back when the SpellcheckWordIterator class // returns a concatenated word which is not in the selected dictionary diff --git a/atom/renderer/api/atom_api_spell_check_client.h b/atom/renderer/api/atom_api_spell_check_client.h index 345cad186ac..af72756e2ec 100644 --- a/atom/renderer/api/atom_api_spell_check_client.h +++ b/atom/renderer/api/atom_api_spell_check_client.h @@ -41,8 +41,6 @@ class SpellCheckClient : public blink::WebSpellCheckClient { const blink::WebVector& markersInText, const blink::WebVector& markerOffsets, blink::WebTextCheckingCompletion* completionCallback) override; - blink::WebString autoCorrectWord( - const blink::WebString& misspelledWord) override; void showSpellingUI(bool show) override; bool isShowingSpellingUI() override; void updateSpellingUIWithMisspelledWord( diff --git a/chromium_src/chrome/browser/browser_process.h b/chromium_src/chrome/browser/browser_process.h index f971320f821..8baa899f7ad 100644 --- a/chromium_src/chrome/browser/browser_process.h +++ b/chromium_src/chrome/browser/browser_process.h @@ -12,7 +12,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/memory/scoped_ptr.h" namespace printing { diff --git a/chromium_src/chrome/browser/extensions/global_shortcut_listener.h b/chromium_src/chrome/browser/extensions/global_shortcut_listener.h index 1f07df2b6e1..9aec54a3263 100644 --- a/chromium_src/chrome/browser/extensions/global_shortcut_listener.h +++ b/chromium_src/chrome/browser/extensions/global_shortcut_listener.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "ui/events/keycodes/keyboard_codes.h" namespace ui { diff --git a/chromium_src/chrome/browser/media/desktop_media_list.h b/chromium_src/chrome/browser/media/desktop_media_list.h index 7ef703e8b7b..6572e792a12 100644 --- a/chromium_src/chrome/browser/media/desktop_media_list.h +++ b/chromium_src/chrome/browser/media/desktop_media_list.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_MEDIA_DESKTOP_MEDIA_LIST_H_ #define CHROME_BROWSER_MEDIA_DESKTOP_MEDIA_LIST_H_ -#include "base/basictypes.h" #include "base/strings/string16.h" #include "base/time/time.h" #include "content/public/browser/desktop_media_id.h" diff --git a/chromium_src/chrome/browser/media/native_desktop_media_list.cc b/chromium_src/chrome/browser/media/native_desktop_media_list.cc index 4a7fb58962c..3c1848df3ef 100644 --- a/chromium_src/chrome/browser/media/native_desktop_media_list.cc +++ b/chromium_src/chrome/browser/media/native_desktop_media_list.cc @@ -34,7 +34,7 @@ const int kDefaultUpdatePeriod = 1000; // Returns a hash of a DesktopFrame content to detect when image for a desktop // media source has changed. -uint32 GetFrameHash(webrtc::DesktopFrame* frame) { +uint32_t GetFrameHash(webrtc::DesktopFrame* frame) { int data_size = frame->stride() * frame->size().height(); return base::SuperFastHash(reinterpret_cast(frame->data()), data_size); } @@ -117,8 +117,8 @@ NativeDesktopMediaList::Worker::Worker( scoped_ptr screen_capturer, scoped_ptr window_capturer) : media_list_(media_list), - screen_capturer_(screen_capturer.Pass()), - window_capturer_(window_capturer.Pass()) { + screen_capturer_(std::move(screen_capturer)), + window_capturer_(std::move(window_capturer)) { if (screen_capturer_) screen_capturer_->Start(this); if (window_capturer_) @@ -195,14 +195,14 @@ void NativeDesktopMediaList::Worker::Refresh( // |current_frame_| may be NULL if capture failed (e.g. because window has // been closed). if (current_frame_) { - uint32 frame_hash = GetFrameHash(current_frame_.get()); + uint32_t frame_hash = GetFrameHash(current_frame_.get()); new_image_hashes[source.id] = frame_hash; // Scale the image only if it has changed. ImageHashesMap::iterator it = image_hashes_.find(source.id); if (it == image_hashes_.end() || it->second != frame_hash) { gfx::ImageSkia thumbnail = - ScaleDesktopFrame(current_frame_.Pass(), thumbnail_size); + ScaleDesktopFrame(std::move(current_frame_), thumbnail_size); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&NativeDesktopMediaList::OnSourceThumbnail, @@ -231,8 +231,8 @@ void NativeDesktopMediaList::Worker::OnCaptureCompleted( NativeDesktopMediaList::NativeDesktopMediaList( scoped_ptr screen_capturer, scoped_ptr window_capturer) - : screen_capturer_(screen_capturer.Pass()), - window_capturer_(window_capturer.Pass()), + : screen_capturer_(std::move(screen_capturer)), + window_capturer_(std::move(window_capturer)), update_period_(base::TimeDelta::FromMilliseconds(kDefaultUpdatePeriod)), thumbnail_size_(100, 100), view_dialog_id_(-1), @@ -269,7 +269,8 @@ void NativeDesktopMediaList::StartUpdating(DesktopMediaListObserver* observer) { observer_ = observer; worker_.reset(new Worker(weak_factory_.GetWeakPtr(), - screen_capturer_.Pass(), window_capturer_.Pass())); + std::move(screen_capturer_), + std::move(window_capturer_))); Refresh(); } diff --git a/chromium_src/chrome/browser/media/native_desktop_media_list.h b/chromium_src/chrome/browser/media/native_desktop_media_list.h index 943d3dd3256..f789a368be9 100644 --- a/chromium_src/chrome/browser/media/native_desktop_media_list.h +++ b/chromium_src/chrome/browser/media/native_desktop_media_list.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_MEDIA_NATIVE_DESKTOP_MEDIA_LIST_H_ #define CHROME_BROWSER_MEDIA_NATIVE_DESKTOP_MEDIA_LIST_H_ -#include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" diff --git a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc index 9064cd961bd..2231ed8b0dc 100644 --- a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc +++ b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc @@ -256,7 +256,7 @@ void LazyEmf::Close() const { bool LazyEmf::LoadEmf(Emf* emf) const { file_->Seek(base::File::FROM_BEGIN, 0); - int64 size = file_->GetLength(); + int64_t size = file_->GetLength(); if (size <= 0) return false; std::vector data(size); diff --git a/chromium_src/chrome/browser/printing/print_job.cc b/chromium_src/chrome/browser/printing/print_job.cc index 65449ef121e..60dcebe0803 100644 --- a/chromium_src/chrome/browser/printing/print_job.cc +++ b/chromium_src/chrome/browser/printing/print_job.cc @@ -441,7 +441,7 @@ void PrintJob::HoldUntilStopIsCalled() { } void PrintJob::Quit() { - base::MessageLoop::current()->Quit(); + base::MessageLoop::current()->QuitWhenIdle(); } // Takes settings_ ownership and will be deleted in the receiving thread. diff --git a/chromium_src/chrome/browser/printing/print_job.h b/chromium_src/chrome/browser/printing/print_job.h index 48daaa6cb97..4963a94f14f 100644 --- a/chromium_src/chrome/browser/printing/print_job.h +++ b/chromium_src/chrome/browser/printing/print_job.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_PRINTING_PRINT_JOB_H_ #define CHROME_BROWSER_PRINTING_PRINT_JOB_H_ -#include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" diff --git a/chromium_src/chrome/browser/printing/print_preview_message_handler.cc b/chromium_src/chrome/browser/printing/print_preview_message_handler.cc index 613f3f2343c..a195ad4c6ad 100644 --- a/chromium_src/chrome/browser/printing/print_preview_message_handler.cc +++ b/chromium_src/chrome/browser/printing/print_preview_message_handler.cc @@ -118,7 +118,7 @@ void PrintPreviewMessageHandler::PrintToPDF( } void PrintPreviewMessageHandler::RunPrintToPDFCallback( - int request_id, uint32 data_size, char* data) { + int request_id, uint32_t data_size, char* data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); v8::Isolate* isolate = v8::Isolate::GetCurrent(); diff --git a/chromium_src/chrome/browser/printing/print_preview_message_handler.h b/chromium_src/chrome/browser/printing/print_preview_message_handler.h index 453d78761bb..1aac74baa22 100644 --- a/chromium_src/chrome/browser/printing/print_preview_message_handler.h +++ b/chromium_src/chrome/browser/printing/print_preview_message_handler.h @@ -47,7 +47,7 @@ class PrintPreviewMessageHandler const PrintHostMsg_DidPreviewDocument_Params& params); void OnPrintPreviewFailed(int document_cookie, int request_id); - void RunPrintToPDFCallback(int request_id, uint32 data_size, char* data); + void RunPrintToPDFCallback(int request_id, uint32_t data_size, char* data); PrintToPDFCallbackMap print_to_pdf_callback_map_; diff --git a/chromium_src/chrome/browser/printing/print_view_manager_base.cc b/chromium_src/chrome/browser/printing/print_view_manager_base.cc index ede1d3b8ba8..688256e4251 100644 --- a/chromium_src/chrome/browser/printing/print_view_manager_base.cc +++ b/chromium_src/chrome/browser/printing/print_view_manager_base.cc @@ -144,7 +144,7 @@ void PrintViewManagerBase::OnDidPrintPage( #if !defined(OS_WIN) // Update the rendered document. It will send notifications to the listener. document->SetPage(params.page_number, - metafile.Pass(), + std::move(metafile), params.page_size, params.content_area); @@ -305,7 +305,7 @@ void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() { inside_inner_message_loop_) { // We are in a message loop created by RenderAllMissingPagesNow. Quit from // it. - base::MessageLoop::current()->Quit(); + base::MessageLoop::current()->QuitWhenIdle(); inside_inner_message_loop_ = false; } } @@ -411,9 +411,9 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { // memory-bound. static const int kPrinterSettingsTimeout = 60000; base::OneShotTimer quit_timer; - quit_timer.Start(FROM_HERE, - TimeDelta::FromMilliseconds(kPrinterSettingsTimeout), - base::MessageLoop::current(), &base::MessageLoop::Quit); + quit_timer.Start( + FROM_HERE, TimeDelta::FromMilliseconds(kPrinterSettingsTimeout), + base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle); inside_inner_message_loop_ = true; diff --git a/chromium_src/chrome/browser/printing/printing_message_filter.cc b/chromium_src/chrome/browser/printing/printing_message_filter.cc index 6fd536ef68c..eac4405fbcf 100644 --- a/chromium_src/chrome/browser/printing/printing_message_filter.cc +++ b/chromium_src/chrome/browser/printing/printing_message_filter.cc @@ -394,7 +394,7 @@ void PrintingMessageFilter::OnUpdatePrintSettings( printer_query = queue_->CreatePrinterQuery(host_id, routing_id); } printer_query->SetSettings( - new_settings.Pass(), + std::move(new_settings), base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this, printer_query, reply_msg)); } diff --git a/chromium_src/chrome/browser/printing/printing_message_filter.h b/chromium_src/chrome/browser/printing/printing_message_filter.h index 624b28fd35d..e8536a69c5a 100644 --- a/chromium_src/chrome/browser/printing/printing_message_filter.h +++ b/chromium_src/chrome/browser/printing/printing_message_filter.h @@ -107,7 +107,7 @@ class PrintingMessageFilter : public content::BrowserMessageFilter { #if defined(ENABLE_FULL_PRINTING) // Check to see if print preview has been cancelled. - void OnCheckForCancel(int32 preview_ui_id, + void OnCheckForCancel(int32_t preview_ui_id, int preview_request_id, bool* cancel); #endif diff --git a/chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.h b/chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.h index 66d51e7fba2..de969f5cdb5 100644 --- a/chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.h +++ b/chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_PRINTING_PRINTING_UI_WEB_CONTENTS_OBSERVER_H_ #define CHROME_BROWSER_PRINTING_PRINTING_UI_WEB_CONTENTS_OBSERVER_H_ -#include "base/basictypes.h" #include "content/public/browser/web_contents_observer.h" #include "ui/gfx/native_widget_types.h" diff --git a/chromium_src/chrome/browser/process_singleton.h b/chromium_src/chrome/browser/process_singleton.h index 3eeb53393e1..eab6c35479a 100644 --- a/chromium_src/chrome/browser/process_singleton.h +++ b/chromium_src/chrome/browser/process_singleton.h @@ -12,7 +12,6 @@ #include #include -#include "base/basictypes.h" #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_path.h" diff --git a/chromium_src/chrome/browser/process_singleton_posix.cc b/chromium_src/chrome/browser/process_singleton_posix.cc index 98fb948730e..7e54d9b5d37 100644 --- a/chromium_src/chrome/browser/process_singleton_posix.cc +++ b/chromium_src/chrome/browser/process_singleton_posix.cc @@ -54,7 +54,6 @@ #include "atom/common/atom_command_line.h" #include "base/base_paths.h" -#include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" @@ -75,6 +74,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "base/thread_task_runner_handle.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "base/timer/timer.h" @@ -222,7 +222,7 @@ int SetupSocketOnly() { int sock = socket(PF_UNIX, SOCK_STREAM, 0); PCHECK(sock >= 0) << "socket() failed"; - int rv = net::SetNonBlocking(sock); + int rv = base::SetNonBlocking(sock); DCHECK_EQ(0, rv) << "Failed to make non-blocking socket."; rv = SetCloseOnExec(sock); DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket."; @@ -577,7 +577,7 @@ void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) { PLOG(ERROR) << "accept() failed"; return; } - int rv = net::SetNonBlocking(connection_socket); + int rv = base::SetNonBlocking(connection_socket); DCHECK_EQ(0, rv) << "Failed to make non-blocking socket."; SocketReader* reader = new SocketReader(this, ui_message_loop_, @@ -990,8 +990,8 @@ bool ProcessSingleton::Create() { // In Electron the ProcessSingleton is created earlier than the IO // thread gets created, so we have to postpone the call until message // loop is up an running. - scoped_refptr task_runner( - base::ThreadTaskRunnerHandle::Get()); + scoped_refptr task_runner = + base::ThreadTaskRunnerHandle::Get(); task_runner->PostTask( FROM_HERE, base::Bind(&ProcessSingleton::StartListening, diff --git a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h index 6fb4aced181..40a03a1ff56 100644 --- a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h +++ b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_BROWSER_HOST_H_ #define CHROME_BROWSER_RENDERER_HOST_PEPPER_PEPPER_FLASH_BROWSER_HOST_H_ -#include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "ppapi/host/host_message_context.h" diff --git a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc index fdc054f59fb..9ddb9fa56d7 100644 --- a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc +++ b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.cc @@ -240,8 +240,8 @@ int32_t PepperFlashClipboardMessageFilter::OnMsgReadData( base::string16 html; std::string url; - uint32 fragment_start; - uint32 fragment_end; + uint32_t fragment_start; + uint32_t fragment_end; clipboard->ReadHTML(type, &html, &url, &fragment_start, &fragment_end); result = PP_OK; clipboard_string = base::UTF16ToUTF8( diff --git a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h index ff07eb73750..4c146dd5daa 100644 --- a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h +++ b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_clipboard_message_filter.h @@ -8,8 +8,6 @@ #include #include -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "ppapi/host/resource_message_filter.h" #include "ppapi/shared_impl/flash_clipboard_format_registry.h" diff --git a/chromium_src/chrome/browser/ui/cocoa/color_chooser_mac.mm b/chromium_src/chrome/browser/ui/cocoa/color_chooser_mac.mm index cb366022d6e..6183dd5d5bd 100644 --- a/chromium_src/chrome/browser/ui/cocoa/color_chooser_mac.mm +++ b/chromium_src/chrome/browser/ui/cocoa/color_chooser_mac.mm @@ -74,7 +74,7 @@ ColorChooserMac::ColorChooserMac(content::WebContents* web_contents, SkColor initial_color) : web_contents_(web_contents) { panel_.reset([[ColorPanelCocoa alloc] initWithChooser:this]); - [panel_ setColor:gfx::SkColorToDeviceNSColor(initial_color)]; + [panel_ setColor:skia::SkColorToDeviceNSColor(initial_color)]; [[NSColorPanel sharedColorPanel] makeKeyAndOrderFront:nil]; } @@ -101,7 +101,7 @@ void ColorChooserMac::End() { } void ColorChooserMac::SetSelectedColor(SkColor color) { - [panel_ setColor:gfx::SkColorToDeviceNSColor(color)]; + [panel_ setColor:skia::SkColorToDeviceNSColor(color)]; } @implementation ColorPanelCocoa @@ -139,7 +139,7 @@ void ColorChooserMac::SetSelectedColor(SkColor color) { nonUserChange_ = NO; return; } - chooser_->DidChooseColorInColorPanel(gfx::NSDeviceColorToSkColor( + chooser_->DidChooseColorInColorPanel(skia::NSDeviceColorToSkColor( [[panel color] colorUsingColorSpaceName:NSDeviceRGBColorSpace])); nonUserChange_ = NO; } diff --git a/chromium_src/chrome/browser/ui/views/color_chooser_aura.h b/chromium_src/chrome/browser/ui/views/color_chooser_aura.h index 6394b973a3d..ba6709889e6 100644 --- a/chromium_src/chrome/browser/ui/views/color_chooser_aura.h +++ b/chromium_src/chrome/browser/ui/views/color_chooser_aura.h @@ -5,8 +5,6 @@ #ifndef CHROME_BROWSER_UI_VIEWS_COLOR_CHOOSER_AURA_H_ #define CHROME_BROWSER_UI_VIEWS_COLOR_CHOOSER_AURA_H_ -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "content/public/browser/color_chooser.h" #include "ui/views/color_chooser/color_chooser_listener.h" diff --git a/chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h b/chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h index 694f776b24e..95a08b229f4 100644 --- a/chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h +++ b/chromium_src/chrome/browser/ui/views/frame/global_menu_bar_registrar_x11.h @@ -9,7 +9,6 @@ #include -#include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "ui/base/glib/glib_signal.h" diff --git a/chromium_src/chrome/common/print_messages.cc b/chromium_src/chrome/common/print_messages.cc index 5f8e30f3698..b0ec282382d 100644 --- a/chromium_src/chrome/common/print_messages.cc +++ b/chromium_src/chrome/common/print_messages.cc @@ -4,7 +4,6 @@ #include "chrome/common/print_messages.h" -#include "base/basictypes.h" #include "base/strings/string16.h" #include "ui/gfx/geometry/size.h" diff --git a/chromium_src/chrome/common/print_messages.h b/chromium_src/chrome/common/print_messages.h index cd775d0478b..034691b5b95 100644 --- a/chromium_src/chrome/common/print_messages.h +++ b/chromium_src/chrome/common/print_messages.h @@ -161,7 +161,7 @@ IPC_STRUCT_BEGIN(PrintHostMsg_DidPrintPage_Params) IPC_STRUCT_MEMBER(base::SharedMemoryHandle, metafile_data_handle) // Size of the metafile data. - IPC_STRUCT_MEMBER(uint32, data_size) + IPC_STRUCT_MEMBER(uint32_t, data_size) // Cookie for the document to ensure correctness. IPC_STRUCT_MEMBER(int, document_cookie) @@ -193,7 +193,7 @@ IPC_STRUCT_BEGIN(PrintHostMsg_DidPreviewDocument_Params) IPC_STRUCT_MEMBER(base::SharedMemoryHandle, metafile_data_handle) // Size of metafile data. - IPC_STRUCT_MEMBER(uint32, data_size) + IPC_STRUCT_MEMBER(uint32_t, data_size) // Cookie for the document to ensure correctness. IPC_STRUCT_MEMBER(int, document_cookie) diff --git a/chromium_src/chrome/common/tts_utterance_request.h b/chromium_src/chrome/common/tts_utterance_request.h index e0b7adfa4a0..a4b4cab68ca 100644 --- a/chromium_src/chrome/common/tts_utterance_request.h +++ b/chromium_src/chrome/common/tts_utterance_request.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/strings/string16.h" struct TtsUtteranceRequest { @@ -41,4 +41,4 @@ struct TtsUtteranceResponse { int id; }; -#endif // CHROME_COMMON_TTS_UTTERANCE_REQUEST_H_ \ No newline at end of file +#endif // CHROME_COMMON_TTS_UTTERANCE_REQUEST_H_ diff --git a/chromium_src/chrome/common/widevine_cdm_constants.cc b/chromium_src/chrome/common/widevine_cdm_constants.cc index 60f487e2ae8..587966a9c36 100644 --- a/chromium_src/chrome/common/widevine_cdm_constants.cc +++ b/chromium_src/chrome/common/widevine_cdm_constants.cc @@ -12,5 +12,5 @@ const base::FilePath::CharType kWidevineCdmBaseDirectory[] = const char kWidevineCdmPluginExtension[] = ""; -const int32 kWidevineCdmPluginPermissions = ppapi::PERMISSION_DEV | - ppapi::PERMISSION_PRIVATE; +const int32_t kWidevineCdmPluginPermissions = ppapi::PERMISSION_DEV | + ppapi::PERMISSION_PRIVATE; diff --git a/chromium_src/chrome/common/widevine_cdm_constants.h b/chromium_src/chrome/common/widevine_cdm_constants.h index b626079a11b..9597b1cb41f 100644 --- a/chromium_src/chrome/common/widevine_cdm_constants.h +++ b/chromium_src/chrome/common/widevine_cdm_constants.h @@ -5,7 +5,7 @@ #ifndef CHROME_COMMON_WIDEVINE_CDM_CONSTANTS_H_ #define CHROME_COMMON_WIDEVINE_CDM_CONSTANTS_H_ -#include "base/basictypes.h" +#include "base/macros.h" #include "base/files/file_path.h" // The Widevine CDM adapter and Widevine CDM are in this directory. @@ -14,6 +14,6 @@ extern const base::FilePath::CharType kWidevineCdmBaseDirectory[]; extern const char kWidevineCdmPluginExtension[]; // Permission bits for Widevine CDM plugin. -extern const int32 kWidevineCdmPluginPermissions; +extern const int32_t kWidevineCdmPluginPermissions; #endif // CHROME_COMMON_WIDEVINE_CDM_CONSTANTS_H_ diff --git a/chromium_src/chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h b/chromium_src/chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h index 13ab2853a35..dd12e9d9160 100644 --- a/chromium_src/chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h +++ b/chromium_src/chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h @@ -5,8 +5,6 @@ #ifndef CHROME_RENDERER_PEPPER_CHROME_RENDERER_PEPPER_HOST_FACTORY_H_ #define CHROME_RENDERER_PEPPER_CHROME_RENDERER_PEPPER_HOST_FACTORY_H_ -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "ppapi/host/host_factory.h" namespace content { diff --git a/chromium_src/chrome/renderer/pepper/pepper_flash_font_file_host.h b/chromium_src/chrome/renderer/pepper/pepper_flash_font_file_host.h index 02bb30f315f..eeaa7209b5f 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_flash_font_file_host.h +++ b/chromium_src/chrome/renderer/pepper/pepper_flash_font_file_host.h @@ -5,8 +5,6 @@ #ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ #define CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "ppapi/c/private/pp_private_font_charset.h" #include "ppapi/host/resource_host.h" diff --git a/chromium_src/chrome/renderer/pepper/pepper_flash_fullscreen_host.h b/chromium_src/chrome/renderer/pepper/pepper_flash_fullscreen_host.h index 3550ea13663..86d0af73aee 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_flash_fullscreen_host.h +++ b/chromium_src/chrome/renderer/pepper/pepper_flash_fullscreen_host.h @@ -5,8 +5,6 @@ #ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_FULLSCREEN_HOST_H_ #define CHROME_RENDERER_PEPPER_PEPPER_FLASH_FULLSCREEN_HOST_H_ -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "ppapi/host/resource_host.h" namespace content { diff --git a/chromium_src/chrome/renderer/pepper/pepper_flash_renderer_host.h b/chromium_src/chrome/renderer/pepper/pepper_flash_renderer_host.h index de22f46045a..f37907a8655 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_flash_renderer_host.h +++ b/chromium_src/chrome/renderer/pepper/pepper_flash_renderer_host.h @@ -8,7 +8,6 @@ #include #include -#include "base/basictypes.h" #include "base/memory/weak_ptr.h" #include "ppapi/host/host_message_context.h" #include "ppapi/host/resource_host.h" diff --git a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc index 3ef6dff0c8b..6fbadd12116 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc +++ b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc @@ -43,9 +43,8 @@ void PepperSharedMemoryMessageFilter::OnHostMsgCreateSharedMemory( ppapi::proxy::SerializedHandle* plugin_handle) { plugin_handle->set_null_shmem(); *host_handle_id = -1; - scoped_ptr shm(content::RenderThread::Get() - ->HostAllocateSharedMemoryBuffer(size) - .Pass()); + scoped_ptr shm( + content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(size)); if (!shm.get()) return; diff --git a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.h b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.h index d7e0934cd6e..860e1c9dbd1 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.h +++ b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.h @@ -5,8 +5,6 @@ #ifndef CHROME_RENDERER_PEPPER_PEPPER_SHARED_MEMORY_MESSAGE_FILTER_H_ #define CHROME_RENDERER_PEPPER_PEPPER_SHARED_MEMORY_MESSAGE_FILTER_H_ -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "ppapi/c/pp_instance.h" #include "ppapi/host/instance_message_filter.h" diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper.cc index 3bfe719a0c9..924553b5cff 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper.cc @@ -415,22 +415,19 @@ class PrepareFrameAndViewForPrint : public blink::WebViewClient, return owns_web_view_ && frame() && frame()->isLoading(); } - // TODO(ojan): Remove this override and have this class use a non-null - // layerTreeView. - // blink::WebViewClient override: - virtual bool allowsBrokenNullLayerTreeView() const; - protected: // blink::WebViewClient override: - virtual void didStopLoading(); + void didStopLoading() override; + bool allowsBrokenNullLayerTreeView() const override; - // blink::WebFrameClient override: - virtual blink::WebFrame* createChildFrame( + // blink::WebFrameClient: + blink::WebFrame* createChildFrame( blink::WebLocalFrame* parent, blink::WebTreeScopeType scope, const blink::WebString& name, - blink::WebSandboxFlags sandboxFlags); - virtual void frameDetached(blink::WebFrame* frame, DetachType type); + blink::WebSandboxFlags sandboxFlags, + const blink::WebFrameOwnerProperties& frameOwnerProperties) override; + void frameDetached(blink::WebFrame* frame, DetachType type) override; private: void CallOnReady(); @@ -576,7 +573,8 @@ blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame( blink::WebLocalFrame* parent, blink::WebTreeScopeType scope, const blink::WebString& name, - blink::WebSandboxFlags sandboxFlags) { + blink::WebSandboxFlags sandboxFlags, + const blink::WebFrameOwnerProperties& frameOwnerProperties) { blink::WebFrame* frame = blink::WebLocalFrame::create(scope, this); parent->appendChild(frame); return frame; @@ -814,7 +812,7 @@ bool PrintWebViewHelper::FinalizePrintReadyDocument() { // Get the size of the resulting metafile. PdfMetafileSkia* metafile = print_preview_context_.metafile(); - uint32 buf_size = metafile->GetDataSize(); + uint32_t buf_size = metafile->GetDataSize(); DCHECK_GT(buf_size, 0u); PrintHostMsg_DidPreviewDocument_Params preview_params; @@ -1164,7 +1162,7 @@ bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame, bool PrintWebViewHelper::CopyMetafileDataToSharedMem( PdfMetafileSkia* metafile, base::SharedMemoryHandle* shared_mem_handle) { - uint32 buf_size = metafile->GetDataSize(); + uint32_t buf_size = metafile->GetDataSize(); scoped_ptr shared_buf( content::RenderThread::Get()->HostAllocateSharedMemoryBuffer( buf_size).release()); diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc index 82d7779d026..62267f8f45f 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc @@ -92,7 +92,7 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, metafile.FinishDocument(); // Get the size of the resulting metafile. - uint32 buf_size = metafile.GetDataSize(); + uint32_t buf_size = metafile.GetDataSize(); DCHECK_GT(buf_size, 0u); #if defined(OS_CHROMEOS) || defined(OS_ANDROID) diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm b/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm index 0785e30a9cf..3b1a0593d06 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm @@ -116,15 +116,13 @@ void PrintWebViewHelper::RenderPage(const PrintMsg_Print_Params& params, gfx::Rect canvas_area = content_area; { - skia::PlatformCanvas* canvas = metafile->GetVectorCanvasForNewPage( + SkCanvas* canvas = metafile->GetVectorCanvasForNewPage( *page_size, canvas_area, scale_factor); if (!canvas) return; MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas, metafile); - skia::SetIsDraftMode(*canvas, is_print_ready_metafile_sent_); skia::SetIsPreviewMetafile(*canvas, is_preview); - RenderPageContent(frame, page_number, canvas_area, content_area, scale_factor, static_cast(canvas)); } diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc index 0b21de46995..243e9ab7522 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc @@ -96,7 +96,7 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, metafile.FinishDocument(); // Get the size of the resulting metafile. - uint32 buf_size = metafile.GetDataSize(); + uint32_t buf_size = metafile.GetDataSize(); DCHECK_GT(buf_size, 0u); PrintHostMsg_DidPrintPage_Params printed_page_params; @@ -218,7 +218,7 @@ void PrintWebViewHelper::PrintPageInternal( bool PrintWebViewHelper::CopyMetafileDataToSharedMem( PdfMetafileSkia* metafile, base::SharedMemoryHandle* shared_mem_handle) { - uint32 buf_size = metafile->GetDataSize(); + uint32_t buf_size = metafile->GetDataSize(); base::SharedMemory shared_buf; // Allocate a shared memory buffer to hold the generated metafile data. if (!shared_buf.CreateAndMapAnonymous(buf_size)) { diff --git a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.cc b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.cc index 815a9c08b34..a3b51a8c46e 100644 --- a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.cc +++ b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.cc @@ -9,7 +9,6 @@ #include #include -#include "base/basictypes.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/strings/stringprintf.h" @@ -332,7 +331,7 @@ bool SpellcheckWordIterator::Initialize( NOTREACHED() << "failed to open iterator (broken rules)"; return false; } - iterator_ = iterator.Pass(); + iterator_ = std::move(iterator); // Set the character attributes so we can normalize the words extracted by // this iterator. diff --git a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h index 2ac28a2e240..03fd8e666f5 100644 --- a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h +++ b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h @@ -11,7 +11,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "third_party/icu/source/common/unicode/uscript.h" diff --git a/chromium_src/chrome/renderer/tts_dispatcher.cc b/chromium_src/chrome/renderer/tts_dispatcher.cc index 91b67ba1674..0d3b97c8454 100644 --- a/chromium_src/chrome/renderer/tts_dispatcher.cc +++ b/chromium_src/chrome/renderer/tts_dispatcher.cc @@ -4,7 +4,6 @@ #include "chrome/renderer/tts_dispatcher.h" -#include "base/basictypes.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/tts_messages.h" #include "chrome/common/tts_utterance_request.h" @@ -197,4 +196,4 @@ void TtsDispatcher::OnSpeakingErrorOccurred(int utterance_id, // The web speech API doesn't support an error message. synthesizer_client_->speakingErrorOccurred(utterance); utterance_id_map_.erase(utterance_id); -} \ No newline at end of file +} diff --git a/chromium_src/chrome/renderer/tts_dispatcher.h b/chromium_src/chrome/renderer/tts_dispatcher.h index fd18acba206..0a770d72183 100644 --- a/chromium_src/chrome/renderer/tts_dispatcher.h +++ b/chromium_src/chrome/renderer/tts_dispatcher.h @@ -7,8 +7,6 @@ #include -#include "base/basictypes.h" -#include "base/compiler_specific.h" #include "base/containers/hash_tables.h" #include "content/public/renderer/render_process_observer.h" #include "third_party/WebKit/public/platform/WebSpeechSynthesizer.h" @@ -75,4 +73,4 @@ class TtsDispatcher DISALLOW_COPY_AND_ASSIGN(TtsDispatcher); }; -#endif // CHROME_RENDERER_TTS_DISPATCHER_H_ \ No newline at end of file +#endif // CHROME_RENDERER_TTS_DISPATCHER_H_ diff --git a/chromium_src/chrome/utility/printing_handler_win.cc b/chromium_src/chrome/utility/printing_handler_win.cc index ec908d19fc5..805cd6e343c 100644 --- a/chromium_src/chrome/utility/printing_handler_win.cc +++ b/chromium_src/chrome/utility/printing_handler_win.cc @@ -177,7 +177,7 @@ int PrintingHandlerWin::LoadPDF(base::File pdf_file) { if (!g_pdf_lib.Get().IsValid()) return 0; - int64 length64 = pdf_file.GetLength(); + int64_t length64 = pdf_file.GetLength(); if (length64 <= 0 || length64 > std::numeric_limits::max()) return 0; int length = static_cast(length64); diff --git a/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc b/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc index 897b23bbd56..6495b23b840 100644 --- a/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc +++ b/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc @@ -17,6 +17,7 @@ #include "net/base/net_errors.h" #endif +#include "base/files/file_util.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" @@ -27,6 +28,7 @@ #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" +#include "net/base/sockaddr_storage.h" #include "net/socket/socket_descriptor.h" using std::string; @@ -125,7 +127,7 @@ SocketDescriptor StreamListenSocket::AcceptSocket() { if (conn == kInvalidSocket) LOG(ERROR) << "Error accepting connection."; else - SetNonBlocking(conn); + base::SetNonBlocking(conn); return conn; } diff --git a/chromium_src/net/test/embedded_test_server/stream_listen_socket.h b/chromium_src/net/test/embedded_test_server/stream_listen_socket.h index 02a8b9827a2..9df51258306 100644 --- a/chromium_src/net/test/embedded_test_server/stream_listen_socket.h +++ b/chromium_src/net/test/embedded_test_server/stream_listen_socket.h @@ -28,7 +28,7 @@ #include "base/message_loop/message_loop.h" #endif -#include "base/basictypes.h" +#include "base/macros.h" #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" diff --git a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc index 418f3459212..fbdcc2bfc7e 100644 --- a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc +++ b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc @@ -34,14 +34,14 @@ namespace test_server { // static scoped_ptr TCPListenSocket::CreateAndListen( const string& ip, - uint16 port, + uint16_t port, StreamListenSocket::Delegate* del) { SocketDescriptor s = CreateAndBind(ip, port); if (s == kInvalidSocket) return scoped_ptr(); scoped_ptr sock(new TCPListenSocket(s, del)); sock->Listen(); - return sock.Pass(); + return sock; } TCPListenSocket::TCPListenSocket(SocketDescriptor s, @@ -52,7 +52,8 @@ TCPListenSocket::TCPListenSocket(SocketDescriptor s, TCPListenSocket::~TCPListenSocket() { } -SocketDescriptor TCPListenSocket::CreateAndBind(const string& ip, uint16 port) { +SocketDescriptor TCPListenSocket::CreateAndBind(const string& ip, + uint16_t port) { SocketDescriptor s = CreatePlatformSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s != kInvalidSocket) { #if defined(OS_POSIX) @@ -79,7 +80,7 @@ SocketDescriptor TCPListenSocket::CreateAndBind(const string& ip, uint16 port) { } SocketDescriptor TCPListenSocket::CreateAndBindAnyPort(const string& ip, - uint16* port) { + uint16_t* port) { SocketDescriptor s = CreateAndBind(ip, 0); if (s == kInvalidSocket) return kInvalidSocket; @@ -110,7 +111,7 @@ void TCPListenSocket::Accept() { #if defined(OS_POSIX) sock->WatchSocket(WAITING_READ); #endif - socket_delegate_->DidAccept(this, sock.Pass()); + socket_delegate_->DidAccept(this, std::move(sock)); } } // namespace test_server diff --git a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.h b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.h index 12b3fa40745..6990845f392 100644 --- a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.h +++ b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.h @@ -7,7 +7,7 @@ #include -#include "base/basictypes.h" +#include "base/macros.h" #include "net/base/net_export.h" #include "net/socket/socket_descriptor.h" #include "net/test/embedded_test_server/stream_listen_socket.h" @@ -25,7 +25,7 @@ class TCPListenSocket : public StreamListenSocket { // accept local connections. static scoped_ptr CreateAndListen( const std::string& ip, - uint16 port, + uint16_t port, StreamListenSocket::Delegate* del); protected: @@ -39,11 +39,11 @@ class TCPListenSocket : public StreamListenSocket { friend class TCPListenSocketTester; // Get raw TCP socket descriptor bound to ip:port. - static SocketDescriptor CreateAndBind(const std::string& ip, uint16 port); + static SocketDescriptor CreateAndBind(const std::string& ip, uint16_t port); // Get raw TCP socket descriptor bound to ip and return port it is bound to. static SocketDescriptor CreateAndBindAnyPort(const std::string& ip, - uint16* port); + uint16_t* port); DISALLOW_COPY_AND_ASSIGN(TCPListenSocket); }; diff --git a/vendor/brightray b/vendor/brightray index 2a29ea6c1de..70f475e34dd 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 2a29ea6c1de3accd01f1883ac94326220349bbe1 +Subproject commit 70f475e34dd5f580dc8d5184d6fa8e5c96c5f601 From f29d633563276b4bc3458d6a215d41c76f6855b4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 23:32:59 +0900 Subject: [PATCH 0115/1265] Fix cpplint warnings --- atom/browser/atom_permission_manager.cc | 2 ++ atom/browser/atom_permission_manager.h | 1 + 2 files changed, 3 insertions(+) diff --git a/atom/browser/atom_permission_manager.cc b/atom/browser/atom_permission_manager.cc index bd005869aa2..720d1f93b32 100644 --- a/atom/browser/atom_permission_manager.cc +++ b/atom/browser/atom_permission_manager.cc @@ -4,6 +4,8 @@ #include "atom/browser/atom_permission_manager.h" +#include + #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/permission_type.h" #include "content/public/browser/render_frame_host.h" diff --git a/atom/browser/atom_permission_manager.h b/atom/browser/atom_permission_manager.h index 58c23723bfb..e16893fd8bb 100644 --- a/atom/browser/atom_permission_manager.h +++ b/atom/browser/atom_permission_manager.h @@ -6,6 +6,7 @@ #define ATOM_BROWSER_ATOM_PERMISSION_MANAGER_H_ #include +#include #include "base/callback.h" #include "content/public/browser/permission_manager.h" From a31cbd24a1426aef466d760897c1fe31839eb47f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 8 Mar 2016 23:35:52 +0900 Subject: [PATCH 0116/1265] Final pieces of int16 and .Pass() --- atom/browser/net/atom_ssl_config_service.cc | 6 +++--- atom/browser/ui/views/submenu_button.cc | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/atom/browser/net/atom_ssl_config_service.cc b/atom/browser/net/atom_ssl_config_service.cc index 2b3143e93cb..79b10d0ca98 100644 --- a/atom/browser/net/atom_ssl_config_service.cc +++ b/atom/browser/net/atom_ssl_config_service.cc @@ -18,8 +18,8 @@ namespace atom { namespace { -uint16 GetSSLProtocolVersion(const std::string& version_string) { - uint16 version = 0; // Invalid +uint16_t GetSSLProtocolVersion(const std::string& version_string) { + uint16_t version = 0; // Invalid if (version_string == "tls1") version = net::SSL_PROTOCOL_VERSION_TLS1; else if (version_string == "tls1.1") @@ -35,7 +35,7 @@ std::vector ParseCipherSuites( cipher_suites.reserve(cipher_strings.size()); for (auto& cipher_string : cipher_strings) { - uint16 cipher_suite = 0; + uint16_t cipher_suite = 0; if (!net::ParseSSLCipherString(cipher_string, &cipher_suite)) { LOG(ERROR) << "Ignoring unrecognised cipher suite : " << cipher_string; diff --git a/atom/browser/ui/views/submenu_button.cc b/atom/browser/ui/views/submenu_button.cc index 7f413d519c2..72cab258cbe 100644 --- a/atom/browser/ui/views/submenu_button.cc +++ b/atom/browser/ui/views/submenu_button.cc @@ -37,7 +37,7 @@ SubmenuButton::SubmenuButton(views::ButtonListener* listener, underline_color_(SK_ColorBLACK) { #if defined(OS_LINUX) // Dont' use native style border. - SetBorder(CreateDefaultBorder().Pass()); + SetBorder(std::move(CreateDefaultBorder())); #endif if (GetUnderlinePosition(title, &accelerator_, &underline_start_, From dd4d3db47bea9b72e20c13f451972573de9e2634 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 9 Mar 2016 12:40:06 +0900 Subject: [PATCH 0117/1265] Fix node integration not working --- atom/browser/atom_browser_client.cc | 3 +-- atom/browser/net/atom_ssl_config_service.cc | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index 876be2b1d00..2363e6442bf 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -49,7 +49,7 @@ namespace { // The default routing id of WebContents. // In Electron each RenderProcessHost only has one WebContents, so this ID is // same for every WebContents. -int kDefaultRoutingID = 2; +int kDefaultRoutingID = 1; // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; @@ -201,7 +201,6 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( if (ContainsKey(pending_processes_, process_id)) process_id = pending_processes_[process_id]; - // Certain render process will be created with no associated render view, // for example: ServiceWorker. auto rvh = content::RenderViewHost::FromID(process_id, kDefaultRoutingID); diff --git a/atom/browser/net/atom_ssl_config_service.cc b/atom/browser/net/atom_ssl_config_service.cc index 79b10d0ca98..c306a8a3917 100644 --- a/atom/browser/net/atom_ssl_config_service.cc +++ b/atom/browser/net/atom_ssl_config_service.cc @@ -29,9 +29,9 @@ uint16_t GetSSLProtocolVersion(const std::string& version_string) { return version; } -std::vector ParseCipherSuites( +std::vector ParseCipherSuites( const std::vector& cipher_strings) { - std::vector cipher_suites; + std::vector cipher_suites; cipher_suites.reserve(cipher_strings.size()); for (auto& cipher_string : cipher_strings) { From 6de9c4332fdf85a1e7645b996be0c9534fcf0f4c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 9 Mar 2016 20:03:42 +0900 Subject: [PATCH 0118/1265] Fix passing Promise with remote Somehow using value.then.bind(value) would result in infinite loop, could be bug of Chromium. --- atom/browser/auto_updater.h | 1 + lib/browser/rpc-server.js | 2 +- lib/renderer/api/remote.js | 2 +- vendor/brightray | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/atom/browser/auto_updater.h b/atom/browser/auto_updater.h index 637545e877f..d13c6f0c330 100644 --- a/atom/browser/auto_updater.h +++ b/atom/browser/auto_updater.h @@ -8,6 +8,7 @@ #include #include "base/macros.h" +#include "build/build_config.h" namespace base { class Time; diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index 5399c192e82..e26843667bd 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -106,7 +106,7 @@ var valueToMeta = function(sender, value, optimizeSimpleObject) { } else if (meta.type === 'buffer') { meta.value = Array.prototype.slice.call(value, 0); } else if (meta.type === 'promise') { - meta.then = valueToMeta(sender, value.then.bind(value)); + meta.then = valueToMeta(sender, function(v) { value.then(v); }); } else if (meta.type === 'error') { meta.members = plainObjectToMeta(value); diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 42435d8304c..d3d490d053c 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -48,7 +48,7 @@ var wrapArgs = function(args, visited) { } else if ((value != null ? value.constructor.name : void 0) === 'Promise') { return { type: 'promise', - then: valueToMeta(value.then.bind(value)) + then: valueToMeta(function(v) { value.then(v); }) }; } else if ((value != null) && typeof value === 'object' && v8Util.getHiddenValue(value, 'atomId')) { return { diff --git a/vendor/brightray b/vendor/brightray index 70f475e34dd..7f9e25b50b3 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 70f475e34dd5f580dc8d5184d6fa8e5c96c5f601 +Subproject commit 7f9e25b50b373aea5e7d0a50c33aea22c85ee876 From bfc6d77bb3d35ed1a89ac7831bd39de9a6d4dad5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 9 Mar 2016 21:34:51 +0900 Subject: [PATCH 0119/1265] Pending renderer process no longer has render view attached --- atom/browser/atom_browser_client.cc | 7 +------ atom/browser/web_contents_preferences.cc | 25 +++++++++++++++++++++++- atom/browser/web_contents_preferences.h | 8 ++++++++ 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index 2363e6442bf..ca12723bb37 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -203,13 +203,8 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( // Certain render process will be created with no associated render view, // for example: ServiceWorker. - auto rvh = content::RenderViewHost::FromID(process_id, kDefaultRoutingID); - if (!rvh) - return; - - // Get the WebContents of the render process. content::WebContents* web_contents = - content::WebContents::FromRenderViewHost(rvh); + WebContentsPreferences::GetWebContentsFromProcessID(process_id); if (!web_contents) return; diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index fb67d2516eb..3939c59b8cd 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -4,12 +4,15 @@ #include "atom/browser/web_contents_preferences.h" +#include #include +#include #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" +#include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/common/web_preferences.h" #include "native_mate/dictionary.h" @@ -23,9 +26,13 @@ DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsPreferences); namespace atom { +// static +std::vector WebContentsPreferences::instances_; + WebContentsPreferences::WebContentsPreferences( content::WebContents* web_contents, - const mate::Dictionary& web_preferences) { + const mate::Dictionary& web_preferences) + : web_contents_(web_contents) { v8::Isolate* isolate = web_preferences.isolate(); mate::Dictionary copied(isolate, web_preferences.GetHandle()->Clone()); // Following fields should not be stored. @@ -35,15 +42,31 @@ WebContentsPreferences::WebContentsPreferences( mate::ConvertFromV8(isolate, copied.GetHandle(), &web_preferences_); web_contents->SetUserData(UserDataKey(), this); + + instances_.push_back(this); } WebContentsPreferences::~WebContentsPreferences() { + instances_.erase( + std::remove(instances_.begin(), instances_.end(), this), + instances_.end()); } void WebContentsPreferences::Merge(const base::DictionaryValue& extend) { web_preferences_.MergeDictionary(&extend); } +// static +content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID( + int process_id) { + for (WebContentsPreferences* preferences : instances_) { + content::WebContents* web_contents = preferences->web_contents_; + if (web_contents->GetRenderProcessHost()->GetID() == process_id) + return web_contents; + } + return nullptr; +} + // static void WebContentsPreferences::AppendExtraCommandLineSwitches( content::WebContents* web_contents, base::CommandLine* command_line) { diff --git a/atom/browser/web_contents_preferences.h b/atom/browser/web_contents_preferences.h index 8b04f9ee24e..dd98a9658ac 100644 --- a/atom/browser/web_contents_preferences.h +++ b/atom/browser/web_contents_preferences.h @@ -5,6 +5,8 @@ #ifndef ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_ #define ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_ +#include + #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" @@ -26,6 +28,9 @@ namespace atom { class WebContentsPreferences : public content::WebContentsUserData { public: + // Get WebContents according to process ID. + static content::WebContents* GetWebContentsFromProcessID(int process_id); + // Append command paramters according to |web_contents|'s preferences. static void AppendExtraCommandLineSwitches( content::WebContents* web_contents, base::CommandLine* command_line); @@ -47,6 +52,9 @@ class WebContentsPreferences private: friend class content::WebContentsUserData; + static std::vector instances_; + + content::WebContents* web_contents_; base::DictionaryValue web_preferences_; DISALLOW_COPY_AND_ASSIGN(WebContentsPreferences); From 044daee086e77f1cd6bc13814e202b2945948efc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 9 Mar 2016 22:19:47 +0900 Subject: [PATCH 0120/1265] Update printing code to latest --- .../printing/print_web_view_helper.cc | 53 +++++++++-------- .../renderer/printing/print_web_view_helper.h | 2 +- .../printing/print_web_view_helper_linux.cc | 49 ++------------- .../printing/print_web_view_helper_mac.mm | 3 +- .../printing/print_web_view_helper_pdf_win.cc | 59 ++++++------------- 5 files changed, 55 insertions(+), 111 deletions(-) diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper.cc index 924553b5cff..eb3599198d9 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper.cc @@ -386,7 +386,7 @@ class PrepareFrameAndViewForPrint : public blink::WebViewClient, blink::WebLocalFrame* frame, const blink::WebNode& node, bool ignore_css_margins); - virtual ~PrepareFrameAndViewForPrint(); + ~PrepareFrameAndViewForPrint() override; // Optional. Replaces |frame_| with selection if needed. Will call |on_ready| // when completed. @@ -810,13 +810,19 @@ bool PrintWebViewHelper::FinalizePrintReadyDocument() { DCHECK(!is_print_ready_metafile_sent_); print_preview_context_.FinalizePrintReadyDocument(); - // Get the size of the resulting metafile. PdfMetafileSkia* metafile = print_preview_context_.metafile(); - uint32_t buf_size = metafile->GetDataSize(); - DCHECK_GT(buf_size, 0u); PrintHostMsg_DidPreviewDocument_Params preview_params; - preview_params.data_size = buf_size; + + // Ask the browser to create the shared memory for us. + if (!CopyMetafileDataToSharedMem(*metafile, + &(preview_params.metafile_data_handle))) { + LOG(ERROR) << "CopyMetafileDataToSharedMem failed"; + print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED); + return false; + } + + preview_params.data_size = metafile->GetDataSize(); preview_params.document_cookie = print_pages_params_->params.document_cookie; preview_params.expected_pages_count = print_preview_context_.total_page_count(); @@ -824,13 +830,6 @@ bool PrintWebViewHelper::FinalizePrintReadyDocument() { preview_params.preview_request_id = print_pages_params_->params.preview_request_id; - // Ask the browser to create the shared memory for us. - if (!CopyMetafileDataToSharedMem(metafile, - &(preview_params.metafile_data_handle))) { - LOG(ERROR) << "CopyMetafileDataToSharedMem failed"; - print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED); - return false; - } is_print_ready_metafile_sent_ = true; Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params)); @@ -1160,21 +1159,25 @@ bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame, #if defined(OS_POSIX) bool PrintWebViewHelper::CopyMetafileDataToSharedMem( - PdfMetafileSkia* metafile, + const PdfMetafileSkia& metafile, base::SharedMemoryHandle* shared_mem_handle) { - uint32_t buf_size = metafile->GetDataSize(); - scoped_ptr shared_buf( - content::RenderThread::Get()->HostAllocateSharedMemoryBuffer( - buf_size).release()); + uint32_t buf_size = metafile.GetDataSize(); + if (buf_size == 0) + return false; - if (shared_buf) { - if (shared_buf->Map(buf_size)) { - metafile->GetData(shared_buf->memory(), buf_size); - return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(), - shared_mem_handle); - } - } - return false; + scoped_ptr shared_buf( + content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(buf_size)); + if (!shared_buf) + return false; + + if (!shared_buf->Map(buf_size)) + return false; + + if (!metafile.GetData(shared_buf->memory(), buf_size)) + return false; + + return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(), + shared_mem_handle); } #endif // defined(OS_POSIX) diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper.h b/chromium_src/chrome/renderer/printing/print_web_view_helper.h index bfe9cb612d1..05f145b5bb8 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper.h +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper.h @@ -218,7 +218,7 @@ class PrintWebViewHelper // Helper methods ----------------------------------------------------------- - bool CopyMetafileDataToSharedMem(PdfMetafileSkia* metafile, + bool CopyMetafileDataToSharedMem(const PdfMetafileSkia& metafile, base::SharedMemoryHandle* shared_mem_handle); // Helper method to get page layout in points and fit to page if needed. diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc index 62267f8f45f..d37aec628ba 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc @@ -11,7 +11,6 @@ #include "printing/metafile_skia_wrapper.h" #include "printing/page_size_margins.h" #include "printing/pdf_metafile_skia.h" -#include "skia/ext/platform_device.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) @@ -91,49 +90,15 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, metafile.FinishDocument(); - // Get the size of the resulting metafile. - uint32_t buf_size = metafile.GetDataSize(); - DCHECK_GT(buf_size, 0u); - -#if defined(OS_CHROMEOS) || defined(OS_ANDROID) - int sequence_number = -1; - base::FileDescriptor fd; - - // Ask the browser to open a file for us. - Send(new PrintHostMsg_AllocateTempFileForPrinting(routing_id(), - &fd, - &sequence_number)); - if (!metafile.SaveToFD(fd)) - return false; - - // Tell the browser we've finished writing the file. - Send(new PrintHostMsg_TempFileForPrintingWritten(routing_id(), - sequence_number)); - return true; -#else PrintHostMsg_DidPrintPage_Params printed_page_params; - printed_page_params.data_size = 0; - printed_page_params.document_cookie = params.params.document_cookie; - - { - scoped_ptr shared_mem( - content::RenderThread::Get()->HostAllocateSharedMemoryBuffer( - buf_size).release()); - if (!shared_mem.get()) { - NOTREACHED() << "AllocateSharedMemoryBuffer failed"; - return false; - } - - if (!shared_mem->Map(buf_size)) { - NOTREACHED() << "Map failed"; - return false; - } - metafile.GetData(shared_mem->memory(), buf_size); - printed_page_params.data_size = buf_size; - shared_mem->GiveToProcess(base::GetCurrentProcessHandle(), - &(printed_page_params.metafile_data_handle)); + if (!CopyMetafileDataToSharedMem( + metafile, &printed_page_params.metafile_data_handle)) { + return false; } + printed_page_params.data_size = metafile.GetDataSize(); + printed_page_params.document_cookie = params.params.document_cookie; + for (size_t i = 0; i < printed_pages.size(); ++i) { printed_page_params.page_number = printed_pages[i]; Send(new PrintHostMsg_DidPrintPage(routing_id(), printed_page_params)); @@ -141,7 +106,6 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, printed_page_params.metafile_data_handle.fd = -1; } return true; -#endif // defined(OS_CHROMEOS) } void PrintWebViewHelper::PrintPageInternal( @@ -165,7 +129,6 @@ void PrintWebViewHelper::PrintPageInternal( return; MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas, metafile); - skia::SetIsDraftMode(*canvas, is_print_ready_metafile_sent_); RenderPageContent(frame, params.page_number, canvas_area, content_area, scale_factor, canvas); diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm b/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm index 3b1a0593d06..b10ba616a1f 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_mac.mm @@ -42,8 +42,9 @@ void PrintWebViewHelper::PrintPageInternal( page_params.content_area = content_area_in_dpi; // Ask the browser to create the shared memory for us. - if (!CopyMetafileDataToSharedMem(&metafile, + if (!CopyMetafileDataToSharedMem(metafile, &(page_params.metafile_data_handle))) { + // TODO(thestig): Fail and return false instead. page_params.data_size = 0; } diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc index 243e9ab7522..a5896934b69 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc @@ -95,40 +95,16 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, metafile.FinishDocument(); - // Get the size of the resulting metafile. - uint32_t buf_size = metafile.GetDataSize(); - DCHECK_GT(buf_size, 0u); - PrintHostMsg_DidPrintPage_Params printed_page_params; - printed_page_params.data_size = 0; + if (!CopyMetafileDataToSharedMem( + metafile, &printed_page_params.metafile_data_handle)) { + return false; + } + + printed_page_params.content_area = params.params.printable_area; + printed_page_params.data_size = metafile.GetDataSize(); printed_page_params.document_cookie = params.params.document_cookie; printed_page_params.page_size = params.params.page_size; - printed_page_params.content_area = params.params.printable_area; - - { - base::SharedMemory shared_buf; - // Allocate a shared memory buffer to hold the generated metafile data. - if (!shared_buf.CreateAndMapAnonymous(buf_size)) { - NOTREACHED() << "Buffer allocation failed"; - return false; - } - - // Copy the bits into shared memory. - if (!metafile.GetData(shared_buf.memory(), buf_size)) { - NOTREACHED() << "GetData() failed"; - shared_buf.Unmap(); - return false; - } - shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), - &printed_page_params.metafile_data_handle); - shared_buf.Unmap(); - - printed_page_params.data_size = buf_size; - Send(new PrintHostMsg_DuplicateSection( - routing_id(), - printed_page_params.metafile_data_handle, - &printed_page_params.metafile_data_handle)); - } for (size_t i = 0; i < printed_pages.size(); ++i) { printed_page_params.page_number = printed_pages[i]; @@ -216,24 +192,25 @@ void PrintWebViewHelper::PrintPageInternal( } bool PrintWebViewHelper::CopyMetafileDataToSharedMem( - PdfMetafileSkia* metafile, + const PdfMetafileSkia& metafile, base::SharedMemoryHandle* shared_mem_handle) { - uint32_t buf_size = metafile->GetDataSize(); + uint32_t buf_size = metafile.GetDataSize(); + if (buf_size == 0) + return false; + base::SharedMemory shared_buf; // Allocate a shared memory buffer to hold the generated metafile data. - if (!shared_buf.CreateAndMapAnonymous(buf_size)) { - NOTREACHED() << "Buffer allocation failed"; + if (!shared_buf.CreateAndMapAnonymous(buf_size)) return false; - } // Copy the bits into shared memory. - if (!metafile->GetData(shared_buf.memory(), buf_size)) { - NOTREACHED() << "GetData() failed"; - shared_buf.Unmap(); + if (!metafile.GetData(shared_buf.memory(), buf_size)) + return false; + + if (!shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), + shared_mem_handle)) { return false; } - shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), shared_mem_handle); - shared_buf.Unmap(); Send(new PrintHostMsg_DuplicateSection(routing_id(), *shared_mem_handle, shared_mem_handle)); From d36b8bca86fa34d1589700cc2af02c99d012cc51 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 9 Mar 2016 22:19:56 +0900 Subject: [PATCH 0121/1265] Fix compilation errors on Linux --- atom/common/atom_command_line.h | 1 + atom/common/crash_reporter/linux/crash_dump_handler.h | 4 ++++ chromium_src/chrome/browser/ui/views/color_chooser_aura.h | 1 + 3 files changed, 6 insertions(+) diff --git a/atom/common/atom_command_line.h b/atom/common/atom_command_line.h index 56ecb8fbd49..b5915533a41 100644 --- a/atom/common/atom_command_line.h +++ b/atom/common/atom_command_line.h @@ -9,6 +9,7 @@ #include #include "base/macros.h" +#include "build/build_config.h" namespace atom { diff --git a/atom/common/crash_reporter/linux/crash_dump_handler.h b/atom/common/crash_reporter/linux/crash_dump_handler.h index 00161f02ee5..f10c5212254 100644 --- a/atom/common/crash_reporter/linux/crash_dump_handler.h +++ b/atom/common/crash_reporter/linux/crash_dump_handler.h @@ -6,6 +6,10 @@ #ifndef ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_ #define ATOM_COMMON_CRASH_REPORTER_LINUX_CRASH_DUMP_HANDLER_H_ +#include +#include +#include + #include "base/macros.h" #include "vendor/breakpad/src/common/simple_string_dictionary.h" diff --git a/chromium_src/chrome/browser/ui/views/color_chooser_aura.h b/chromium_src/chrome/browser/ui/views/color_chooser_aura.h index ba6709889e6..355f540b19d 100644 --- a/chromium_src/chrome/browser/ui/views/color_chooser_aura.h +++ b/chromium_src/chrome/browser/ui/views/color_chooser_aura.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_COLOR_CHOOSER_AURA_H_ #define CHROME_BROWSER_UI_VIEWS_COLOR_CHOOSER_AURA_H_ +#include "base/macros.h" #include "content/public/browser/color_chooser.h" #include "ui/views/color_chooser/color_chooser_listener.h" From a737baafbfb38ba9109e73c3b403be19e9193f8b Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:01:53 -0800 Subject: [PATCH 0122/1265] We don't need Metro --- chromium_src/chrome/browser/process_singleton_win.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/chromium_src/chrome/browser/process_singleton_win.cc b/chromium_src/chrome/browser/process_singleton_win.cc index 14e53bec5fa..fd4c22e7405 100644 --- a/chromium_src/chrome/browser/process_singleton_win.cc +++ b/chromium_src/chrome/browser/process_singleton_win.cc @@ -16,7 +16,6 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" -#include "base/win/metro.h" #include "base/win/registry.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" From 60a2495b300c7bfd051ba15291322a48134645fd Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:05:17 -0800 Subject: [PATCH 0123/1265] Update Get() => get(), Set() => reset() --- atom/browser/ui/win/notify_icon.cc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/atom/browser/ui/win/notify_icon.cc b/atom/browser/ui/win/notify_icon.cc index 1ac29f1360c..7c8e1a189a6 100644 --- a/atom/browser/ui/win/notify_icon.cc +++ b/atom/browser/ui/win/notify_icon.cc @@ -80,7 +80,7 @@ void NotifyIcon::ResetIcon() { InitIconData(&icon_data); icon_data.uFlags |= NIF_MESSAGE; icon_data.uCallbackMessage = message_id_; - icon_data.hIcon = icon_.Get(); + icon_data.hIcon = icon_.get(); // If we have an image, then set the NIF_ICON flag, which tells // Shell_NotifyIcon() to set the image for the status icon it creates. if (icon_data.hIcon) @@ -96,8 +96,8 @@ void NotifyIcon::SetImage(const gfx::Image& image) { NOTIFYICONDATA icon_data; InitIconData(&icon_data); icon_data.uFlags |= NIF_ICON; - icon_.Set(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap())); - icon_data.hIcon = icon_.Get(); + icon_.reset(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap())); + icon_data.hIcon = icon_.get(); BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data); if (!result) LOG(WARNING) << "Error setting status tray icon image"; @@ -132,8 +132,8 @@ void NotifyIcon::DisplayBalloon(const gfx::Image& icon, base::win::Version win_version = base::win::GetVersion(); if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) { - balloon_icon_.Set(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap())); - icon_data.hBalloonIcon = balloon_icon_.Get(); + balloon_icon_.reset(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap())); + icon_data.hBalloonIcon = balloon_icon_.get(); icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON; } From 12e9b7ab884ff4e423c0ba9fd057b175daf18915 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:08:19 -0800 Subject: [PATCH 0124/1265] Use assignment operator since both sides are scoped now --- atom/browser/ui/win/notify_icon.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/browser/ui/win/notify_icon.cc b/atom/browser/ui/win/notify_icon.cc index 7c8e1a189a6..11247301380 100644 --- a/atom/browser/ui/win/notify_icon.cc +++ b/atom/browser/ui/win/notify_icon.cc @@ -96,7 +96,7 @@ void NotifyIcon::SetImage(const gfx::Image& image) { NOTIFYICONDATA icon_data; InitIconData(&icon_data); icon_data.uFlags |= NIF_ICON; - icon_.reset(IconUtil::CreateHICONFromSkBitmap(image.AsBitmap())); + icon_ = IconUtil::CreateHICONFromSkBitmap(image.AsBitmap()); icon_data.hIcon = icon_.get(); BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data); if (!result) @@ -132,7 +132,7 @@ void NotifyIcon::DisplayBalloon(const gfx::Image& icon, base::win::Version win_version = base::win::GetVersion(); if (!icon.IsEmpty() && win_version != base::win::VERSION_PRE_XP) { - balloon_icon_.reset(IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap())); + balloon_icon_ = IconUtil::CreateHICONFromSkBitmap(icon.AsBitmap()); icon_data.hBalloonIcon = balloon_icon_.get(); icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON; } From e835111195d50e5bd861a01d954127c1388bd839 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:16:12 -0800 Subject: [PATCH 0125/1265] More type fixups --- chromium_src/chrome/browser/speech/tts_win.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chromium_src/chrome/browser/speech/tts_win.cc b/chromium_src/chrome/browser/speech/tts_win.cc index ac258205889..bc9411a8c15 100644 --- a/chromium_src/chrome/browser/speech/tts_win.cc +++ b/chromium_src/chrome/browser/speech/tts_win.cc @@ -87,7 +87,7 @@ bool TtsPlatformImplWin::Speak( // 0.1 -> -10 // 1.0 -> 0 // 10.0 -> 10 - speech_synthesizer_->SetRate(static_cast(10 * log10(params.rate))); + speech_synthesizer_->SetRate(static_cast(10 * log10(params.rate))); } if (params.pitch >= 0.0) { @@ -102,7 +102,7 @@ bool TtsPlatformImplWin::Speak( if (params.volume >= 0.0) { // The TTS api allows a range of 0 to 100 for speech volume. - speech_synthesizer_->SetVolume(static_cast(params.volume * 100)); + speech_synthesizer_->SetVolume(static_cast(params.volume * 100)); } // TODO(dmazzoni): convert SSML to SAPI xml. http://crbug.com/88072 From 7b60ef6261b8e2d5712257633aae9ffaf1233cf6 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:16:31 -0800 Subject: [PATCH 0126/1265] SetIsDraftMode no longer a thing, see https://groups.google.com/a/chromium.org/forum/m/#!topic/chromium-checkins/6qohfKmEYyg --- .../chrome/renderer/printing/print_web_view_helper_pdf_win.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc index a5896934b69..ce1e962505f 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc @@ -164,7 +164,6 @@ void PrintWebViewHelper::PrintPageInternal( return; MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas, metafile); - skia::SetIsDraftMode(*canvas, is_print_ready_metafile_sent_); #if 0 if (params.params.display_header_footer) { From 1c01e4955f1a854f339be2b67e71bd53654e8ef9 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:22:54 -0800 Subject: [PATCH 0127/1265] Modifiers moved under UI --- atom/browser/ui/win/notify_icon_host.cc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/atom/browser/ui/win/notify_icon_host.cc b/atom/browser/ui/win/notify_icon_host.cc index a0d4287ff61..1f0b35b09fd 100644 --- a/atom/browser/ui/win/notify_icon_host.cc +++ b/atom/browser/ui/win/notify_icon_host.cc @@ -15,6 +15,7 @@ #include "base/win/win_util.h" #include "base/win/wrapped_window_proc.h" #include "ui/events/event_constants.h" +#include "ui/events/win/system_event_state_lookup.h" #include "ui/gfx/win/hwnd_util.h" namespace atom { @@ -35,11 +36,11 @@ bool IsWinPressed() { int GetKeyboardModifers() { int modifiers = ui::EF_NONE; - if (base::win::IsShiftPressed()) + if (ui::win::IsShiftPressed()) modifiers |= ui::EF_SHIFT_DOWN; - if (base::win::IsCtrlPressed()) + if (ui::win::IsCtrlPressed()) modifiers |= ui::EF_CONTROL_DOWN; - if (base::win::IsAltPressed()) + if (ui::win::IsAltPressed()) modifiers |= ui::EF_ALT_DOWN; if (IsWinPressed()) modifiers |= ui::EF_COMMAND_DOWN; From f4ec369873d9d22313361964c828bda41e3b32ac Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 11:27:16 -0800 Subject: [PATCH 0128/1265] More boring fixups --- atom/browser/ui/message_box_win.cc | 4 ++-- atom/browser/ui/win/taskbar_host.cc | 4 ++-- atom/common/api/atom_api_native_image.cc | 4 ++-- atom/common/crash_reporter/win/crash_service.cc | 2 +- chromium_src/chrome/common/chrome_paths_win.cc | 1 - 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/atom/browser/ui/message_box_win.cc b/atom/browser/ui/message_box_win.cc index 2847ae21a16..5f49151c30f 100644 --- a/atom/browser/ui/message_box_win.cc +++ b/atom/browser/ui/message_box_win.cc @@ -102,9 +102,9 @@ int ShowMessageBoxUTF16(HWND parent, base::win::ScopedHICON hicon; if (!icon.isNull()) { - hicon.Set(IconUtil::CreateHICONFromSkBitmap(*icon.bitmap())); + hicon = IconUtil::CreateHICONFromSkBitmap(*icon.bitmap()); config.dwFlags |= TDF_USE_HICON_MAIN; - config.hMainIcon = hicon.Get(); + config.hMainIcon = hicon.get(); } else { // Show icon according to dialog's type. switch (type) { diff --git a/atom/browser/ui/win/taskbar_host.cc b/atom/browser/ui/win/taskbar_host.cc index 0d250829110..abfda15edf7 100644 --- a/atom/browser/ui/win/taskbar_host.cc +++ b/atom/browser/ui/win/taskbar_host.cc @@ -91,7 +91,7 @@ bool TaskbarHost::SetThumbarButtons( if (!button.icon.IsEmpty()) { thumb_button.dwMask |= THB_ICON; icons[i] = IconUtil::CreateHICONFromSkBitmap(button.icon.AsBitmap()); - thumb_button.hIcon = icons[i].Get(); + thumb_button.hIcon = icons[i].get(); } // Set tooltip. @@ -139,7 +139,7 @@ bool TaskbarHost::SetOverlayIcon( base::win::ScopedHICON icon( IconUtil::CreateHICONFromSkBitmap(overlay.AsBitmap())); return SUCCEEDED( - taskbar_->SetOverlayIcon(window, icon, base::UTF8ToUTF16(text).c_str())); + taskbar_->SetOverlayIcon(window, icon.get(), base::UTF8ToUTF16(text).c_str())); } bool TaskbarHost::HandleThumbarButtonEvent(int button_id) { diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 3d000b6d5d9..69ead046458 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -158,11 +158,11 @@ bool ReadImageSkiaFromICO(gfx::ImageSkia* image, const base::FilePath& path) { base::win::ScopedHICON icon(static_cast( LoadImage(NULL, image_path.value().c_str(), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_LOADFROMFILE))); - if (!icon) + if (!icon.get()) return false; // Convert the icon from the Windows specific HICON to gfx::ImageSkia. - scoped_ptr bitmap(IconUtil::CreateSkBitmapFromHICON(icon)); + scoped_ptr bitmap(IconUtil:: CreateSkBitmapFromHICON(icon.get())); image->AddRepresentation(gfx::ImageSkiaRep(*bitmap, 1.0f)); return true; } diff --git a/atom/common/crash_reporter/win/crash_service.cc b/atom/common/crash_reporter/win/crash_service.cc index b8032f696fc..58c7c38632e 100644 --- a/atom/common/crash_reporter/win/crash_service.cc +++ b/atom/common/crash_reporter/win/crash_service.cc @@ -86,7 +86,7 @@ bool WriteReportIDToFile(const std::wstring& dump_path, if (!file.is_open()) return false; - int64 seconds_since_epoch = + int64_t seconds_since_epoch = (base::Time::Now() - base::Time::UnixEpoch()).InSeconds(); std::wstring line = base::Int64ToString16(seconds_since_epoch); line += L','; diff --git a/chromium_src/chrome/common/chrome_paths_win.cc b/chromium_src/chrome/common/chrome_paths_win.cc index 37f4ec2b05b..89c2ae48eaa 100644 --- a/chromium_src/chrome/common/chrome_paths_win.cc +++ b/chromium_src/chrome/common/chrome_paths_win.cc @@ -12,7 +12,6 @@ #include "base/files/file_path.h" #include "base/path_service.h" -#include "base/win/metro.h" #include "base/win/scoped_co_mem.h" #include "chrome/common/chrome_constants.h" From e3af5de7d74d7b107809705360f1107e16510bff Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 9 Mar 2016 13:59:28 -0800 Subject: [PATCH 0129/1265] Update pdf_to_emf_converter --- .../browser/printing/pdf_to_emf_converter.cc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc index 2231ed8b0dc..5d42264144a 100644 --- a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc +++ b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc @@ -109,21 +109,21 @@ class PdfToEmfUtilityProcessHostClient private: class GetPageCallbackData { - MOVE_ONLY_TYPE_FOR_CPP_03(GetPageCallbackData, RValue); + MOVE_ONLY_TYPE_FOR_CPP_03(GetPageCallbackData); public: GetPageCallbackData(int page_number, PdfToEmfConverter::GetPageCallback callback) : page_number_(page_number), callback_(callback) {} - // Move constructor for STL. - GetPageCallbackData(RValue other) { this->operator=(other); } + GetPageCallbackData(GetPageCallbackData&& other) { + *this = std::move(other); + } - // Move assignment for STL. - GetPageCallbackData& operator=(RValue rhs) { - page_number_ = rhs.object->page_number_; - callback_ = rhs.object->callback_; - emf_ = rhs.object->emf_.Pass(); + GetPageCallbackData& operator=(GetPageCallbackData&& rhs) { + page_number_ = rhs.page_number_; + callback_ = rhs.callback_; + emf_ = std::move(rhs.emf_); return *this; } From 89f17e0bafcd371dab2513559167fc1b370c5ea8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 14:39:40 +0900 Subject: [PATCH 0130/1265] Create complete URLRequestContextGetter for URLRequestFetchJob The trivial one is causing crashes. --- atom/browser/net/js_asker.cc | 15 ++++++-- atom/browser/net/js_asker.h | 6 +++ atom/browser/net/url_request_fetch_job.cc | 46 ++++++++++++----------- atom/browser/net/url_request_fetch_job.h | 9 ++--- vendor/brightray | 2 +- 5 files changed, 47 insertions(+), 31 deletions(-) diff --git a/atom/browser/net/js_asker.cc b/atom/browser/net/js_asker.cc index 8f0d1d2b957..b11a69c9c13 100644 --- a/atom/browser/net/js_asker.cc +++ b/atom/browser/net/js_asker.cc @@ -16,7 +16,9 @@ namespace internal { namespace { // The callback which is passed to |handler|. -void HandlerCallback(const ResponseCallback& callback, mate::Arguments* args) { +void HandlerCallback(const BeforeStartCallback& before_start, + const ResponseCallback& callback, + mate::Arguments* args) { // If there is no argument passed then we failed. v8::Local value; if (!args->GetNext(&value)) { @@ -26,6 +28,9 @@ void HandlerCallback(const ResponseCallback& callback, mate::Arguments* args) { return; } + // Give the job a chance to parse V8 value. + before_start.Run(args->isolate(), value); + // Pass whatever user passed to the actaul request job. V8ValueConverter converter; v8::Local context = args->isolate()->GetCurrentContext(); @@ -40,15 +45,17 @@ void HandlerCallback(const ResponseCallback& callback, mate::Arguments* args) { void AskForOptions(v8::Isolate* isolate, const JavaScriptHandler& handler, net::URLRequest* request, + const BeforeStartCallback& before_start, const ResponseCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Local context = isolate->GetCurrentContext(); v8::Context::Scope context_scope(context); - handler.Run(request, - mate::ConvertToV8(isolate, - base::Bind(&HandlerCallback, callback))); + handler.Run( + request, + mate::ConvertToV8(isolate, + base::Bind(&HandlerCallback, before_start, callback))); } bool IsErrorOptions(base::Value* value, int* error) { diff --git a/atom/browser/net/js_asker.h b/atom/browser/net/js_asker.h index 061a9cb859e..8a70794fa94 100644 --- a/atom/browser/net/js_asker.h +++ b/atom/browser/net/js_asker.h @@ -23,6 +23,8 @@ using JavaScriptHandler = namespace internal { +using BeforeStartCallback = + base::Callback)>; using ResponseCallback = base::Callback options)>; @@ -30,6 +32,7 @@ using ResponseCallback = void AskForOptions(v8::Isolate* isolate, const JavaScriptHandler& handler, net::URLRequest* request, + const BeforeStartCallback& before_start, const ResponseCallback& callback); // Test whether the |options| means an error. @@ -54,6 +57,7 @@ class JsAsker : public RequestJob { } // Subclass should do initailze work here. + virtual void BeforeStartInUI(v8::Isolate*, v8::Local) {} virtual void StartAsync(scoped_ptr options) = 0; net::URLRequestContextGetter* request_context_getter() const { @@ -69,6 +73,8 @@ class JsAsker : public RequestJob { isolate_, handler_, RequestJob::request(), + base::Bind(&JsAsker::BeforeStartInUI, + weak_factory_.GetWeakPtr()), base::Bind(&JsAsker::OnResponse, weak_factory_.GetWeakPtr()))); } diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index b176aef378a..d58ea3fe9fb 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -8,15 +8,14 @@ #include #include "base/strings/string_util.h" -#include "base/thread_task_runner_handle.h" +#include "native_mate/dictionary.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_builder.h" -#include "net/url_request/url_request_status.h" + +using content::BrowserThread; namespace atom { @@ -81,6 +80,25 @@ URLRequestFetchJob::URLRequestFetchJob( pending_buffer_size_(0) { } +void URLRequestFetchJob::BeforeStartInUI( + v8::Isolate* isolate, v8::Local value) { + mate::Dictionary options; + if (!mate::ConvertFromV8(isolate, value, &options)) + return; + + // When |session| is set to |null| we use a new request context for fetch job. + // TODO(zcbenz): Handle the case when it is not null. + v8::Local session; + if (options.Get("session", &session) && session->IsNull()) { + // We have to create the URLRequestContextGetter on UI thread. + url_request_context_getter_ = new brightray::URLRequestContextGetter( + this, nullptr, nullptr, base::FilePath(), true, + BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), + BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE), + nullptr, content::URLRequestInterceptorScopedVector()); + } +} + void URLRequestFetchJob::StartAsync(scoped_ptr options) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) { NotifyStartError(net::URLRequestStatus( @@ -89,14 +107,12 @@ void URLRequestFetchJob::StartAsync(scoped_ptr options) { } std::string url, method, referrer; - base::Value* session = nullptr; base::DictionaryValue* upload_data = nullptr; base::DictionaryValue* dict = static_cast(options.get()); dict->GetString("url", &url); dict->GetString("method", &method); dict->GetString("referrer", &referrer); - dict->Get("session", &session); dict->GetDictionary("uploadData", &upload_data); // Check if URL is valid. @@ -117,9 +133,9 @@ void URLRequestFetchJob::StartAsync(scoped_ptr options) { fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); fetcher_->SaveResponseWithWriter(make_scoped_ptr(new ResponsePiper(this))); - // When |session| is set to |null| we use a new request context for fetch job. - if (session && session->IsType(base::Value::TYPE_NULL)) - fetcher_->SetRequestContext(CreateRequestContext()); + // A request context getter is passed by the user. + if (url_request_context_getter_) + fetcher_->SetRequestContext(url_request_context_getter_.get()); else fetcher_->SetRequestContext(request_context_getter()); @@ -144,18 +160,6 @@ void URLRequestFetchJob::StartAsync(scoped_ptr options) { fetcher_->Start(); } -net::URLRequestContextGetter* URLRequestFetchJob::CreateRequestContext() { - if (!url_request_context_getter_.get()) { - auto task_runner = base::ThreadTaskRunnerHandle::Get(); - net::URLRequestContextBuilder builder; - builder.set_proxy_service(net::ProxyService::CreateDirect()); - request_context_ = builder.Build(); - url_request_context_getter_ = new net::TrivialURLRequestContextGetter( - request_context_.get(), task_runner); - } - return url_request_context_getter_.get(); -} - void URLRequestFetchJob::HeadersCompleted() { response_info_.reset(new net::HttpResponseInfo); response_info_->headers = fetcher_->GetResponseHeaders(); diff --git a/atom/browser/net/url_request_fetch_job.h b/atom/browser/net/url_request_fetch_job.h index d9a247c5db8..69067fdc7fd 100644 --- a/atom/browser/net/url_request_fetch_job.h +++ b/atom/browser/net/url_request_fetch_job.h @@ -8,6 +8,7 @@ #include #include "atom/browser/net/js_asker.h" +#include "browser/url_request_context_getter.h" #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_job.h" @@ -17,7 +18,8 @@ namespace atom { class AtomBrowserContext; class URLRequestFetchJob : public JsAsker, - public net::URLFetcherDelegate { + public net::URLFetcherDelegate, + public brightray::URLRequestContextGetter::Delegate { public: URLRequestFetchJob(net::URLRequest*, net::NetworkDelegate*); @@ -27,6 +29,7 @@ class URLRequestFetchJob : public JsAsker, protected: // JsAsker: + void BeforeStartInUI(v8::Isolate*, v8::Local) override; void StartAsync(scoped_ptr options) override; // net::URLRequestJob: @@ -40,10 +43,6 @@ class URLRequestFetchJob : public JsAsker, void OnURLFetchComplete(const net::URLFetcher* source) override; private: - // Create a independent request context. - net::URLRequestContextGetter* CreateRequestContext(); - - scoped_ptr request_context_; scoped_refptr url_request_context_getter_; scoped_ptr fetcher_; scoped_refptr pending_buffer_; diff --git a/vendor/brightray b/vendor/brightray index 7f9e25b50b3..73d5b67617e 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 7f9e25b50b373aea5e7d0a50c33aea22c85ee876 +Subproject commit 73d5b67617e22c7d5a305d86a05ea40972683b63 From 20466bad8f0434b0f978b2a4a90a6e7f761fbcda Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 14:45:19 +0900 Subject: [PATCH 0131/1265] Fix cpplint warnings --- atom/browser/ui/win/taskbar_host.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/browser/ui/win/taskbar_host.cc b/atom/browser/ui/win/taskbar_host.cc index abfda15edf7..f7841cfa856 100644 --- a/atom/browser/ui/win/taskbar_host.cc +++ b/atom/browser/ui/win/taskbar_host.cc @@ -138,8 +138,8 @@ bool TaskbarHost::SetOverlayIcon( base::win::ScopedHICON icon( IconUtil::CreateHICONFromSkBitmap(overlay.AsBitmap())); - return SUCCEEDED( - taskbar_->SetOverlayIcon(window, icon.get(), base::UTF8ToUTF16(text).c_str())); + return SUCCEEDED(taskbar_->SetOverlayIcon( + window, icon.get(), base::UTF8ToUTF16(text).c_str())); } bool TaskbarHost::HandleThumbarButtonEvent(int button_id) { From cadd1969d9ecb6a2bf4125f80de7778cb33d64ae Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 15:57:03 +0900 Subject: [PATCH 0132/1265] Fix compilation errors on Windows --- .../chrome/browser/ui/views/color_chooser_win.cc | 10 +++++++--- .../net/test/embedded_test_server/tcp_listen_socket.cc | 1 + common.gypi | 1 + script/lib/config.py | 2 +- vendor/brightray | 2 +- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/chromium_src/chrome/browser/ui/views/color_chooser_win.cc b/chromium_src/chrome/browser/ui/views/color_chooser_win.cc index b62801399e8..7a4f7573333 100644 --- a/chromium_src/chrome/browser/ui/views/color_chooser_win.cc +++ b/chromium_src/chrome/browser/ui/views/color_chooser_win.cc @@ -9,8 +9,10 @@ #include "chrome/browser/ui/views/color_chooser_dialog.h" #include "content/public/browser/color_chooser.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" +#include "ui/aura/window.h" #include "ui/views/color_chooser/color_chooser_listener.h" class ColorChooserWin : public content::ColorChooser, @@ -55,9 +57,11 @@ ColorChooserWin* ColorChooserWin::Open(content::WebContents* web_contents, ColorChooserWin::ColorChooserWin(content::WebContents* web_contents, SkColor initial_color) : web_contents_(web_contents) { - gfx::NativeWindow owning_window = (gfx::NativeWindow)::GetAncestor( - (HWND)web_contents->GetRenderViewHost()->GetView()->GetNativeView(), - GA_ROOT); + gfx::NativeWindow owning_window = web_contents->GetRenderViewHost() + ->GetWidget() + ->GetView() + ->GetNativeView() + ->GetToplevelWindow(); color_chooser_dialog_ = new ColorChooserDialog(this, initial_color, owning_window); diff --git a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc index fbdcc2bfc7e..1a72b2efe37 100644 --- a/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc +++ b/chromium_src/net/test/embedded_test_server/tcp_listen_socket.cc @@ -8,6 +8,7 @@ // winsock2.h must be included first in order to ensure it is included before // windows.h. #include +#include #elif defined(OS_POSIX) #include #include diff --git a/common.gypi b/common.gypi index d8c7ee30935..6eacdc93a02 100644 --- a/common.gypi +++ b/common.gypi @@ -43,6 +43,7 @@ 'target_conditions': [ ['_target_name in ["libuv", "http_parser", "openssl", "cares", "node", "zlib"]', { 'msvs_disabled_warnings': [ + 4003, # not enough actual parameters for macro 'V' 4013, # 'free' undefined; assuming extern returning int 4018, # signed/unsigned mismatch 4054, # diff --git a/script/lib/config.py b/script/lib/config.py index 10319a2df4e..e5fafa34720 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'a661ccb38f21859309cc97c1fc313f1360101462' +LIBCHROMIUMCONTENT_COMMIT = '497f11bcb91d9b0b5b5cbd004411b37b933c825e' PLATFORM = { 'cygwin': 'win32', diff --git a/vendor/brightray b/vendor/brightray index 73d5b67617e..4a1be58208f 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 73d5b67617e22c7d5a305d86a05ea40972683b63 +Subproject commit 4a1be58208fc89a2d56cd95aed4864158890b96b From 0794980d01454c697b22a4d277ab84fffa99476e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 17:34:52 +0900 Subject: [PATCH 0133/1265] pdf.dll is not shipped any more --- script/create-dist.py | 1 - 1 file changed, 1 deletion(-) diff --git a/script/create-dist.py b/script/create-dist.py index 32d8f52aff3..f3894eb4fa2 100755 --- a/script/create-dist.py +++ b/script/create-dist.py @@ -40,7 +40,6 @@ TARGET_BINARIES = { 'msvcr120.dll', 'ffmpeg.dll', 'node.dll', - 'pdf.dll', 'content_resources_200_percent.pak', 'ui_resources_200_percent.pak', 'xinput1_3.dll', From 60f40a6704091706cf2cc0245d1e29a53a5980ea Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 21:01:45 +0900 Subject: [PATCH 0134/1265] Fix linking error for Release build on Linux --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index 4a1be58208f..5077bee89dc 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 4a1be58208fc89a2d56cd95aed4864158890b96b +Subproject commit 5077bee89dc3403982e9a5c59cc0a2218b2d4610 From e27e3d641c79cd82787d042e7abf0819ccf67113 Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 4 Mar 2016 05:24:01 +0530 Subject: [PATCH 0135/1265] linux: optionaly allow building x64 targets with sysroot --- .gitignore | 1 + script/bootstrap.py | 29 ++++++++++++++++++++++------- script/install-sysroot.py | 21 +++++++++++++++------ script/update.py | 6 ++++++ toolchain.gypi | 5 ++++- 5 files changed, 48 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index eb9aedb4e2f..a92239801a4 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ /external_binaries/ /out/ /vendor/brightray/vendor/download/ +/vendor/debian_wheezy_amd64-sysroot/ /vendor/debian_wheezy_arm-sysroot/ /vendor/debian_wheezy_i386-sysroot/ /vendor/python_26/ diff --git a/script/bootstrap.py b/script/bootstrap.py index 6eaf635bfd8..b09bc015d70 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -43,8 +43,8 @@ def main(): args.libcc_source_path, args.libcc_shared_library_path, args.libcc_static_library_path) - if args.target_arch in ['arm', 'ia32'] and PLATFORM == 'linux': - download_sysroot(args.target_arch) + if PLATFORM == 'linux': + download_sysroot(args.target_arch, args.sysroot_url, args.sysroot_sha1sum) create_chrome_version_h() touch_config_gypi() @@ -79,6 +79,10 @@ def parse_args(): help='The shared library path of libchromiumcontent.') parser.add_argument('--libcc_static_library_path', required=False, help='The static library path of libchromiumcontent.') + parser.add_argument('--sysroot_url', required=False, + help='The URL to download sysroot image.') + parser.add_argument('--sysroot_sha1sum', required=False, + help='SHA1 hash of the sysroot image tarball.') return parser.parse_args() @@ -163,11 +167,22 @@ def update_clang(): execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'update-clang.sh')]) -def download_sysroot(target_arch): - if target_arch == 'ia32': - target_arch = 'i386' - execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py'), - '--arch', target_arch]) +def download_sysroot(target_arch, url, sha1sum): + if url or target_arch in ['ia32', 'arm']: + os.environ['USE_SYSROOT'] = '1' + sysroot_script = os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py') + if target_arch == 'ia32': + target_arch = 'i386' + if target_arch == 'x64': + target_arch = 'amd64' + args = [ + '--arch', target_arch + ] + if url: + args += ['--url', url] + if sha1sum: + args += ['--revision', sha1sum] + execute_stdout([sysroot_script] + args) def create_chrome_version_h(): diff --git a/script/install-sysroot.py b/script/install-sysroot.py index 69acfb13269..6c7b8adc62d 100755 --- a/script/install-sysroot.py +++ b/script/install-sysroot.py @@ -134,7 +134,11 @@ def main(): print 'Unknown architecture: %s' % target_arch assert(False) - url = '%s/%s/%s/%s' % (URL_PREFIX, URL_PATH, revision, tarball_filename) + if options.url: + url = options.url + tarball_sha1sum = options.revision + else: + url = '%s/%s/%s/%s' % (URL_PREFIX, URL_PATH, revision, tarball_filename) stamp = os.path.join(sysroot, '.stamp') if os.path.exists(stamp): @@ -153,11 +157,12 @@ def main(): sys.stdout.flush() sys.stderr.flush() subprocess.check_call(['curl', '--fail', '-L', url, '-o', tarball]) - sha1sum = GetSha1(tarball) - if sha1sum != tarball_sha1sum: - print 'Tarball sha1sum is wrong.' - print 'Expected %s, actual: %s' % (tarball_sha1sum, sha1sum) - return 1 + if tarball_sha1sum: + sha1sum = GetSha1(tarball) + if sha1sum != tarball_sha1sum: + print 'Tarball sha1sum is wrong.' + print 'Expected %s, actual: %s' % (tarball_sha1sum, sha1sum) + return 1 subprocess.check_call(['tar', 'xf', tarball, '-C', sysroot]) os.remove(tarball) @@ -173,5 +178,9 @@ if __name__ == '__main__': 'Linux builds') parser.add_option('--arch', type='choice', choices=valid_archs, help='Sysroot architecture: %s' % ', '.join(valid_archs)) + parser.add_option('--url', default=None, + help='The URL to download sysroot image.') + parser.add_option('--revision', default=None, + help='SHA1 hash of the sysroot image tarball.') options, _ = parser.parse_args() sys.exit(main()) diff --git a/script/update.py b/script/update.py index e91e8401cbf..2388f16515c 100755 --- a/script/update.py +++ b/script/update.py @@ -60,12 +60,18 @@ def run_gyp(target_arch, component): mas_build = 1 else: mas_build = 0 + # Whether to use sysroot image. + if os.environ.has_key('USE_SYSROOT'): + use_sysroot = 1 + else: + use_sysroot = 0 defines = [ '-Dlibchromiumcontent_component={0}'.format(component), '-Dtarget_arch={0}'.format(target_arch), '-Dhost_arch={0}'.format(get_host_arch()), '-Dlibrary=static_library', '-Dmas_build={0}'.format(mas_build), + '-Duse_sysroot={0}'.format(use_sysroot) ] return subprocess.call([python, gyp, '-f', 'ninja', '--depth', '.', 'atom.gyp', '-Icommon.gypi'] + defines, env=env) diff --git a/toolchain.gypi b/toolchain.gypi index 23592d0473a..7215cb8c542 100644 --- a/toolchain.gypi +++ b/toolchain.gypi @@ -113,7 +113,7 @@ }], # Setup sysroot environment. - ['OS=="linux" and target_arch in ["arm", "ia32"]', { + ['OS=="linux" and target_arch in ["arm", "ia32", "x64"] and use_sysroot', { 'variables': { 'conditions': [ ['target_arch=="arm"', { @@ -124,6 +124,9 @@ ['target_arch=="ia32"', { 'sysroot': '<(source_root)/vendor/debian_wheezy_i386-sysroot', }], + ['target_arch=="x64"', { + 'sysroot': '<(source_root)/vendor/debian_wheezy_amd64-sysroot', + }], ], }, 'target_defaults': { From 91951472bf06e82ab472d8aad62b4be17a9b3033 Mon Sep 17 00:00:00 2001 From: Robo Date: Tue, 8 Mar 2016 20:35:32 +0530 Subject: [PATCH 0136/1265] use sysroot by default on linux --- script/bootstrap.py | 30 ++++++++---------------------- script/install-sysroot.py | 33 ++++++++++++--------------------- script/update.py | 6 ------ toolchain.gypi | 2 +- 4 files changed, 21 insertions(+), 50 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index b09bc015d70..b0a528f760a 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -44,7 +44,7 @@ def main(): args.libcc_static_library_path) if PLATFORM == 'linux': - download_sysroot(args.target_arch, args.sysroot_url, args.sysroot_sha1sum) + download_sysroot(args.target_arch) create_chrome_version_h() touch_config_gypi() @@ -79,10 +79,6 @@ def parse_args(): help='The shared library path of libchromiumcontent.') parser.add_argument('--libcc_static_library_path', required=False, help='The static library path of libchromiumcontent.') - parser.add_argument('--sysroot_url', required=False, - help='The URL to download sysroot image.') - parser.add_argument('--sysroot_sha1sum', required=False, - help='SHA1 hash of the sysroot image tarball.') return parser.parse_args() @@ -167,23 +163,13 @@ def update_clang(): execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'update-clang.sh')]) -def download_sysroot(target_arch, url, sha1sum): - if url or target_arch in ['ia32', 'arm']: - os.environ['USE_SYSROOT'] = '1' - sysroot_script = os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py') - if target_arch == 'ia32': - target_arch = 'i386' - if target_arch == 'x64': - target_arch = 'amd64' - args = [ - '--arch', target_arch - ] - if url: - args += ['--url', url] - if sha1sum: - args += ['--revision', sha1sum] - execute_stdout([sysroot_script] + args) - +def download_sysroot(target_arch): + if target_arch == 'ia32': + target_arch = 'i386' + if target_arch == 'x64': + target_arch = 'amd64' + execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py'), + '--arch', target_arch]) def create_chrome_version_h(): version_file = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', diff --git a/script/install-sysroot.py b/script/install-sysroot.py index 6c7b8adc62d..16df6f7b9e5 100755 --- a/script/install-sysroot.py +++ b/script/install-sysroot.py @@ -30,15 +30,15 @@ from lib.util import get_host_arch SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) URL_PREFIX = 'https://github.com' URL_PATH = 'atom/debian-sysroot-image-creator/releases/download' -REVISION_AMD64 = 264817 -REVISION_I386 = 'v0.2.0' -REVISION_ARM = 'v0.1.0' +REVISION_AMD64 = 'v0.3.0' +REVISION_I386 = 'v0.3.0' +REVISION_ARM = 'v0.3.0' TARBALL_AMD64 = 'debian_wheezy_amd64_sysroot.tgz' TARBALL_I386 = 'debian_wheezy_i386_sysroot.tgz' TARBALL_ARM = 'debian_wheezy_arm_sysroot.tgz' -TARBALL_AMD64_SHA1SUM = '74b7231e12aaf45c5c5489d9aebb56bd6abb3653' -TARBALL_I386_SHA1SUM = 'f5b2ceaeb3f7e6bc2058733585fe877d002b5fa7' -TARBALL_ARM_SHA1SUM = '72e668c57b8591e108759584942ddb6f6cee1322' +TARBALL_AMD64_SHA1SUM = '3dc6f553c3f4e54166ac1264b7754cddc01942e4' +TARBALL_I386_SHA1SUM = '62d2490de201f73b3774868f7ab82b2a48acf3c0' +TARBALL_ARM_SHA1SUM = '1110793341e7a3c12adfe5e53138d692a22c99bc' SYSROOT_DIR_AMD64 = 'debian_wheezy_amd64-sysroot' SYSROOT_DIR_I386 = 'debian_wheezy_i386-sysroot' SYSROOT_DIR_ARM = 'debian_wheezy_arm-sysroot' @@ -134,11 +134,7 @@ def main(): print 'Unknown architecture: %s' % target_arch assert(False) - if options.url: - url = options.url - tarball_sha1sum = options.revision - else: - url = '%s/%s/%s/%s' % (URL_PREFIX, URL_PATH, revision, tarball_filename) + url = '%s/%s/%s/%s' % (URL_PREFIX, URL_PATH, revision, tarball_filename) stamp = os.path.join(sysroot, '.stamp') if os.path.exists(stamp): @@ -157,12 +153,11 @@ def main(): sys.stdout.flush() sys.stderr.flush() subprocess.check_call(['curl', '--fail', '-L', url, '-o', tarball]) - if tarball_sha1sum: - sha1sum = GetSha1(tarball) - if sha1sum != tarball_sha1sum: - print 'Tarball sha1sum is wrong.' - print 'Expected %s, actual: %s' % (tarball_sha1sum, sha1sum) - return 1 + sha1sum = GetSha1(tarball) + if sha1sum != tarball_sha1sum: + print 'Tarball sha1sum is wrong.' + print 'Expected %s, actual: %s' % (tarball_sha1sum, sha1sum) + return 1 subprocess.check_call(['tar', 'xf', tarball, '-C', sysroot]) os.remove(tarball) @@ -178,9 +173,5 @@ if __name__ == '__main__': 'Linux builds') parser.add_option('--arch', type='choice', choices=valid_archs, help='Sysroot architecture: %s' % ', '.join(valid_archs)) - parser.add_option('--url', default=None, - help='The URL to download sysroot image.') - parser.add_option('--revision', default=None, - help='SHA1 hash of the sysroot image tarball.') options, _ = parser.parse_args() sys.exit(main()) diff --git a/script/update.py b/script/update.py index 2388f16515c..e91e8401cbf 100755 --- a/script/update.py +++ b/script/update.py @@ -60,18 +60,12 @@ def run_gyp(target_arch, component): mas_build = 1 else: mas_build = 0 - # Whether to use sysroot image. - if os.environ.has_key('USE_SYSROOT'): - use_sysroot = 1 - else: - use_sysroot = 0 defines = [ '-Dlibchromiumcontent_component={0}'.format(component), '-Dtarget_arch={0}'.format(target_arch), '-Dhost_arch={0}'.format(get_host_arch()), '-Dlibrary=static_library', '-Dmas_build={0}'.format(mas_build), - '-Duse_sysroot={0}'.format(use_sysroot) ] return subprocess.call([python, gyp, '-f', 'ninja', '--depth', '.', 'atom.gyp', '-Icommon.gypi'] + defines, env=env) diff --git a/toolchain.gypi b/toolchain.gypi index 7215cb8c542..42c2987dc68 100644 --- a/toolchain.gypi +++ b/toolchain.gypi @@ -113,7 +113,7 @@ }], # Setup sysroot environment. - ['OS=="linux" and target_arch in ["arm", "ia32", "x64"] and use_sysroot', { + ['OS=="linux" and target_arch in ["arm", "ia32", "x64"]', { 'variables': { 'conditions': [ ['target_arch=="arm"', { From dfe1641d1e8a6ec77f3cc8f14346b3f3ab75c9b1 Mon Sep 17 00:00:00 2001 From: Robo Date: Wed, 9 Mar 2016 19:41:17 +0530 Subject: [PATCH 0137/1265] set path for pkg-config when using sysroot --- common.gypi | 6 +++ toolchain.gypi | 51 +++++++++++++----------- tools/linux/pkg-config-wrapper | 49 +++++++++++++++++++++++ tools/linux/rewrite_dirs.py | 71 ++++++++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 23 deletions(-) create mode 100755 tools/linux/pkg-config-wrapper create mode 100755 tools/linux/rewrite_dirs.py diff --git a/common.gypi b/common.gypi index 6eacdc93a02..285baa84c29 100644 --- a/common.gypi +++ b/common.gypi @@ -260,5 +260,11 @@ }, }, }], # OS=="mac" + + ['OS=="linux"', { + 'variables': { + 'pkg-config': '<(source_root)/tools/linux/pkg-config-wrapper "<(sysroot)" "<(target_arch)" "<(system_libdir)"', + }, + }], # OS=="linux" ], } diff --git a/toolchain.gypi b/toolchain.gypi index 42c2987dc68..8e07ecc497b 100644 --- a/toolchain.gypi +++ b/toolchain.gypi @@ -5,8 +5,7 @@ # Set this to true when building with Clang. 'clang%': 1, - # Path to sysroot dir. - 'sysroot%': '', + 'system_libdir%': 'lib', 'variables': { # The minimum OS X SDK version to use. @@ -17,12 +16,20 @@ # Set NEON compilation flags. 'arm_neon%': 1, + + 'conditions': [ + # Define the abosulte version of <(DEPTH). + ['OS!="win"', { + 'source_root%': '&2 + exit 1 +fi + +rewrite=`dirname $0`/rewrite_dirs.py +package=${!#} + +libdir=$root/usr/$libpath/pkgconfig:$root/usr/share/pkgconfig + +set -e +# Some sysroots, like the Chromium OS ones, may generate paths that are not +# relative to the sysroot. For example, +# /path/to/chroot/build/x86-generic/usr/lib/pkgconfig/pkg.pc may have all paths +# relative to /path/to/chroot (i.e. prefix=/build/x86-generic/usr) instead of +# relative to /path/to/chroot/build/x86-generic (i.e prefix=/usr). +# To support this correctly, it's necessary to extract the prefix to strip from +# pkg-config's |prefix| variable. +prefix=`PKG_CONFIG_LIBDIR=$libdir pkg-config --variable=prefix "$package" | sed -e 's|/usr$||'` +result=`PKG_CONFIG_LIBDIR=$libdir pkg-config "$@"` +echo "$result"| $rewrite --sysroot "$root" --strip-prefix "$prefix" diff --git a/tools/linux/rewrite_dirs.py b/tools/linux/rewrite_dirs.py new file mode 100755 index 00000000000..30f22f0cd61 --- /dev/null +++ b/tools/linux/rewrite_dirs.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Rewrites paths in -I, -L and other option to be relative to a sysroot.""" + +import sys +import os +import optparse + +REWRITE_PREFIX = ['-I', + '-idirafter', + '-imacros', + '-imultilib', + '-include', + '-iprefix', + '-iquote', + '-isystem', + '-L'] + +def RewritePath(path, opts): + """Rewrites a path by stripping the prefix and prepending the sysroot.""" + sysroot = opts.sysroot + prefix = opts.strip_prefix + if os.path.isabs(path) and not path.startswith(sysroot): + if path.startswith(prefix): + path = path[len(prefix):] + path = path.lstrip('/') + return os.path.join(sysroot, path) + else: + return path + + +def RewriteLine(line, opts): + """Rewrites all the paths in recognized options.""" + args = line.split() + count = len(args) + i = 0 + while i < count: + for prefix in REWRITE_PREFIX: + # The option can be either in the form "-I /path/to/dir" or + # "-I/path/to/dir" so handle both. + if args[i] == prefix: + i += 1 + try: + args[i] = RewritePath(args[i], opts) + except IndexError: + sys.stderr.write('Missing argument following %s\n' % prefix) + break + elif args[i].startswith(prefix): + args[i] = prefix + RewritePath(args[i][len(prefix):], opts) + i += 1 + + return ' '.join(args) + + +def main(argv): + parser = optparse.OptionParser() + parser.add_option('-s', '--sysroot', default='/', help='sysroot to prepend') + parser.add_option('-p', '--strip-prefix', default='', help='prefix to strip') + opts, args = parser.parse_args(argv[1:]) + + for line in sys.stdin.readlines(): + line = RewriteLine(line.strip(), opts) + print line + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) From ed2103a49fdafad683fd81eb071c48e6b79c846d Mon Sep 17 00:00:00 2001 From: Robo Date: Thu, 10 Mar 2016 17:24:45 +0530 Subject: [PATCH 0138/1265] update sysroot image revisions --- script/bootstrap.py | 2 +- script/install-sysroot.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index b0a528f760a..1efea3c2897 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -165,7 +165,7 @@ def update_clang(): def download_sysroot(target_arch): if target_arch == 'ia32': - target_arch = 'i386' + target_arch = 'i386' if target_arch == 'x64': target_arch = 'amd64' execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py'), diff --git a/script/install-sysroot.py b/script/install-sysroot.py index 16df6f7b9e5..be68fbad0ad 100755 --- a/script/install-sysroot.py +++ b/script/install-sysroot.py @@ -30,15 +30,15 @@ from lib.util import get_host_arch SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) URL_PREFIX = 'https://github.com' URL_PATH = 'atom/debian-sysroot-image-creator/releases/download' -REVISION_AMD64 = 'v0.3.0' -REVISION_I386 = 'v0.3.0' -REVISION_ARM = 'v0.3.0' +REVISION_AMD64 = 'v0.4.0' +REVISION_I386 = 'v0.4.0' +REVISION_ARM = 'v0.4.0' TARBALL_AMD64 = 'debian_wheezy_amd64_sysroot.tgz' TARBALL_I386 = 'debian_wheezy_i386_sysroot.tgz' TARBALL_ARM = 'debian_wheezy_arm_sysroot.tgz' -TARBALL_AMD64_SHA1SUM = '3dc6f553c3f4e54166ac1264b7754cddc01942e4' -TARBALL_I386_SHA1SUM = '62d2490de201f73b3774868f7ab82b2a48acf3c0' -TARBALL_ARM_SHA1SUM = '1110793341e7a3c12adfe5e53138d692a22c99bc' +TARBALL_AMD64_SHA1SUM = 'a7e8faa99b681317969ac450a27233925bdeed62' +TARBALL_I386_SHA1SUM = '9fc827eddc26e562c0a0b2586be5dc075e570e10' +TARBALL_ARM_SHA1SUM = 'bfa4233708ab937d682a14e8d87ddba3cadb6eae' SYSROOT_DIR_AMD64 = 'debian_wheezy_amd64-sysroot' SYSROOT_DIR_I386 = 'debian_wheezy_i386-sysroot' SYSROOT_DIR_ARM = 'debian_wheezy_arm-sysroot' From 8e19edd1b519fec7420f3245397c660e13e955a5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 10 Mar 2016 21:58:09 +0900 Subject: [PATCH 0139/1265] Move toolchain related configures into one place --- common.gypi | 6 ------ toolchain.gypi | 50 +++++++++++++++++++++++++++----------------------- 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/common.gypi b/common.gypi index 285baa84c29..6eacdc93a02 100644 --- a/common.gypi +++ b/common.gypi @@ -260,11 +260,5 @@ }, }, }], # OS=="mac" - - ['OS=="linux"', { - 'variables': { - 'pkg-config': '<(source_root)/tools/linux/pkg-config-wrapper "<(sysroot)" "<(target_arch)" "<(system_libdir)"', - }, - }], # OS=="linux" ], } diff --git a/toolchain.gypi b/toolchain.gypi index 8e07ecc497b..7c3cd0d0583 100644 --- a/toolchain.gypi +++ b/toolchain.gypi @@ -5,8 +5,6 @@ # Set this to true when building with Clang. 'clang%': 1, - 'system_libdir%': 'lib', - 'variables': { # The minimum OS X SDK version to use. 'mac_sdk_min%': '10.10', @@ -17,12 +15,8 @@ # Set NEON compilation flags. 'arm_neon%': 1, - 'conditions': [ - # Define the abosulte version of <(DEPTH). - ['OS!="win"', { - 'source_root%': ' Date: Thu, 10 Mar 2016 23:12:57 +0800 Subject: [PATCH 0140/1265] finish browser-window first --- docs-translations/zh-CN/api/browser-window.md | 767 ++++++++++++++++++ 1 file changed, 767 insertions(+) create mode 100644 docs-translations/zh-CN/api/browser-window.md diff --git a/docs-translations/zh-CN/api/browser-window.md b/docs-translations/zh-CN/api/browser-window.md new file mode 100644 index 00000000000..66ae76cff91 --- /dev/null +++ b/docs-translations/zh-CN/api/browser-window.md @@ -0,0 +1,767 @@ +# BrowserWindow + + `BrowserWindow` 类让你有创建一个浏览器窗口的权力。例如: + +```javascript +// In the main process. +const BrowserWindow = require('electron').BrowserWindow; + +// Or in the renderer process. +const BrowserWindow = require('electron').remote.BrowserWindow; + +var win = new BrowserWindow({ width: 800, height: 600, show: false }); +win.on('closed', function() { + win = null; +}); + +win.loadURL('https://github.com'); +win.show(); +``` + +你也可以不通过chrome创建窗口,使用 +[Frameless Window](frameless-window.md) API. + +## Class: BrowserWindow + +`BrowserWindow` 是一个 +[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). + +通过 `options` 可以创建一个具有本质属性的 `BrowserWindow` . + +### `new BrowserWindow([options])` + +* `options` Object + * `width` Integer - 窗口宽度,单位像素. 默认是 `800`. + * `height` Integer - 窗口高度,单位像素. 默认是 `600`. + * `x` Integer - 窗口相对于屏幕的左偏移位置.默认居中. + * `y` Integer - 窗口相对于屏幕的顶部偏移位置.默认居中. + * `useContentSize` Boolean - `width` 和 `height` 使用web网页size, 这意味着实际窗口的size应该包括窗口框架的size,稍微会大一点,默认为 `false`. + * `center` Boolean - 窗口屏幕居中. + * `minWidth` Integer - 窗口最小宽度,默认为 `0`. + * `minHeight` Integer - 窗口最小高度,默认为 `0`. + * `maxWidth` Integer - 窗口最大宽度,默认无限制. + * `maxHeight` Integer - 窗口最大高度,默认无限制. + * `resizable` Boolean - 是否可以改变窗口size,默认为 `true`. + * `movable` Boolean - 窗口是否可以拖动. 在 Linux 上无效. 默认为 `true`. + * `minimizable` Boolean - 窗口是否可以最小化. 在 Linux 上无效. 默认为 `true`. + * `maximizable` Boolean - 窗口是否可以最大化. 在 Linux 上无效. 默认为 `true`. + * `closable` Boolean - 窗口是否可以关闭. 在 Linux 上无效. 默认为 `true`. + * `alwaysOnTop` Boolean - 窗口是否总是显示在其他窗口之前. 在 Linux 上无效. 默认为 `false`. + * `fullscreen` Boolean - 窗口是否可以全屏幕. 当明确设置值为When `false` ,全屏化按钮将会隐藏,在 OS X 将禁用. 默认 `false`. + * `fullscreenable` Boolean - 在 OS X 上,全屏化按钮是否可用,默认为 `true`. + * `skipTaskbar` Boolean - 是否在人物栏中显示窗口. 默认是`false`. + * `kiosk` Boolean - kiosk 方式. 默认为 `false`. + * `title` String - 窗口默认title. 默认 `"Electron"`. + * `icon` [NativeImage](native-image.md) - 窗口图标, 如果不设置,窗口将使用可用的默认图标. + * `show` Boolean - 窗口创建的时候是否显示. 默认为 `true`. + * `frame` Boolean - 指定 `false` 来创建一个 + [Frameless Window](frameless-window.md). 默认为 `true`. + * `acceptFirstMouse` Boolean - 是否允许单击web view来激活窗口 . 默认为 `false`. + * `disableAutoHideCursor` Boolean - 当 typing 时是否隐藏鼠标.默认 `false`. + * `autoHideMenuBar` Boolean - 除非点击 `Alt`,否则隐藏菜单栏.默认为 `false`. + * `enableLargerThanScreen` Boolean - 是否允许允许改变窗口大小大于屏幕. 默认是 `false`. + * `backgroundColor` String -窗口的 background color 值为十六进制,如 `#66CD00` 或 `#FFF` 或 `#80FFFFFF` (支持透明度). 默认为在 Linux 和 Windows 上为 + `#000` (黑色) , Mac上为 `#FFF`(或透明). + * `hasShadow` Boolean - 窗口是否有阴影. 只在 OS X 上有效. 默认为 `true`. + * `darkTheme` Boolean - 为窗口使用 dark 主题, 只在一些拥有 GTK+3 桌面环境上有效. 默认为 `false`. + * `transparent` Boolean - 窗口 [透明](frameless-window.md). + 默认为 `false`. + * `type` String - 窗口type, 默认普通窗口. 下面查看更多. + * `titleBarStyle` String - 窗口标题栏样式. 下面查看更多. + * `webPreferences` Object - 设置界面特性. 下面查看更多. + +`type` 的值和效果不同平台展示效果不同,具体: + +* Linux, 可用值为 `desktop`, `dock`, `toolbar`, `splash`, + `notification`. +* OS X, 可用值为 `desktop`, `textured`. + * `textured` type 添加金属梯度效果 + (`NSTexturedBackgroundWindowMask`). + * `desktop` 设置窗口在桌面背景窗口水平 + (`kCGDesktopWindowLevel - 1`). 注意桌面窗口不可聚焦, 不可不支持键盘和鼠标事件, 但是可以使用 `globalShortcut` 来解决输入问题. + +`titleBarStyle` 只在 OS X 10.10 Yosemite 或更新版本上支持. +可用值: + +* `default` 以及无值, 显示在 Mac 标题栏上为不透明的标准灰色. +* `hidden` 隐藏标题栏,内容充满整个窗口, 然后它依然在左上角,仍然受标准窗口控制. +* `hidden-inset`主体隐藏,显示小的控制按钮在窗口边缘. + +`webPreferences` 参数是个对象,它的属性: + +* `nodeIntegration` Boolean - 是否完整支持node. 默认为 `true`. +* `preload` String - 界面的其它脚本运行之前预先加载一个指定脚本. 这个脚本将一直可以使用 node APIs 无论 node integration 是否开启. 脚本路径为绝对路径. + 当 node integration 关闭, 预加载的脚本将从全局范围重新引入node的全局引用标志. 查看例子 + [here](process.md#event-loaded). +* `session` [Session](session.md#class-session) - 设置界面session. 而不是直接忽略session对象 , 也可用 `partition` 来代替, 它接受一个 partition 字符串. 当同时使用 `session` 和 `partition`, `session` 优先级更高. + 默认使用默认 session. +* `partition` String - 通过session的partition字符串来设置界面session. 如果 `partition` 以 `persist:` 开头, 这个界面将会为所有界面使用相同的 `partition`. 如果没有 `persist:` 前缀, 界面使用历史session. 通过分享同一个 `partition`, 所有界面使用相同的session. 默认使用默认 session. +* `zoomFactor` Number - 界面默认缩放值, `3.0` 表示 + `300%`. 默认 `1.0`. +* `javascript` Boolean - 开启javascript支持. 默认为`true`. +* `webSecurity` Boolean - 当设置为 `false`, 它将禁用相同地方的规则 (通常测试服), 并且如果有2个非用户设置的参数,就设置 + `allowDisplayingInsecureContent` 和 `allowRunningInsecureContent` 的值为 + `true`. 默认为 `true`. +* `allowDisplayingInsecureContent` Boolean -允许一个使用 https的界面来展示由 http URLs 传过来的资源. 默认`false`. +* `allowRunningInsecureContent` Boolean - Boolean -允许一个使用 https的界面来渲染由 http URLs 提交的html,css,javascript. 默认为 `false`. +* `images` Boolean - 开启图片使用支持. 默认 `true`. +* `textAreasAreResizable` Boolean - textArea 可以编辑. 默认为 `true`. +* `webgl` Boolean - 开启 WebGL 支持. 默认为 `true`. +* `webaudio` Boolean - 开启 WebAudio 支持. 默认为 `true`. +* `plugins` Boolean - 是否开启插件支持. 默认为 `false`. +* `experimentalFeatures` Boolean - 开启 Chromium 的 可测试 特性. + 默认为 `false`. +* `experimentalCanvasFeatures` Boolean - 开启 Chromium 的 canvas 可测试特性. 默认为 `false`. +* `directWrite` Boolean - 开启窗口的 DirectWrite font 渲染系统. 默认为 `true`. +* `blinkFeatures` String - 以 `,` 分隔的特性列表, 如 + `CSSVariables,KeyboardEventKey`. 被支持的所有特性可在 [setFeatureEnabledFromString][blink-feature-string] + 中找到. +* `defaultFontFamily` Object - 设置 font-family 默认字体. + * `standard` String - 默认为 `Times New Roman`. + * `serif` String - 默认为 `Times New Roman`. + * `sansSerif` String - 默认为 `Arial`. + * `monospace` String - 默认为 `Courier New`. +* `defaultFontSize` Integer - 默认为 `16`. +* `defaultMonospaceFontSize` Integer - 默认为 `13`. +* `minimumFontSize` Integer - 默认为 `0`. +* `defaultEncoding` String - 默认为 `ISO-8859-1`. + +## 事件 + + `BrowserWindow` 对象可触发下列事件: + +**注意:** 一些事件只能在特定os环境中触发,已经尽可能地标出. + +### Event: 'page-title-updated' + +返回: + +* `event` Event + +当文档改变标题时触发,使用 `event.preventDefault()` 可以阻止原窗口的标题改变. + +### Event: 'close' + +返回: + +* `event` Event + +在窗口要关闭的时候触发. 它在DOM的 `beforeunload` and `unload` 事件之前触发.使用 `event.preventDefault()` 可以取消这个操作 + +通常你想通过 `beforeunload` 处理器来决定是否关闭窗口,但是它也会在窗口重载的时候被触发. 在 Electron 中,返回一个空的字符串或 `false` 可以取消关闭.例如: + +```javascript +window.onbeforeunload = function(e) { + console.log('I do not want to be closed'); + + // Unlike usual browsers, in which a string should be returned and the user is + // prompted to confirm the page unload, Electron gives developers more options. + // Returning empty string or false would prevent the unloading now. + // You can also use the dialog API to let the user confirm closing the application. + e.returnValue = false; +}; +``` + +### Event: 'closed' + +当窗口已经关闭的时候触发.当你接收到这个事件的时候,你应当删除对已经关闭的窗口的引用对象和避免再次使用它. + +### Event: 'unresponsive' + +在界面卡死的时候触发事件. + +### Event: 'responsive' + +在界面恢复卡死的时候触发. + +### Event: 'blur' + +在窗口失去焦点的时候触发. + +### Event: 'focus' + +在窗口获得焦点的时候触发. + +### Event: 'maximize' + +在窗口最大化的时候触发. + +### Event: 'unmaximize' + +在窗口退出最大化的时候触发. + +### Event: 'minimize' + +在窗口最小化的时候触发. + +### Event: 'restore' + +在窗口从最小化恢复的时候触发. +Emitted when the window is restored from minimized state. + +### Event: 'resize' + +在窗口size改变的时候触发. +Emitted when the window is getting resized. + +### Event: 'move' + +在窗口移动的时候触发. + +注意:在 OS X 中别名为 `moved`. + +### Event: 'moved' _OS X_ + +在窗口移动的时候触发. + +### Event: 'enter-full-screen' + +在的窗口进入全屏状态时候触发. + +### Event: 'leave-full-screen' + +在的窗口退出全屏状态时候触发. + +### Event: 'enter-html-full-screen' + +在的窗口通过 html api 进入全屏状态时候触发. + +### Event: 'leave-html-full-screen' + +在的窗口通过 html api 退出全屏状态时候触发. + +### Event: 'app-command' _Windows_ + +在请求一个[App Command](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx)的时候触发. +典型的是键盘媒体或浏览器命令, Windows上的 "Back" 按钮用作鼠标也会触发. + +```js +someWindow.on('app-command', function(e, cmd) { + // Navigate the window back when the user hits their mouse back button + if (cmd === 'browser-backward' && someWindow.webContents.canGoBack()) { + someWindow.webContents.goBack(); + } +}); +``` + +### Event: 'scroll-touch-begin' _OS X_ + +在滚动条事件开始的时候触发. + +### Event: 'scroll-touch-end' _OS X_ + +在滚动条事件结束的时候触发. + +## 方法 + +`BrowserWindow` 对象有如下方法: + +### `BrowserWindow.getAllWindows()` + +返回一个所有已经打开了的窗口的对象数组. + +### `BrowserWindow.getFocusedWindow()` + +返回应用当前聚焦窗口,如果没有就返回 `null`. + +### `BrowserWindow.fromWebContents(webContents)` + +* `webContents` [WebContents](web-contents.md) + +根据 `webContents` 查找窗口. + +### `BrowserWindow.fromId(id)` + +* `id` Integer + +根据 id 查找窗口. + +### `BrowserWindow.addDevToolsExtension(path)` + +* `path` String + +添加位于 `path` 的开发者工具栏扩展,并且返回扩展项的名字. + +这个扩展会被添加到历史,所以只需要使用这个API一次,这个api不可用作编程使用. + +### `BrowserWindow.removeDevToolsExtension(name)` + +* `name` String + +删除开发者工具栏名为 `name` 的扩展. + +## 实例属性 + +使用 `new BrowserWindow` 创建的实例对象,有如下属性: + +```javascript +// In this example `win` is our instance +var win = new BrowserWindow({ width: 800, height: 600 }); +``` + +### `win.webContents` + +这个窗口的 `WebContents` 对象,所有与界面相关的事件和方法都通过它完成的. + +查看 [`webContents` documentation](web-contents.md) 的方法和事件. + +### `win.id` + +窗口的唯一id. + +## 实例方法 + +使用 `new BrowserWindow` 创建的实例对象,有如下方法: + +**注意:** 一些方法只能在特定os环境中调用,已经尽可能地标出. + +### `win.destroy()` + +强制关闭窗口, `unload` and `beforeunload` 不会触发,并且 `close` 也不会触发, 但是它保证了 `closed` 触发. + +### `win.close()` + +尝试关闭窗口,这与用户点击关闭按钮的效果一样. 虽然网页可能会取消关闭,查看 [close event](#event-close). + +### `win.focus()` + +聚焦窗口. + +### `win.isFocused()` + +返回 boolean, 窗口是否聚焦. + +### `win.show()` + +展示并且聚焦窗口. + +### `win.showInactive()` + +展示窗口但是不聚焦. + +### `win.hide()` + +隐藏窗口. + +### `win.isVisible()` + +返回 boolean, 窗口是否可见. + +### `win.maximize()` + +窗口最大化. + +### `win.unmaximize()` + +取消窗口最大化. + +### `win.isMaximized()` + +返回 boolean, 窗口是否最大化. + +### `win.minimize()` + +窗口最小化. 在一些os中,它将在dock中显示. + +### `win.restore()` + +将最小化的窗口恢复为之前的状态. + +### `win.isMinimized()` + +返回 boolean, 窗口是否最小化. + +### `win.setFullScreen(flag)` + +* `flag` Boolean + +设置是否全屏. + +### `win.isFullScreen()` + +返回 boolean, 窗口是否全屏化. + +### `win.setAspectRatio(aspectRatio[, extraSize])` _OS X_ + +* `aspectRatio` 维持部分视图内容窗口的高宽比值. +* `extraSize` Object (可选) - 维持高宽比值时不包含的额外size. + * `width` Integer + * `height` Integer + +由一个窗口来维持高宽比值. `extraSize` 允许开发者使用它,它的单位为像素,不包含在 `aspectRatio` 中.这个 API 可用来区分窗口的size和内容的size . + +想象一个普通可控的HD video 播放器窗口. 假如左边缘有15控制像素,右边缘有25控制像素,在播放器下面有50控制像素.为了在播放器内保持一个 16:9 的高宽比例,我们可以调用这个api传入参数16/9 and +[ 40, 50 ].第二个参数不管网页中的额外的宽度和高度在什么位置,只要它们存在就行.只需要把网页中的所有额外的高度和宽度加起来就行. + +### `win.setBounds(options[, animate])` + +* `options` Object + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer +* `animate` Boolean (可选) _OS X_ + +重新设置窗口的宽高值,并且移动到指定的 `x`, `y` 位置. + +### `win.getBounds()` + +返回一个对象,它包含了窗口的宽,高,x坐标,y坐标. + +### `win.setSize(width, height[, animate])` + +* `width` Integer +* `height` Integer +* `animate` Boolean (可选) _OS X_ + +重新设置窗口的宽高值. + +### `win.getSize()` + +返回一个数组,它包含了窗口的宽,高. + +### `win.setContentSize(width, height[, animate])` + +* `width` Integer +* `height` Integer +* `animate` Boolean (可选) _OS X_ + +重新设置窗口客户端的宽高值(例如网页界面). + +### `win.getContentSize()` + +返回一个数组,它包含了窗口客户端的宽,高. + +### `win.setMinimumSize(width, height)` + +* `width` Integer +* `height` Integer + +设置窗口最小化的宽高值. + +### `win.getMinimumSize()` + +返回一个数组,它包含了窗口最小化的宽,高. + +### `win.setMaximumSize(width, height)` + +* `width` Integer +* `height` Integer + +设置窗口最大化的宽高值. + +### `win.getMaximumSize()` + +返回一个数组,它包含了窗口最大化的宽,高. + +### `win.setResizable(resizable)` + +* `resizable` Boolean + +设置窗口是否可以被用户改变size. + +### `win.isResizable()` + +返回窗口是否可以被用户改变size的状态. + +### `win.setMovable(movable)` _OS X_ _Windows_ + +* `movable` Boolean + +设置窗口是否可以被用户拖动. Linux 无效. + +### `win.isMovable()` _OS X_ _Windows_ + +返回窗口是否可以被用户拖动的状态. Linux 总是返回 `true`. + +### `win.setMinimizable(minimizable)` _OS X_ _Windows_ + +* `minimizable` Boolean + +设置窗口是否可以最小化. Linux 无效. + +### `win.isMinimizable()` _OS X_ _Windows_ + +返回窗口是否可以最小化的状态. Linux 总是返回 `true`. + +### `win.setMaximizable(maximizable)` _OS X_ _Windows_ + +* `maximizable` Boolean + +设置窗口是否可以最大化. Linux 无效. + +### `win.isMaximizable()` _OS X_ _Windows_ + +返回窗口是否可以最大化的状态. Linux 总是返回 `true`. + +### `win.setFullScreenable(fullscreenable)` + +* `fullscreenable` Boolean + +设置点击最大化按钮是否可以全屏或最大化窗口. + +### `win.isFullScreenable()` + +返回点击最大化按钮是否可以全屏或最大化窗口的状态. + +### `win.setClosable(closable)` _OS X_ _Windows_ + +* `closable` Boolean + +设置窗口是否可以人为关闭. Linux 无效. + +### `win.isClosable()` _OS X_ _Windows_ + +返回窗口是否可以人为关闭的状态. Linux 总是返回 `true`. + +### `win.setAlwaysOnTop(flag)` + +* `flag` Boolean + +是否设置这个窗口始终在其他窗口之上.设置之后,这个窗口仍然是一个普通的窗口,不是一个不可以聚焦的工具箱窗口. + +### `win.isAlwaysOnTop()` + +返回当前窗口是否始终在其它窗口之前的状态. + +### `win.center()` + +窗口居中. + +### `win.setPosition(x, y[, animate])` + +* `x` Integer +* `y` Integer +* `animate` Boolean (可选) _OS X_ + +移动窗口到对应的 `x` and `y` 坐标. + +### `win.getPosition()` + +返回一个包含当前窗口位置的数组. + +### `win.setTitle(title)` + +* `title` String + +改变原窗口的title. + +### `win.getTitle()` + +返回原窗口的title. + +**注意:** 界面title可能和窗口title不相同. + +### `win.flashFrame(flag)` + +* `flag` Boolean + +开始或停止显示窗口来获得用户的关注. + +### `win.setSkipTaskbar(skip)` + +* `skip` Boolean + +让窗口不在任务栏中显示. + +### `win.setKiosk(flag)` + +* `flag` Boolean + +进入或离开 kiosk 模式. + +### `win.isKiosk()` + +返回是否进入或离开 kiosk 模式的状态. + +### `win.getNativeWindowHandle()` + +以 `Buffer` 形式返回这个具体平台的窗口的句柄. + +windows上句柄类型为 `HWND` ,OS X `NSView*` , Linux `Window`. + +### `win.hookWindowMessage(message, callback)` _Windows_ + +* `message` Integer +* `callback` Function + +拦截windows 消息,在 WndProc 接收到消息时触发 `callback`函数. + +### `win.isWindowMessageHooked(message)` _Windows_ + +* `message` Integer + +返回 `true` or `false` 来代表是否拦截到消息. + +### `win.unhookWindowMessage(message)` _Windows_ + +* `message` Integer + +不拦截窗口消息. + +### `win.unhookAllWindowMessages()` _Windows_ + +窗口消息全部不拦截. + +### `win.setRepresentedFilename(filename)` _OS X_ + +* `filename` String + +设置窗口当前文件路径,并且将这个文件的图标放在窗口标题栏上. + +### `win.getRepresentedFilename()` _OS X_ + +获取窗口当前文件路径. + +### `win.setDocumentEdited(edited)` _OS X_ + +* `edited` Boolean + +明确指出窗口文档是否可以编辑,如果可以编辑则将标题栏的图标变成灰色. + +### `win.isDocumentEdited()` _OS X_ + +返回当前窗口文档是否可编辑状态. + +### `win.focusOnWebView()` + +### `win.blurWebView()` + +### `win.capturePage([rect, ]callback)` + +* `rect` Object (可选) - 捕获Page位置 + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer +* `callback` Function + +捕获 `rect` 中的page 的快照.完成后将调用回调函数 `callback` 并返回 `image` . `image` 是存储了快照信息的[NativeImage](native-image.md)实例.如果不设置 `rect` 则将捕获所有可见page. + +### `win.print([options])` + +类似 `webContents.print([options])` + +### `win.printToPDF(options, callback)` + +类似 `webContents.printToPDF(options, callback)` + +### `win.loadURL(url[, options])` + +类似 `webContents.loadURL(url[, options])`. + +### `win.reload()` + +类似 `webContents.reload`. + +### `win.setMenu(menu)` _Linux_ _Windows_ + +* `menu` Menu + +设置菜单栏的 `menu` ,设置它为 `null` 则表示不设置菜单栏. + +### `win.setProgressBar(progress)` + +* `progress` Double + +在进度条中设置进度值,有效范围 [0, 1.0]. + +当进度小于0时则不显示进度; +当进度大于0时显示结果不确定. + +在libux上,只支持Unity桌面环境,需要指明 `*.desktop` 文件并且在 `package.json` 中添加文件名字.默认它为 `app.getName().desktop`. + +### `win.setOverlayIcon(overlay, description)` _Windows 7+_ + +* `overlay` [NativeImage](native-image.md) - the icon to display on the bottom +right corner of the taskbar icon. If this parameter is `null`, the overlay is +cleared +* `description` String - a description that will be provided to Accessibility +screen readers + +Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some +sort of application status or to passively notify the user. + +### `win.setHasShadow(hasShadow)` _OS X_ + +* `hasShadow` (Boolean) + +设置窗口是否应该有阴影.在Windows和Linux系统无效. + +### `win.hasShadow()` _OS X_ + +返回设置窗口是否有阴影的状态.在Windows和Linux系统始终返回 +`true`. + +### `win.setThumbarButtons(buttons)` _Windows 7+_ + +* `buttons` Array + +在窗口的任务栏button布局出为缩略图添加一个有特殊button的缩略图工具栏. 返回一个 `Boolean` 对象来指示是否成功添加这个缩略图工具栏. + +因为空间有限,缩略图工具栏上的 button 数量不应该超过7个.一旦设置了,由于平台限制,就不能移动它了.但是你可使用一个空数组来调用api来清除 buttons . + +所有 `buttons` 是一个 `Button` 对象数组: + +* `Button` Object + * `icon` [NativeImage](native-image.md) - 在工具栏上显示的图标. + * `click` Function + * `tooltip` String (可选) - tooltip 文字. + * `flags` Array (可选) - 控制button的状态和行为. 默认它是 `['enabled']`. + +`flags` 是一个数组,它包含下面这些 `String`s: + +* `enabled` - button 为激活状态并且开放给用户. +* `disabled` -button 不可用. 目前它有一个可见的状态来表示它不会响应你的行为. +* `dismissonclick` - 点击button,这个缩略窗口直接关闭. +* `nobackground` - 不绘制边框,仅仅使用图像. +* `hidden` - button 对用户不可见. +* `noninteractive` - button 可用但是不可响应; 也不显示按下的状态. 它的值意味着这是一个在通知单使用 button 的实例. + +### `win.showDefinitionForSelection()` _OS X_ + +在界面查找选中文字时显示弹出字典. + +### `win.setAutoHideMenuBar(hide)` + +* `hide` Boolean + +设置窗口的菜单栏是否可以自动隐藏. 一旦设置了,只有当用户按下 `Alt` 键时则显示. + +如果菜单栏已经可见,调用 `setAutoHideMenuBar(true)` 则不会立刻隐藏. + +### `win.isMenuBarAutoHide()` + +返回窗口的菜单栏是否可以自动隐藏的状态. + +### `win.setMenuBarVisibility(visible)` + +* `visible` Boolean + +设置菜单栏是否可见.如果菜单栏自动隐藏,用户仍然可以按下 `Alt` 键来显示. + +### `win.isMenuBarVisible()` + +返回菜单栏是否可见的状态. + +### `win.setVisibleOnAllWorkspaces(visible)` + +* `visible` Boolean + +设置窗口是否在所有地方都可见. + +**注意:** 这个api 在windows无效. + +### `win.isVisibleOnAllWorkspaces()` + +返回窗口是否在所有地方都可见的状态. + +**注意:** 在 windows上始终返回 false. + +### `win.setIgnoreMouseEvents(ignore)` _OS X_ + +* `ignore` Boolean + +忽略窗口的所有鼠标事件. + +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 \ No newline at end of file From ee61ab2d260f84775698dcb7cdbf5308bc520dbb Mon Sep 17 00:00:00 2001 From: Arek Sredzki Date: Mon, 7 Mar 2016 01:26:36 -0800 Subject: [PATCH 0141/1265] Cache browser visibility state & emit visibilitychange event on change Fixes #3788 --- lib/browser/api/browser-window.js | 12 ++++++++++++ lib/renderer/api/ipc-renderer.js | 2 +- lib/renderer/inspector.js | 2 +- lib/renderer/override.js | 31 +++++++++++++++++++++---------- 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index a9649f853d7..b3e27c58056 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -88,6 +88,18 @@ BrowserWindow.prototype._init = function() { }; })(this)); + // Evented visibilityState changes + this.on('minimize', (function(_this) { + return function() { + return _this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', false); + }; + })(this)); + this.on('restore', (function(_this) { + return function() { + return _this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', true); + }; + })(this)); + // Notify the creation of the window. app.emit('browser-window-created', {}, this); diff --git a/lib/renderer/api/ipc-renderer.js b/lib/renderer/api/ipc-renderer.js index dd614103cfa..e946dc7a4c0 100644 --- a/lib/renderer/api/ipc-renderer.js +++ b/lib/renderer/api/ipc-renderer.js @@ -3,7 +3,7 @@ const v8Util = process.atomBinding('v8_util'); var slice = [].slice; -// Created by init.coffee. +// Created by init.js. const ipcRenderer = v8Util.getHiddenValue(global, 'ipc'); ipcRenderer.send = function() { diff --git a/lib/renderer/inspector.js b/lib/renderer/inspector.js index edec3074b95..d1473c7d1be 100644 --- a/lib/renderer/inspector.js +++ b/lib/renderer/inspector.js @@ -3,7 +3,7 @@ window.onload = function() { InspectorFrontendHost.showContextMenuAtPoint = createMenu; // Use dialog API to override file chooser dialog. - return WebInspector.createFileSelectorElement = createFileSelectorElement; + return (WebInspector.createFileSelectorElement = createFileSelectorElement); }; var convertToMenuTemplate = function(items) { diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 6ff1e80785d..6a025af4ed1 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -3,6 +3,13 @@ const remote = require('electron').remote; var slice = [].slice; +// Cache browser window visibility +var _isVisible = (function() { + var currentWindow; + currentWindow = remote.getCurrentWindow(); + return currentWindow.isMinimized() || !currentWindow.isVisible(); +})(); + // Helper function to resolve relative url. var a = window.top.document.createElement('a'); @@ -30,7 +37,7 @@ var BrowserWindowProxy = (function() { ipcRenderer.once("ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_" + this.guestId, (function(_this) { return function() { BrowserWindowProxy.remove(_this.guestId); - return _this.closed = true; + return (_this.closed = true); }; })(this)); } @@ -87,7 +94,9 @@ window.open = function(url, frameName, features) { ref1 = features.split(/,\s*/); for (i = 0, len = ref1.length; i < len; i++) { feature = ref1[i]; - ref2 = feature.split(/\s*=/), name = ref2[0], value = ref2[1]; + ref2 = feature.split(/\s*=/); + name = ref2[0]; + value = ref2[1]; options[name] = value === 'yes' || value === '1' ? true : value === 'no' || value === '0' ? false : value; } if (options.left) { @@ -168,6 +177,12 @@ if (process.openerId != null) { window.opener = BrowserWindowProxy.getOrCreate(process.openerId); } +ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible) { + _isVisible = isVisible; + + document.dispatchEvent(new Event('visibilitychange')); +}); + ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, message, sourceOrigin) { // Manually dispatch event instead of using postMessage because we also need to // set event.source. @@ -212,19 +227,15 @@ Object.defineProperty(window.history, 'length', { // Make document.hidden and document.visibilityState return the correct value. Object.defineProperty(document, 'hidden', { - get: function() { - var currentWindow; - currentWindow = remote.getCurrentWindow(); - return currentWindow.isMinimized() || !currentWindow.isVisible(); - } + get: !_isVisible }); Object.defineProperty(document, 'visibilityState', { get: function() { - if (document.hidden) { - return "hidden"; - } else { + if (_isVisible) { return "visible"; + } else { + return "hidden"; } } }); From c1267b232072c48b21b55908d5bd699be954b4fa Mon Sep 17 00:00:00 2001 From: Arek Sredzki Date: Tue, 8 Mar 2016 09:36:41 -0800 Subject: [PATCH 0142/1265] Added 'show' & 'hide' events to browser-window, fixed visibilitychange event in renderer --- atom/browser/api/atom_api_window.cc | 8 +++ atom/browser/api/atom_api_window.h | 2 + atom/browser/native_window.h | 2 + atom/browser/native_window_observer.h | 6 ++ atom/browser/native_window_views.cc | 6 ++ docs/api/browser-window.md | 8 +++ lib/browser/api/browser-window.js | 92 ++++++++++++--------------- lib/renderer/override.js | 24 +++++-- 8 files changed, 88 insertions(+), 60 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index ea1d95b79ca..2975980cabe 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -191,6 +191,14 @@ void Window::OnWindowFocus() { Emit("focus"); } +void Window::OnWindowShow() { + Emit("show"); +} + +void Window::OnWindowHide() { + Emit("hide"); +} + void Window::OnWindowMaximize() { Emit("maximize"); } diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 641124f4dfd..d814a48c983 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -58,6 +58,8 @@ class Window : public mate::TrackableObject, void OnWindowClosed() override; void OnWindowBlur() override; void OnWindowFocus() override; + void OnWindowShow() override; + void OnWindowHide() override; void OnWindowMaximize() override; void OnWindowUnmaximize() override; void OnWindowMinimize() override; diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 09fae6c6bcf..a215b9eb4c1 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -210,6 +210,8 @@ class NativeWindow : public base::SupportsUserData, void NotifyWindowClosed(); void NotifyWindowBlur(); void NotifyWindowFocus(); + void NotifyWindowShow(); + void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); diff --git a/atom/browser/native_window_observer.h b/atom/browser/native_window_observer.h index 4af181085a0..e9dbff4292e 100644 --- a/atom/browser/native_window_observer.h +++ b/atom/browser/native_window_observer.h @@ -42,6 +42,12 @@ class NativeWindowObserver { // Called when window gains focus. virtual void OnWindowFocus() {} + // Called when window is shown. + virtual void OnWindowShow() {} + + // Called when window is hidden. + virtual void OnWindowHide() {} + // Called when window state changed. virtual void OnWindowMaximize() {} virtual void OnWindowUnmaximize() {} diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 93eb7b88d89..15f2046364b 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -302,6 +302,8 @@ bool NativeWindowViews::IsFocused() { void NativeWindowViews::Show() { window_->native_widget_private()->ShowWithWindowState(GetRestoredState()); + NotifyWindowShow(); + #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); @@ -311,6 +313,8 @@ void NativeWindowViews::Show() { void NativeWindowViews::ShowInactive() { window_->ShowInactive(); + NotifyWindowShow(); + #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); @@ -320,6 +324,8 @@ void NativeWindowViews::ShowInactive() { void NativeWindowViews::Hide() { window_->Hide(); + NotifyWindowHide(); + #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 6e1bc992539..0595fbc7056 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -245,6 +245,14 @@ Emitted when the window loses focus. Emitted when the window gains focus. +### Event: 'show' + +Emitted when the window is shown. + +### Event: 'hide' + +Emitted when the window is hidden. + ### Event: 'maximize' Emitted when window is maximized. diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index b3e27c58056..139659c2ea2 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -20,7 +20,7 @@ BrowserWindow.prototype._init = function() { } // Make new windows requested by links behave like "window.open" - this.webContents.on('-new-window', function(event, url, frameName) { + this.webContents.on('-new-window', (event, url, frameName) => { var options; options = { show: true, @@ -32,27 +32,21 @@ BrowserWindow.prototype._init = function() { // window.resizeTo(...) // window.moveTo(...) - this.webContents.on('move', (function(_this) { - return function(event, size) { - return _this.setBounds(size); - }; - })(this)); + this.webContents.on('move', (event, title) => { + return this.setBounds(size); + }); // Hide the auto-hide menu when webContents is focused. - this.webContents.on('activate', (function(_this) { - return function() { - if (process.platform !== 'darwin' && _this.isMenuBarAutoHide() && _this.isMenuBarVisible()) { - return _this.setMenuBarVisibility(false); - } - }; - })(this)); + this.webContents.on('activate', () => { + if (process.platform !== 'darwin' && this.isMenuBarAutoHide() && this.isMenuBarVisible()) { + return this.setMenuBarVisibility(false); + } + }); // Forward the crashed event. - this.webContents.on('crashed', (function(_this) { - return function() { - return _this.emit('crashed'); - }; - })(this)); + this.webContents.on('crashed', () => { + return this.emit('crashed'); + }); // Change window title to page title. this.webContents.on('page-title-updated', (event, title) => { @@ -77,48 +71,40 @@ BrowserWindow.prototype._init = function() { }); // Redirect focus/blur event to app instance too. - this.on('blur', (function(_this) { - return function(event) { - return app.emit('browser-window-blur', event, _this); - }; - })(this)); - this.on('focus', (function(_this) { - return function(event) { - return app.emit('browser-window-focus', event, _this); - }; - })(this)); + this.on('blur', (event) => { + return app.emit('browser-window-blur', event, this); + }); + this.on('focus', (event) => { + return app.emit('browser-window-focus', event, this); + }); // Evented visibilityState changes - this.on('minimize', (function(_this) { - return function() { - return _this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', false); - }; - })(this)); - this.on('restore', (function(_this) { - return function() { - return _this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', true); - }; - })(this)); + this.on('show', () => { + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', true, this.isMinimized()); + }); + this.on('hide', () => { + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', false, this.isMinimized()); + }); + this.on('minimize', () => { + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), true); + }); + this.on('restore', () => { + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), false); + }); // Notify the creation of the window. app.emit('browser-window-created', {}, this); // Be compatible with old APIs. - this.webContents.on('devtools-focused', (function(_this) { - return function() { - return _this.emit('devtools-focused'); - }; - })(this)); - this.webContents.on('devtools-opened', (function(_this) { - return function() { - return _this.emit('devtools-opened'); - }; - })(this)); - this.webContents.on('devtools-closed', (function(_this) { - return function() { - return _this.emit('devtools-closed'); - }; - })(this)); + this.webContents.on('devtools-focused', () => { + return this.emit('devtools-focused'); + }); + this.webContents.on('devtools-opened', () => { + return this.emit('devtools-opened'); + }); + this.webContents.on('devtools-closed', () => { + return this.emit('devtools-closed'); + }); return Object.defineProperty(this, 'devToolsWebContents', { enumerable: true, configurable: false, diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 6a025af4ed1..2b0e48b3dd3 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -4,10 +4,13 @@ const remote = require('electron').remote; var slice = [].slice; // Cache browser window visibility -var _isVisible = (function() { +var _isVisible = true; +var _isMinimized = false; +(function() { var currentWindow; currentWindow = remote.getCurrentWindow(); - return currentWindow.isMinimized() || !currentWindow.isVisible(); + _isVisible = currentWindow.isVisible(); + _isMinimized = currentWindow.isMinimized(); })(); // Helper function to resolve relative url. @@ -177,10 +180,15 @@ if (process.openerId != null) { window.opener = BrowserWindowProxy.getOrCreate(process.openerId); } -ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible) { - _isVisible = isVisible; +ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { + var hasChanged = _isVisible != isVisible || _isMinimized != isMinimized; + + if (hasChanged) { + _isVisible = isVisible; + _isMinimized = isMinimized; - document.dispatchEvent(new Event('visibilitychange')); + document.dispatchEvent(new Event('visibilitychange')); + } }); ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, message, sourceOrigin) { @@ -227,12 +235,14 @@ Object.defineProperty(window.history, 'length', { // Make document.hidden and document.visibilityState return the correct value. Object.defineProperty(document, 'hidden', { - get: !_isVisible + get: function () { + return _isMinimized || !_isVisible; + } }); Object.defineProperty(document, 'visibilityState', { get: function() { - if (_isVisible) { + if (_isVisible && !_isMinimized) { return "visible"; } else { return "hidden"; From fcc1f4d7ed1fd0978e68f72c405c8ee5f179e519 Mon Sep 17 00:00:00 2001 From: Arek Sredzki Date: Tue, 8 Mar 2016 11:11:17 -0800 Subject: [PATCH 0143/1265] Finalized browser-window show & hide events, added tests & fixed os x implementation --- atom/browser/native_window.cc | 8 +++++ atom/browser/native_window_mac.mm | 15 ++++++++++ lib/browser/api/browser-window.js | 10 +++---- spec/api-browser-window-spec.js | 49 ++++++++++++++++++++++++++++--- 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 98b3d725a9a..56cfdea54c5 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -428,6 +428,14 @@ void NativeWindow::NotifyWindowFocus() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowFocus()); } +void NativeWindow::NotifyWindowShow() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowShow()); +} + +void NativeWindow::NotifyWindowHide() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowHide()); +} + void NativeWindow::NotifyWindowMaximize() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowMaximize()); } diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 6bbd9fd5001..a8f7bc5c168 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -79,6 +79,21 @@ bool ScopedDisableResize::disable_resize_ = false; return self; } +- (void)windowDidChangeOcclusionState:(NSNotification *)notification { + // notification.object is the window that changed its state. + // It's safe to use self.window instead if you don't assign one delegate to many windows + NSWindow *window = notification.object; + + // check occlusion binary flag + if (window.occlusionState & NSWindowOcclusionStateVisible) { + // The app is visible + shell_->NotifyWindowShow(); + } else { + // The app is not visible + shell_->NotifyWindowHide(); + } +} + - (void)windowDidBecomeMain:(NSNotification*)notification { content::WebContents* web_contents = shell_->web_contents(); if (!web_contents) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 139659c2ea2..1d2f665e5d0 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -32,7 +32,7 @@ BrowserWindow.prototype._init = function() { // window.resizeTo(...) // window.moveTo(...) - this.webContents.on('move', (event, title) => { + this.webContents.on('move', (event, size) => { return this.setBounds(size); }); @@ -80,16 +80,16 @@ BrowserWindow.prototype._init = function() { // Evented visibilityState changes this.on('show', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', true, this.isMinimized()); + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('hide', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', false, this.isMinimized()); + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('minimize', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), true); + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('restore', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), false); + return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); // Notify the creation of the window. diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 731ae1cb86f..9a6be6865da 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -120,14 +120,55 @@ describe('browser-window module', function() { }); describe('BrowserWindow.show()', function() { - it('should focus on window', function() { - if (isCI) { - return; - } + if (isCI) { + return; + } + it('should focus on window', function() { w.show(); assert(w.isFocused()); }); + + it('should make the window visible', function() { + w.show(); + assert(w.isVisible()); + }); + + it('emits when window is shown', function(done) { + this.timeout(10000); + w.once('show', function() { + assert.equal(w.isVisible(), true); + done(); + }); + w.show(); + }); + }); + + describe('BrowserWindow.hide()', function() { + if (isCI) { + return; + } + + it('should defocus on window', function() { + w.hide(); + assert(!w.isFocused()); + }); + + it('should make the window not visible', function() { + w.show(); + w.hide(); + assert(!w.isVisible()); + }); + + it('emits when window is hidden', function(done) { + this.timeout(10000); + w.show(); + w.once('hide', function() { + assert.equal(w.isVisible(), false); + done(); + }); + w.hide(); + }); }); describe('BrowserWindow.showInactive()', function() { From 256c2684ee13cea01b064dae3b3d8aeb80a2d4dc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 10:25:12 +0900 Subject: [PATCH 0144/1265] spec: Do not enter fullscreen in travis on OS X It is too flaky --- spec/webview-spec.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index cd2be69d737..3579415a0b4 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -548,11 +548,10 @@ describe(' tag', function() { }); describe('executeJavaScript', function() { - if (process.env.TRAVIS !== 'true') { - return; - } - it('should support user gesture', function(done) { + if (process.env.TRAVIS !== 'true' || process.platform == 'darwin') + return done(); + var listener = function() { webview.removeEventListener('enter-html-full-screen', listener); done(); From 83809cef0944d0a9590d921c70f38c974b41a551 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 10:47:15 +0900 Subject: [PATCH 0145/1265] Update to master branch of brightray and libchromiumcontent --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index 5077bee89dc..c1f3bb4ecf4 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 5077bee89dc3403982e9a5c59cc0a2218b2d4610 +Subproject commit c1f3bb4ecf4cacb33bf56b9ebd3656a4defbeb64 From d564727583b405fdeec53a320ffdc41bc7ed5c28 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 11:17:02 +0900 Subject: [PATCH 0146/1265] spec: Increase timeout for executeJavaScript --- spec/webview-spec.js | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 3579415a0b4..ba3913e2e47 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -568,6 +568,7 @@ describe(' tag', function() { }); it('can return the result of the executed script', function(done) { + this.timeout(50000); var listener = function() { var jsScript = "'4'+2"; webview.executeJavaScript(jsScript, false, function(result) { From d25d1f3f8b06f081e30f4ed3ce2cfd418e7e97e2 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Fri, 11 Mar 2016 11:53:04 +0800 Subject: [PATCH 0147/1265] add content-tracing && update browser-window --- docs-translations/zh-CN/api/browser-window.md | 50 ++++--- .../zh-CN/api/content-tracing.md | 129 ++++++++++++++++++ 2 files changed, 152 insertions(+), 27 deletions(-) create mode 100644 docs-translations/zh-CN/api/content-tracing.md diff --git a/docs-translations/zh-CN/api/browser-window.md b/docs-translations/zh-CN/api/browser-window.md index 66ae76cff91..5ed0069caf4 100644 --- a/docs-translations/zh-CN/api/browser-window.md +++ b/docs-translations/zh-CN/api/browser-window.md @@ -258,11 +258,11 @@ someWindow.on('app-command', function(e, cmd) { ### `BrowserWindow.getAllWindows()` -返回一个所有已经打开了的窗口的对象数组. +返回一个所有已经打开了窗口的对象数组. ### `BrowserWindow.getFocusedWindow()` -返回应用当前聚焦窗口,如果没有就返回 `null`. +返回应用当前获得焦点窗口,如果没有就返回 `null`. ### `BrowserWindow.fromWebContents(webContents)` @@ -325,19 +325,19 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.focus()` -聚焦窗口. +窗口获得焦点. ### `win.isFocused()` -返回 boolean, 窗口是否聚焦. +返回 boolean, 窗口是否获得焦点. ### `win.show()` -展示并且聚焦窗口. +展示并且使窗口获得焦点. ### `win.showInactive()` -展示窗口但是不聚焦. +展示窗口但是不获得焦点. ### `win.hide()` @@ -462,7 +462,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isResizable()` -返回窗口是否可以被用户改变size的状态. +返回 boolean,窗口是否可以被用户改变size. ### `win.setMovable(movable)` _OS X_ _Windows_ @@ -472,7 +472,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isMovable()` _OS X_ _Windows_ -返回窗口是否可以被用户拖动的状态. Linux 总是返回 `true`. +返回 boolean,窗口是否可以被用户拖动. Linux 总是返回 `true`. ### `win.setMinimizable(minimizable)` _OS X_ _Windows_ @@ -482,7 +482,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isMinimizable()` _OS X_ _Windows_ -返回窗口是否可以最小化的状态. Linux 总是返回 `true`. +返回 boolean,窗口是否可以最小化. Linux 总是返回 `true`. ### `win.setMaximizable(maximizable)` _OS X_ _Windows_ @@ -492,7 +492,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isMaximizable()` _OS X_ _Windows_ -返回窗口是否可以最大化的状态. Linux 总是返回 `true`. +返回 boolean,窗口是否可以最大化. Linux 总是返回 `true`. ### `win.setFullScreenable(fullscreenable)` @@ -502,7 +502,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isFullScreenable()` -返回点击最大化按钮是否可以全屏或最大化窗口的状态. +返回 boolean,点击最大化按钮是否可以全屏或最大化窗口. ### `win.setClosable(closable)` _OS X_ _Windows_ @@ -512,17 +512,17 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isClosable()` _OS X_ _Windows_ -返回窗口是否可以人为关闭的状态. Linux 总是返回 `true`. +返回 boolean,窗口是否可以人为关闭. Linux 总是返回 `true`. ### `win.setAlwaysOnTop(flag)` * `flag` Boolean -是否设置这个窗口始终在其他窗口之上.设置之后,这个窗口仍然是一个普通的窗口,不是一个不可以聚焦的工具箱窗口. +是否设置这个窗口始终在其他窗口之上.设置之后,这个窗口仍然是一个普通的窗口,不是一个不可以获得焦点的工具箱窗口. ### `win.isAlwaysOnTop()` -返回当前窗口是否始终在其它窗口之前的状态. +返回 boolean,当前窗口是否始终在其它窗口之前. ### `win.center()` @@ -572,7 +572,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.isKiosk()` -返回是否进入或离开 kiosk 模式的状态. +返回 boolean,是否进入或离开 kiosk 模式. ### `win.getNativeWindowHandle()` @@ -621,7 +621,7 @@ windows上句柄类型为 `HWND` ,OS X `NSView*` , Linux `Window`. ### `win.isDocumentEdited()` _OS X_ -返回当前窗口文档是否可编辑状态. +返回 boolean,当前窗口文档是否可编辑. ### `win.focusOnWebView()` @@ -673,14 +673,10 @@ windows上句柄类型为 `HWND` ,OS X `NSView*` , Linux `Window`. ### `win.setOverlayIcon(overlay, description)` _Windows 7+_ -* `overlay` [NativeImage](native-image.md) - the icon to display on the bottom -right corner of the taskbar icon. If this parameter is `null`, the overlay is -cleared -* `description` String - a description that will be provided to Accessibility -screen readers +* `overlay` [NativeImage](native-image.md) - 在底部任务栏右边显示图标. +* `description` String - 描述. -Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some -sort of application status or to passively notify the user. +向当前任务栏添加一个 16 x 16 像素的图标,通常用来覆盖一些应用的状态,或者直接来提示用户. ### `win.setHasShadow(hasShadow)` _OS X_ @@ -690,7 +686,7 @@ sort of application status or to passively notify the user. ### `win.hasShadow()` _OS X_ -返回设置窗口是否有阴影的状态.在Windows和Linux系统始终返回 +返回 boolean,设置窗口是否有阴影.在Windows和Linux系统始终返回 `true`. ### `win.setThumbarButtons(buttons)` _Windows 7+_ @@ -732,7 +728,7 @@ sort of application status or to passively notify the user. ### `win.isMenuBarAutoHide()` -返回窗口的菜单栏是否可以自动隐藏的状态. +返回 boolean,窗口的菜单栏是否可以自动隐藏. ### `win.setMenuBarVisibility(visible)` @@ -742,7 +738,7 @@ sort of application status or to passively notify the user. ### `win.isMenuBarVisible()` -返回菜单栏是否可见的状态. +返回 boolean,菜单栏是否可见. ### `win.setVisibleOnAllWorkspaces(visible)` @@ -754,7 +750,7 @@ sort of application status or to passively notify the user. ### `win.isVisibleOnAllWorkspaces()` -返回窗口是否在所有地方都可见的状态. +返回 boolean,窗口是否在所有地方都可见. **注意:** 在 windows上始终返回 false. diff --git a/docs-translations/zh-CN/api/content-tracing.md b/docs-translations/zh-CN/api/content-tracing.md new file mode 100644 index 00000000000..fd1edc9bc2f --- /dev/null +++ b/docs-translations/zh-CN/api/content-tracing.md @@ -0,0 +1,129 @@ +# contentTracing + +`content-tracing` 模块是用来收集由底层的Chromium content 模块 产生的搜索数据. 这个模块不具备web接口,所有需要我们在chrome浏览器中添加 `chrome://tracing/` 来加载生成文件从而查看结果. + +```javascript +const contentTracing = require('electron').contentTracing; + +const options = { + categoryFilter: '*', + traceOptions: 'record-until-full,enable-sampling' +} + +contentTracing.startRecording(options, function() { + console.log('Tracing started'); + + setTimeout(function() { + contentTracing.stopRecording('', function(path) { + console.log('Tracing data recorded to ' + path); + }); + }, 5000); +}); +``` + +## 方法 + + `content-tracing` 模块的方法如下: + +### `contentTracing.getCategories(callback)` + +* `callback` Function + +获得一组分类组. 分类组可以更改为新的代码路径。 + +一旦所有的子进程都接受到了`getCategories`方法请求, 分类组将调用 `callback`. + +### `contentTracing.startRecording(options, callback)` + +* `options` Object + * `categoryFilter` String + * `traceOptions` String +* `callback` Function + +开始向所有进程进行记录.(recording) + +一旦收到可以开始记录的请求,记录将会立马启动并且在子进程是异步记录听的. 当所有的子进程都收到 `startRecording` 请求的时候,`callback` 将会被调用. + +`categoryFilter`是一个过滤器,它用来控制那些分类组应该被用来查找.过滤器应当有一个可选的 `-` 前缀来排除匹配的分类组.不允许同一个列表既是包含又是排斥. + +例子: + +* `test_MyTest*`, +* `test_MyTest*,test_OtherStuff`, +* `"-excluded_category1,-excluded_category2` + +`traceOptions` 控制着哪种查找应该被启动,这是一个用逗号分隔的列表.可用参数如下: + +* `record-until-full` +* `record-continuously` +* `trace-to-console` +* `enable-sampling` +* `enable-systrace` + +前3个参数是来查找记录模块,并且以后都互斥.如果在`traceOptions` 中超过一个跟踪 +记录模式,那最后一个的优先级最高.如果没有指明跟踪 +记录模式,那么它默认为 `record-until-full`. + +在 `traceOptions` 中的参数被解析应用之前,查找参数初始化默认为 (`record_mode` 设置为 +`record-until-full`, `enable_sampling` 和 `enable_systrace` 设置为 `false`). + +### `contentTracing.stopRecording(resultFilePath, callback)` + +* `resultFilePath` String +* `callback` Function + +停止对所有子进程的记录. + +子进程通常缓存查找数据,并且仅仅将数据截取和发送给主进程.这有利于在通过 IPC 发送查找数据之前减小查找时的运行开销,这样做很有价值.因此,发送查找数据,我们应当异步通知所有子进程来截取任何待查找的数据. + +一旦所有子进程接收到了 `stopRecording` 请求,将调用 `callback` ,并且返回一个包含查找数据的文件. + +如果 `resultFilePath` 不为空,那么将把查找数据写入其中,否则写入一个临时文件.实际文件路径如果不为空,则将调用 `callback` . + +### `contentTracing.startMonitoring(options, callback)` + +* `options` Object + * `categoryFilter` String + * `traceOptions` String +* `callback` Function + +开始向所有进程进行监听.(monitoring) + +一旦收到可以开始监听的请求,记录将会立马启动并且在子进程是异步记监听的. 当所有的子进程都收到 `startMonitoring` 请求的时候,`callback` 将会被调用. + +### `contentTracing.stopMonitoring(callback)` + +* `callback` Function + +停止对所有子进程的监听. + +一旦所有子进程接收到了 `stopMonitoring` 请求,将调用 `callback` . + +### `contentTracing.captureMonitoringSnapshot(resultFilePath, callback)` + +* `resultFilePath` String +* `callback` Function + +获取当前监听的查找数据. + +子进程通常缓存查找数据,并且仅仅将数据截取和发送给主进程.因为如果直接通过 IPC 来发送查找数据的代价昂贵,我们宁愿避免不必要的查找运行开销.因此,为了停止查找,我们应当异步通知所有子进程来截取任何待查找的数据. + +一旦所有子进程接收到了 `captureMonitoringSnapshot` 请求,将调用 `callback` ,并且返回一个包含查找数据的文件. + +### `contentTracing.getTraceBufferUsage(callback)` + +* `callback` Function + +通过查找 buffer 进程来获取百分比最大使用量.当确定了TraceBufferUsage 的值确定的时候,就调用 `callback` . + +### `contentTracing.setWatchEvent(categoryName, eventName, callback)` + +* `categoryName` String +* `eventName` String +* `callback` Function + +任意时刻在任何进程上指定事件发生时将调用 `callback` . + +### `contentTracing.cancelWatchEvent()` + +取消 watch 事件. 如果启动查找,这或许会造成 watch 事件的回调函数 出错. \ No newline at end of file From 704b8335aafad69c78d5dc75528133f3b89f36fe Mon Sep 17 00:00:00 2001 From: Max Beatty Date: Thu, 10 Mar 2016 21:45:51 -0800 Subject: [PATCH 0148/1265] Add blur method to window ref #4724 --- atom/browser/api/atom_api_window.cc | 5 +++++ atom/browser/api/atom_api_window.h | 1 + docs/api/browser-window.md | 4 ++++ spec/api-browser-window-spec.js | 7 +++++++ 4 files changed, 17 insertions(+) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index ea1d95b79ca..fb5f3eddc7f 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -294,6 +294,10 @@ void Window::Focus() { window_->Focus(true); } +void Window::Blur() { + window_->Focus(false); +} + bool Window::IsFocused() { return window_->IsFocused(); } @@ -688,6 +692,7 @@ void Window::BuildPrototype(v8::Isolate* isolate, .MakeDestroyable() .SetMethod("close", &Window::Close) .SetMethod("focus", &Window::Focus) + .SetMethod("blur", &Window::Blur) .SetMethod("isFocused", &Window::IsFocused) .SetMethod("show", &Window::Show) .SetMethod("showInactive", &Window::ShowInactive) diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 641124f4dfd..c9840900515 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -83,6 +83,7 @@ class Window : public mate::TrackableObject, // APIs for NativeWindow. void Close(); void Focus(); + void Blur(); bool IsFocused(); void Show(); void ShowInactive(); diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 6e1bc992539..b21459659da 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -397,6 +397,10 @@ the [close event](#event-close). Focus on the window. +### `win.blur()` + +Remove focus on the window. + ### `win.isFocused()` Returns a boolean, whether the window is focused. diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 731ae1cb86f..3474a859cf0 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -145,6 +145,13 @@ describe('browser-window module', function() { }); }); + describe('BrowserWindow.blur()', function() { + it('removes focus from window', function() { + w.blur(); + assert(!w.isFocused()); + }); + }); + describe('BrowserWindow.capturePage(rect, callback)', function() { it('calls the callback with a Buffer', function(done) { w.capturePage({ From 328583575d4977dbf90db65b96d2878599f0d7c4 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Fri, 11 Mar 2016 15:09:08 +0800 Subject: [PATCH 0149/1265] modify again and add dialog.md --- docs-translations/zh-CN/api/browser-window.md | 2 - docs-translations/zh-CN/api/dialog.md | 94 +++++++++++++++++++ docs-translations/zh-CN/api/window-open.md | 4 +- 3 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 docs-translations/zh-CN/api/dialog.md diff --git a/docs-translations/zh-CN/api/browser-window.md b/docs-translations/zh-CN/api/browser-window.md index 5ed0069caf4..6e486406d63 100644 --- a/docs-translations/zh-CN/api/browser-window.md +++ b/docs-translations/zh-CN/api/browser-window.md @@ -197,12 +197,10 @@ window.onbeforeunload = function(e) { ### Event: 'restore' 在窗口从最小化恢复的时候触发. -Emitted when the window is restored from minimized state. ### Event: 'resize' 在窗口size改变的时候触发. -Emitted when the window is getting resized. ### Event: 'move' diff --git a/docs-translations/zh-CN/api/dialog.md b/docs-translations/zh-CN/api/dialog.md new file mode 100644 index 00000000000..3e77eeaa2a5 --- /dev/null +++ b/docs-translations/zh-CN/api/dialog.md @@ -0,0 +1,94 @@ +# dialog + +`dialog` 模块提供了api来展示原生的系统对话框,例如打开文件框,alert框,所以web应用可以给用户带来跟系统应用相同的体验. + +对话框例子,展示了选择文件和目录: + +```javascript +var win = ...; // BrowserWindow in which to show the dialog +const dialog = require('electron').dialog; +console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]})); +``` + +**OS X 上的注意事项**: 如果你想像sheets一样展示对话框,只需要在`browserWindow` 参数中提供一个 `BrowserWindow` 的引用对象. + +## 方法 + +`dialog` 模块有以下方法: + +### `dialog.showOpenDialog([browserWindow, ]options[, callback])` + +* `browserWindow` BrowserWindow (可选) +* `options` Object + * `title` String + * `defaultPath` String + * `filters` Array + * `properties` Array - 包含了对话框的特性值, 可以包含 `openFile`, `openDirectory`, `multiSelections` and + `createDirectory` +* `callback` Function (可选) + +成功使用这个方法的话,就返回一个可供用户选择的文件路径数组,失败返回 `undefined`. + +`filters` 当需要限定用户的行为的时候,指定一个文件数组给用户展示或选择. 例如: + +```javascript +{ + filters: [ + { name: 'Images', extensions: ['jpg', 'png', 'gif'] }, + { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }, + { name: 'Custom File Type', extensions: ['as'] }, + { name: 'All Files', extensions: ['*'] } + ] +} +``` + +`extensions` 数组应当只包含扩展名,不应该包含通配符或'.'号 (例如 +`'png'` 正确,但是 `'.png'` 和 `'*.png'` 不正确). 展示全部文件的话, 使用 +`'*'` 通配符 (不支持其他通配符). + +如果 `callback` 被调用, 将异步调用 API ,并且结果将用过 `callback(filenames)` 展示. + +**注意:** 在 Windows 和 Linux ,一个打开的 dialog 不能既是文件选择框又是目录选择框, 所以如果在这些平台上设置 `properties` 的值为 +`['openFile', 'openDirectory']` , 将展示一个目录选择框. + +### `dialog.showSaveDialog([browserWindow, ]options[, callback])` + +* `browserWindow` BrowserWindow (可选) +* `options` Object + * `title` String + * `defaultPath` String + * `filters` Array +* `callback` Function (可选) + +成功使用这个方法的话,就返回一个可供用户选择的文件路径数组,失败返回 `undefined`. + +`filters` 指定展示一个文件类型数组, 例子 +`dialog.showOpenDialog` . + +如果 `callback` 被调用, 将异步调用 API ,并且结果将用过 `callback(filenames)` 展示. + +### `dialog.showMessageBox([browserWindow, ]options[, callback])` + +* `browserWindow` BrowserWindow (可选) +* `options` Object + * `type` String - 可以是 `"none"`, `"info"`, `"error"`, `"question"` 或 + `"warning"`. 在 Windows, "question" 与 "info" 展示图标相同, 除非你使用 "icon" 参数. + * `buttons` Array - buttons 内容,数组. + * `defaultId` Integer - 在message box 对话框打开的时候,设置默认button选中,值为在 buttons 数组中的button索引. + * `title` String - message box 的标题,一些平台不显示. + * `message` String - message box 内容. + * `detail` String - 额外信息. + * `icon` [NativeImage](native-image.md) + * `cancelId` Integer - 当用户关闭对话框的时候,不是通过点击对话框的button,就返回值.默认值为对应 "cancel" 或 "no" 标签button 的索引值, 或者如果没有这种button,就返回0. 在 OS X 和 Windows 上, "Cancel" button 的索引值将一直是 `cancelId`, 不管之前是不是特别指出的. + * `noLink` Boolean - 在 Windows ,Electron 将尝试识别哪个button 是普通 button (如 "Cancel" 或 "Yes"), 然后再对话框中以链接命令(command links)方式展现其它的 button . 这能让对话框展示得很炫酷.如果你不喜欢这种效果,你可以设置 `noLink` 为 `true`. +* `callback` Function + +展示 message box, 它会阻塞进程,直到 message box 关闭为止.返回点击按钮的索引值. + +如果 `callback` 被调用, 将异步调用 API ,并且结果将用过 `callback(response)` 展示. + +### `dialog.showErrorBox(title, content)` + +展示一个传统的包含错误信息的对话框. + +在 `app` 模块触发 `ready` 事件之前,这个 api 可以被安全调用,通常它被用来在启动的早期阶段报告错误. 在 Linux 上,如果在 `app` 模块触发 `ready` 事件之前调用,message 将会被触发显示stderr,并且没有实际GUI 框显示. \ No newline at end of file diff --git a/docs-translations/zh-CN/api/window-open.md b/docs-translations/zh-CN/api/window-open.md index a8ef042b0e3..069e2c35226 100644 --- a/docs-translations/zh-CN/api/window-open.md +++ b/docs-translations/zh-CN/api/window-open.md @@ -30,7 +30,7 @@ ### `BrowserWindowProxy.blur()` -取消对子窗口的聚焦. +子窗口的失去焦点. ### `BrowserWindowProxy.close()` 强行关闭子窗口,忽略卸载事件. @@ -47,7 +47,7 @@ ### `BrowserWindowProxy.focus()` -聚焦子窗口(让其现实在最前). +子窗口获得焦点(让其显示在最前). ### `BrowserWindowProxy.postMessage(message, targetOrigin)` From fe248ac03f796fbc84be3abbef14de3b3b3de931 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Fri, 11 Mar 2016 16:05:02 +0800 Subject: [PATCH 0150/1265] add ipc-main first --- docs-translations/zh-CN/api/ipc-main.md | 85 +++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 docs-translations/zh-CN/api/ipc-main.md diff --git a/docs-translations/zh-CN/api/ipc-main.md b/docs-translations/zh-CN/api/ipc-main.md new file mode 100644 index 00000000000..aef9c454a06 --- /dev/null +++ b/docs-translations/zh-CN/api/ipc-main.md @@ -0,0 +1,85 @@ +# ipcMain + +`ipcMain` 模块是类 +[EventEmitter](https://nodejs.org/api/events.html) 的实例.当在主进程中使用它的时候,它控制着由渲染进程(web page)发送过来的异步或同步消息.从渲染进程发送过来的消息将触发事件. + +## 发送消息 + +同样也可以从主进程向渲染进程发送消息,查看更多 [webContents.send][web-contents-send] . + +* 发送消息,事件名为 `channel`. +* 回应同步消息, 你可以设置 `event.returnValue`. +* 回应异步消息, 你可以使用 + `event.sender.send(...)`. + +一个例子,在主进程和渲染进程之间发送和处理消息: + +```javascript +// In main process. +const ipcMain = require('electron').ipcMain; +ipcMain.on('asynchronous-message', function(event, arg) { + console.log(arg); // prints "ping" + event.sender.send('asynchronous-reply', 'pong'); +}); + +ipcMain.on('synchronous-message', function(event, arg) { + console.log(arg); // prints "ping" + event.returnValue = 'pong'; +}); +``` + +```javascript +// In renderer process (web page). +const ipcRenderer = require('electron').ipcRenderer; +console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong" + +ipcRenderer.on('asynchronous-reply', function(event, arg) { + console.log(arg); // prints "pong" +}); +ipcRenderer.send('asynchronous-message', 'ping'); +``` + +## 监听消息 + +`ipcMain` 模块有如下监听事件方法: + +### `ipcMain.on(channel, listener)` + +* `channel` String +* `listener` Function + +监听 `channel`, 当新消息到达,将通过 `listener(event, args...)` 调用 `listener`. + +### `ipcMain.once(channel, listener)` + +* `channel` String +* `listener` Function + +为事件添加一个一次性用的`listener` 函数.这个 `listener` 只有在下次的消息到达 `channel` 时被请求调用,之后就被删除了. + +### `ipcMain.removeListener(channel, listener)` + +* `channel` String +* `listener` Function + +为特定的 `channel` 从监听队列中删除特定的 `listener` 监听者. + +### `ipcMain.removeAllListeners([channel])` + +* `channel` String (可选) + +删除所有监听者,或特指的 `channel` 的所有监听者. + +## 事件对象 + +传递给 `callback` 的 `event` 对象有如下方法: + +### `event.returnValue` + +将此设置为在一个同步消息中返回的值. + +### `event.sender` + +返回发送消息的 `webContents` ,你可以调用 `event.sender.send` 来回复异步消息,更多信息 [webContents.send][web-contents-send]. + +[web-contents-send]: web-contents.md#webcontentssendchannel-arg1-arg2- \ No newline at end of file From 3e04884a578bbc62a1c25b4ebdfbcd76552d7f08 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Fri, 11 Mar 2016 17:25:38 +0800 Subject: [PATCH 0151/1265] add menu.md first --- docs-translations/zh-CN/api/menu.md | 351 ++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 docs-translations/zh-CN/api/menu.md diff --git a/docs-translations/zh-CN/api/menu.md b/docs-translations/zh-CN/api/menu.md new file mode 100644 index 00000000000..3a4e7e5c24e --- /dev/null +++ b/docs-translations/zh-CN/api/menu.md @@ -0,0 +1,351 @@ +# 菜单 + +`menu` 类可以用来创建原生菜单,它可用作应用菜单和 +[context 菜单](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/ContextMenus). + +这个模块是一个主进程的模块,并且可以通过 `remote` 模块给渲染进程调用. + +每个菜单有一个或几个菜单项 [menu items](menu-item.md),并且每个菜单项可以有子菜单. + +下面这个例子是在网页(渲染进程)中通过 [remote](remote.md) 模块动态创建的菜单,并且右键显示: + +```html + + +``` + +例子,在渲染进程中使用模板api创建应用菜单: + +```javascript +var template = [ + { + label: 'Edit', + submenu: [ + { + label: 'Undo', + accelerator: 'CmdOrCtrl+Z', + role: 'undo' + }, + { + label: 'Redo', + accelerator: 'Shift+CmdOrCtrl+Z', + role: 'redo' + }, + { + type: 'separator' + }, + { + label: 'Cut', + accelerator: 'CmdOrCtrl+X', + role: 'cut' + }, + { + label: 'Copy', + accelerator: 'CmdOrCtrl+C', + role: 'copy' + }, + { + label: 'Paste', + accelerator: 'CmdOrCtrl+V', + role: 'paste' + }, + { + label: 'Select All', + accelerator: 'CmdOrCtrl+A', + role: 'selectall' + }, + ] + }, + { + label: 'View', + submenu: [ + { + label: 'Reload', + accelerator: 'CmdOrCtrl+R', + click: function(item, focusedWindow) { + if (focusedWindow) + focusedWindow.reload(); + } + }, + { + label: 'Toggle Full Screen', + accelerator: (function() { + if (process.platform == 'darwin') + return 'Ctrl+Command+F'; + else + return 'F11'; + })(), + click: function(item, focusedWindow) { + if (focusedWindow) + focusedWindow.setFullScreen(!focusedWindow.isFullScreen()); + } + }, + { + label: 'Toggle Developer Tools', + accelerator: (function() { + if (process.platform == 'darwin') + return 'Alt+Command+I'; + else + return 'Ctrl+Shift+I'; + })(), + click: function(item, focusedWindow) { + if (focusedWindow) + focusedWindow.toggleDevTools(); + } + }, + ] + }, + { + label: 'Window', + role: 'window', + submenu: [ + { + label: 'Minimize', + accelerator: 'CmdOrCtrl+M', + role: 'minimize' + }, + { + label: 'Close', + accelerator: 'CmdOrCtrl+W', + role: 'close' + }, + ] + }, + { + label: 'Help', + role: 'help', + submenu: [ + { + label: 'Learn More', + click: function() { require('electron').shell.openExternal('http://electron.atom.io') } + }, + ] + }, +]; + +if (process.platform == 'darwin') { + var name = require('electron').remote.app.getName(); + template.unshift({ + label: name, + submenu: [ + { + label: 'About ' + name, + role: 'about' + }, + { + type: 'separator' + }, + { + label: 'Services', + role: 'services', + submenu: [] + }, + { + type: 'separator' + }, + { + label: 'Hide ' + name, + accelerator: 'Command+H', + role: 'hide' + }, + { + label: 'Hide Others', + accelerator: 'Command+Alt+H', + role: 'hideothers' + }, + { + label: 'Show All', + role: 'unhide' + }, + { + type: 'separator' + }, + { + label: 'Quit', + accelerator: 'Command+Q', + click: function() { app.quit(); } + }, + ] + }); + // Window menu. + template[3].submenu.push( + { + type: 'separator' + }, + { + label: 'Bring All to Front', + role: 'front' + } + ); +} + +var menu = Menu.buildFromTemplate(template); +Menu.setApplicationMenu(menu); +``` + +## 类: Menu + +### `new Menu()` + +创建一个新的菜单. + +## 方法 + +`菜单` 类有如下方法: + +### `Menu.setApplicationMenu(menu)` + +* `menu` Menu + +在 OS X 上设置应用菜单 `menu` . +在windows 和 linux,是为每个窗口都在其顶部设置菜单 `menu`. + +### `Menu.sendActionToFirstResponder(action)` _OS X_ + +* `action` String + +发送 `action` 给应用的第一个响应器.这个用来模仿 Cocoa 菜单的默认行为,通常你只需要使用 `MenuItem` 的属性 `role`. + +查看更多 OS X 的原生 action [OS X Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) . + +### `Menu.buildFromTemplate(template)` + +* `template` Array + +一般来说,`template` 只是用来创建 [MenuItem](menu-item.md) 的数组 `参数` . + +你也可以向 `template` 元素添加其它东西,并且他们会变成已经有的菜单项的属性. + +### `Menu.popup([browserWindow, x, y, positioningItem])` + +* `browserWindow` BrowserWindow (可选) - 默认为 `null`. +* `x` Number (可选) - 默认为 -1. +* `y` Number (**必须** 如果x设置了) - 默认为 -1. +* `positioningItem` Number (可选) _OS X_ - 在指定坐标鼠标位置下面的菜单项的索引. 默认为 + -1. + +在 `browserWindow` 中弹出 context menu .你可以选择性地提供指定的 `x, y` 来设置菜单应该放在哪里,否则它将默认地放在当前鼠标的位置. + +### `Menu.append(menuItem)` + +* `menuItem` MenuItem + +添加菜单项. + +### `Menu.insert(pos, menuItem)` + +* `pos` Integer +* `menuItem` MenuItem + +在制定位置添加菜单项. + +### `Menu.items()` + +获取一个菜单项数组. + +## OS X Application 上的菜单的注意事项 + +相对于windows 和 linux, OS X 上的应用菜单是完全不同的style,这里是一些注意事项,来让你的菜单项更原生化. + +### 标准菜单 + +在 OS X 上,有很多系统定义的标准菜单,例如 `Services` and +`Windows` 菜单.为了让你的应用更标准化,你可以为你的菜单的 `role` 设置值,然后 electron 将会识别他们并且让你的菜单更标准: + +* `window` +* `help` +* `services` + +### 标准菜单项行为 + +OS X 为一些菜单项提供了标准的行为方法,例如 `About xxx`, +`Hide xxx`, and `Hide Others`. 为了让你的菜单项的行为更标准化,你应该为菜单项设置 `role` 属性. + +### 主菜单名 + +在 OS X ,无论你设置的什么标签,应用菜单的第一个菜单项的标签始终未你的应用名字.想要改变它的话,你必须通过修改应用绑定的 `Info.plist` 文件来修改应用名字.更多信息参考[About Information +Property List Files][AboutInformationPropertyListFiles] . + +## 为制定浏览器窗口设置菜单 (*Linux* *Windows*) + +浏览器窗口的[`setMenu` 方法][setMenu] 能够设置菜单为特定浏览器窗口的类型. + +## 菜单项位置 + +当通过 `Menu.buildFromTemplate` 创建菜单的时候,你可以使用 `position` and `id` 来放置菜单项. + +`MenuItem` 的属性 `position` 格式为 `[placement]=[id]`,`placement` 取值为 `before`, `after`, 或 `endof` 和 `id`, `id` 是菜单已经存在的菜单项的唯一 ID: + +* `before` - 在对应引用id菜单项之前插入. 如果引用的菜单项不存在,则将其插在菜单末尾. +* `after` - 在对应引用id菜单项之后插入. 如果引用的菜单项不存在,则将其插在菜单末尾. +* `endof` - 在逻辑上包含对应引用id菜单项的集合末尾插入. 如果引用的菜单项不存在, 则将使用给定的id创建一个新的集合,并且这个菜单项将插入. + +当一个菜档项插入成功了,所有的没有插入的菜单项将一个接一个地在后面插入.所以如果你想在同一个位置插入一组菜单项,只需要为这组菜单项的第一个指定位置. + +### 例子 + +模板: + +```javascript +[ + {label: '4', id: '4'}, + {label: '5', id: '5'}, + {label: '1', id: '1', position: 'before=4'}, + {label: '2', id: '2'}, + {label: '3', id: '3'} +] +``` + +菜单: + +``` +- 1 +- 2 +- 3 +- 4 +- 5 +``` + +模板: + +```javascript +[ + {label: 'a', position: 'endof=letters'}, + {label: '1', position: 'endof=numbers'}, + {label: 'b', position: 'endof=letters'}, + {label: '2', position: 'endof=numbers'}, + {label: 'c', position: 'endof=letters'}, + {label: '3', position: 'endof=numbers'} +] +``` + +菜单: + +``` +- --- +- a +- b +- c +- --- +- 1 +- 2 +- 3 +``` + +[AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html +[setMenu]: +https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows \ No newline at end of file From 288ef13fb594673744856cee1d3d2613fcb3c69f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 10 Mar 2016 16:57:41 +0900 Subject: [PATCH 0152/1265] :memo: Update Korean docs as upstream [ci skip] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/app.md | 21 ++++++++++++------- docs-translations/ko-KR/api/browser-window.md | 8 +++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 72da6862741..7c18f181742 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -256,14 +256,6 @@ GPU가 작동하던 중 크래시가 일어났을 때 발생하는 이벤트입 `beforeunload` 이벤트 핸들러에서 `false`를 반환했을 때 윈도우 종료가 취소 될 수 있습니다. -### `app.hide()` _OS X_ - -최소화를 하지 않고 어플리케이션의 모든 윈도우들을 숨깁니다. - -### `app.show()` _OS X_ - -숨긴 어플리케이션 윈도우들을 다시 보이게 만듭니다. 자동으로 포커스되지 않습니다. - ### `app.exit(exitCode)` * `exitCode` Integer @@ -273,6 +265,19 @@ GPU가 작동하던 중 크래시가 일어났을 때 발생하는 이벤트입 모든 윈도우는 사용자의 동의 여부에 상관없이 즉시 종료되며 `before-quit` 이벤트와 `will-quit` 이벤트가 발생하지 않습니다. +### `app.focus()` + +Linux에선, 첫 번째로 보여지는 윈도우가 포커스됩니다. OS X에선, 어플리케이션을 활성화 +앱 상태로 만듭니다. Windows에선, 어플리케이션의 첫 윈도우에 포커스 됩니다. + +### `app.hide()` _OS X_ + +최소화를 하지 않고 어플리케이션의 모든 윈도우들을 숨깁니다. + +### `app.show()` _OS X_ + +숨긴 어플리케이션 윈도우들을 다시 보이게 만듭니다. 자동으로 포커스되지 않습니다. + ### `app.getAppPath()` 현재 어플리케이션의 디렉터리를 반환합니다. diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 3517f3d500c..c5030e04d1a 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -240,6 +240,14 @@ window.onbeforeunload = function(e) { 윈도우가 포커스를 가졌을 때 발생하는 이벤트입니다. +### Event: 'show' + +윈도우가 보여진 상태일 때 발생하는 이벤트입니다. + +### Event: 'hide' + +윈도우가 숨겨진 상태일 때 발생하는 이벤트입니다. + ### Event: 'maximize' 윈도우가 최대화됐을 때 발생하는 이벤트입니다. From 5f63df248ad386ea7a4af0017156b35f1bd63bac Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 19:53:41 +0900 Subject: [PATCH 0153/1265] Fix the chrome version --- atom/common/chrome_version.h | 2 +- script/lib/config.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/common/chrome_version.h b/atom/common/chrome_version.h index 604e0161c3a..8b9b7ef0c82 100644 --- a/atom/common/chrome_version.h +++ b/atom/common/chrome_version.h @@ -8,7 +8,7 @@ #ifndef ATOM_COMMON_CHROME_VERSION_H_ #define ATOM_COMMON_CHROME_VERSION_H_ -#define CHROME_VERSION_STRING "49.0.2623.64" +#define CHROME_VERSION_STRING "49.0.2623.75" #define CHROME_VERSION "v" CHROME_VERSION_STRING #endif // ATOM_COMMON_CHROME_VERSION_H_ diff --git a/script/lib/config.py b/script/lib/config.py index e5fafa34720..fb1a4b89f27 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '497f11bcb91d9b0b5b5cbd004411b37b933c825e' +LIBCHROMIUMCONTENT_COMMIT = 'b06d4c307b861cdb091f4ba26b1a185333889033' PLATFORM = { 'cygwin': 'win32', From ead94b7b1f1286e5ce06fd6cfa9b4218c3c9ab0f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 20:09:19 +0900 Subject: [PATCH 0154/1265] Bump v0.36.11 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index b7075301894..f8133b35d0b 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.36.10', + 'version%': '0.36.11', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 54b4f4d6179..267df223e2b 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.36.10 + 0.36.11 CFBundleShortVersionString - 0.36.10 + 0.36.11 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 9acd36f43a2..222c4ac4610 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,36,10,0 - PRODUCTVERSION 0,36,10,0 + FILEVERSION 0,36,11,0 + PRODUCTVERSION 0,36,11,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.36.10" + VALUE "FileVersion", "0.36.11" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.36.10" + VALUE "ProductVersion", "0.36.11" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index c4291437e5b..362e4dc7b88 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 36 -#define ATOM_PATCH_VERSION 10 +#define ATOM_PATCH_VERSION 11 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index ca232158068..343f1baa8fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.36.10", + "version": "0.36.11", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From aebfbf77825fbc6e14ee69afd688a9e3bc4627d3 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 21:47:32 +0900 Subject: [PATCH 0155/1265] Bump v0.37.0 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 4 ++-- package.json | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/atom.gyp b/atom.gyp index 27b7ecd256b..969a0665f9f 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.36.11', + 'version%': '0.37.0', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 267df223e2b..6b504728ae3 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.36.11 + 0.37.0 CFBundleShortVersionString - 0.36.11 + 0.37.0 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 222c4ac4610..bdffd90effd 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,36,11,0 - PRODUCTVERSION 0,36,11,0 + FILEVERSION 0,37,0,0 + PRODUCTVERSION 0,37,0,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.36.11" + VALUE "FileVersion", "0.37.0" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.36.11" + VALUE "ProductVersion", "0.37.0" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 362e4dc7b88..1b1aee905ce 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -6,8 +6,8 @@ #define ATOM_VERSION_H #define ATOM_MAJOR_VERSION 0 -#define ATOM_MINOR_VERSION 36 -#define ATOM_PATCH_VERSION 11 +#define ATOM_MINOR_VERSION 37 +#define ATOM_PATCH_VERSION 0 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 343f1baa8fc..6b6abb5bc68 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.36.11", + "version": "0.37.0", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From cd327e65cb1e4f809b0ab38a527917741af8cf27 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 22:20:11 +0900 Subject: [PATCH 0156/1265] Revert "Bump v0.37.0" This reverts commit aebfbf77825fbc6e14ee69afd688a9e3bc4627d3. We have troubles with linux-ia32 release. --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 4 ++-- package.json | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/atom.gyp b/atom.gyp index 969a0665f9f..27b7ecd256b 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.0', + 'version%': '0.36.11', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 6b504728ae3..267df223e2b 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.37.0 + 0.36.11 CFBundleShortVersionString - 0.37.0 + 0.36.11 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index bdffd90effd..222c4ac4610 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,0,0 - PRODUCTVERSION 0,37,0,0 + FILEVERSION 0,36,11,0 + PRODUCTVERSION 0,36,11,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.0" + VALUE "FileVersion", "0.36.11" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.0" + VALUE "ProductVersion", "0.36.11" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 1b1aee905ce..362e4dc7b88 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -6,8 +6,8 @@ #define ATOM_VERSION_H #define ATOM_MAJOR_VERSION 0 -#define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 0 +#define ATOM_MINOR_VERSION 36 +#define ATOM_PATCH_VERSION 11 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 6b6abb5bc68..343f1baa8fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.0", + "version": "0.36.11", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From 0f620a53930af3a479a67166afc72edea5c18705 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 11 Mar 2016 22:22:17 +0900 Subject: [PATCH 0157/1265] Do not copy system libraries on Linux --- script/create-dist.py | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/script/create-dist.py b/script/create-dist.py index f3894eb4fa2..e25845432c7 100755 --- a/script/create-dist.py +++ b/script/create-dist.py @@ -71,17 +71,11 @@ TARGET_DIRECTORIES = { ], } -SYSTEM_LIBRARIES = [ - 'libgcrypt.so', -] - def main(): rm_rf(DIST_DIR) os.makedirs(DIST_DIR) - target_arch = get_target_arch() - force_build() create_symbols() copy_binaries() @@ -91,8 +85,6 @@ def main(): if PLATFORM == 'linux': strip_binaries() - if target_arch != 'arm': - copy_system_libraries() create_version() create_dist_zip() @@ -144,21 +136,6 @@ def strip_binaries(): execute([strip, os.path.join(DIST_DIR, binary)]) -def copy_system_libraries(): - executable_path = os.path.join(OUT_DIR, PROJECT_NAME) # our/R/electron - ldd = execute(['ldd', executable_path]) - lib_re = re.compile('\t(.*) => (.+) \(.*\)$') - for line in ldd.splitlines(): - m = lib_re.match(line) - if not m: - continue - for i, library in enumerate(SYSTEM_LIBRARIES): - real_library = m.group(1) - if real_library.startswith(library): - shutil.copyfile(m.group(2), os.path.join(DIST_DIR, real_library)) - SYSTEM_LIBRARIES[i] = real_library - - def create_version(): version_path = os.path.join(SOURCE_ROOT, 'dist', 'version') with open(version_path, 'w') as version_file: @@ -185,8 +162,6 @@ def create_dist_zip(): with scoped_cwd(DIST_DIR): files = TARGET_BINARIES[PLATFORM] + ['LICENSE', 'LICENSES.chromium.html', 'version'] - if PLATFORM == 'linux': - files += [lib for lib in SYSTEM_LIBRARIES if os.path.exists(lib)] dirs = TARGET_DIRECTORIES[PLATFORM] make_zip(zip_file, files, dirs) From 5ed6c7714b3a8e9b7b4658654e9882c560aaac0a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 13:08:38 -0800 Subject: [PATCH 0158/1265] Don't return attributes from from WebViewImpl::setupWebViewAttributes --- lib/renderer/web-view/web-view-attributes.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index 4ad4bd72501..bb7847fe163 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -297,7 +297,6 @@ class BlinkFeaturesAttribute extends WebViewAttribute { // Sets up all of the webview attributes. WebViewImpl.prototype.setupWebViewAttributes = function() { - var attribute, autosizeAttributes, i, len, results; this.attributes = {}; this.attributes[webViewConstants.ATTRIBUTE_ALLOWTRANSPARENCY] = new AllowTransparencyAttribute(this); this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE] = new AutosizeAttribute(this); @@ -311,11 +310,9 @@ WebViewImpl.prototype.setupWebViewAttributes = function() { this.attributes[webViewConstants.ATTRIBUTE_ALLOWPOPUPS] = new BooleanAttribute(webViewConstants.ATTRIBUTE_ALLOWPOPUPS, this); this.attributes[webViewConstants.ATTRIBUTE_PRELOAD] = new PreloadAttribute(this); this.attributes[webViewConstants.ATTRIBUTE_BLINKFEATURES] = new BlinkFeaturesAttribute(this); - autosizeAttributes = [webViewConstants.ATTRIBUTE_MAXHEIGHT, webViewConstants.ATTRIBUTE_MAXWIDTH, webViewConstants.ATTRIBUTE_MINHEIGHT, webViewConstants.ATTRIBUTE_MINWIDTH]; - results = []; - for (i = 0, len = autosizeAttributes.length; i < len; i++) { - attribute = autosizeAttributes[i]; - results.push(this.attributes[attribute] = new AutosizeDimensionAttribute(attribute, this)); - } - return results; + + const autosizeAttributes = [webViewConstants.ATTRIBUTE_MAXHEIGHT, webViewConstants.ATTRIBUTE_MAXWIDTH, webViewConstants.ATTRIBUTE_MINHEIGHT, webViewConstants.ATTRIBUTE_MINWIDTH]; + autosizeAttributes.forEach((attribute) => { + this.attributes[attribute] = new AutosizeDimensionAttribute(attribute, this); + }); }; From 3a1e837f8bbbdf129fe2af4361f6d6d8dc5d7196 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 13:23:14 -0800 Subject: [PATCH 0159/1265] Don't collect results in exit event callback --- lib/common/asar.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/common/asar.js b/lib/common/asar.js index f45e62b176d..aeff18916a1 100644 --- a/lib/common/asar.js +++ b/lib/common/asar.js @@ -24,14 +24,12 @@ // Clean cache on quit. process.on('exit', function() { - var archive, p, results; - results = []; + var archive, p; for (p in cachedArchives) { if (!hasProp.call(cachedArchives, p)) continue; archive = cachedArchives[p]; - results.push(archive.destroy()); + archive.destroy(); } - return results; }); // Separate asar package's path from full path. From 93939089eca0cf01aa2ae355b52bdbe88485355b Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 13:26:14 -0800 Subject: [PATCH 0160/1265] Don't collect results in Menu.setApplicationMenu --- lib/browser/api/menu.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 5af577872db..f22002e144d 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -267,7 +267,6 @@ Menu.prototype._callMenuWillShow = function() { var applicationMenu = null; Menu.setApplicationMenu = function(menu) { - var j, len, results, w, windows; if (!(menu === null || menu.constructor === Menu)) { throw new TypeError('Invalid menu'); } @@ -279,15 +278,11 @@ Menu.setApplicationMenu = function(menu) { return; } menu._callMenuWillShow(); - return bindings.setApplicationMenu(menu); + bindings.setApplicationMenu(menu); } else { - windows = BrowserWindow.getAllWindows(); - results = []; - for (j = 0, len = windows.length; j < len; j++) { - w = windows[j]; - results.push(w.setMenu(menu)); - } - return results; + BrowserWindow.getAllWindows().forEach(function(window) { + window.setMenu(menu); + }); } }; From 3a08aa37de1e7277c82934ae884197ecde5b58d2 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 13:29:57 -0800 Subject: [PATCH 0161/1265] Don't collect results from Menu::_callMenuWillShow --- lib/browser/api/menu.js | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index f22002e144d..5c19c7d421f 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -249,19 +249,14 @@ Menu.prototype.insert = function(pos, item) { // Force menuWillShow to be called Menu.prototype._callMenuWillShow = function() { - var item, j, len, ref1, ref2, results; - if ((ref1 = this.delegate) != null) { - ref1.menuWillShow(); + if (this.delegate != null) { + this.delegate.menuWillShow(); } - ref2 = this.items; - results = []; - for (j = 0, len = ref2.length; j < len; j++) { - item = ref2[j]; + this.items.forEach(function(item) { if (item.submenu != null) { - results.push(item.submenu._callMenuWillShow()); + item.submenu._callMenuWillShow(); } - } - return results; + }); }; var applicationMenu = null; From 6b1748d6d639f3849acf0e8c0d207ea2ae1e1e0e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 14:01:57 -0800 Subject: [PATCH 0162/1265] Don't collect results from delegate.menuWillShow --- lib/browser/api/menu.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 5c19c7d421f..a24f1ae0fb7 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -132,9 +132,8 @@ Menu.prototype._init = function() { return function() { // Make sure radio groups have at least one menu item seleted. - var checked, group, id, j, len, radioItem, ref1, results; + var checked, group, id, j, len, radioItem, ref1; ref1 = _this.groupsMap; - results = []; for (id in ref1) { group = ref1[id]; checked = false; @@ -147,12 +146,9 @@ Menu.prototype._init = function() { break; } if (!checked) { - results.push(v8Util.setHiddenValue(group[0], 'checked', true)); - } else { - results.push(void 0); + v8Util.setHiddenValue(group[0], 'checked', true); } } - return results; }; })(this) }; From c2b1f630f6e035cf999e4de190df34eb0da433ec Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 09:37:56 -0800 Subject: [PATCH 0163/1265] Add AppVeyor badge --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0080585b54c..9c7d4ce815e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) -[![Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) +[![Travis Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron/branch/master) [![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/) From a95d0078b5a909e75eb57a4bafdef832f3b2c954 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 09:39:12 -0800 Subject: [PATCH 0164/1265] Link to root build page --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c7d4ce815e..f7b5cb79000 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) [![Travis Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) -[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron/branch/master) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) [![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/) From a3f08c9b514bde39067fa3c5a029a163484abdde Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 11:54:17 -0800 Subject: [PATCH 0165/1265] Use arrow functions to replace old CoffeeScript => this wrappers --- lib/browser/api/app.js | 10 +- .../api/auto-updater/auto-updater-win.js | 38 +++--- lib/browser/api/browser-window.js | 8 +- lib/browser/api/menu-item.js | 41 +++--- lib/browser/api/menu.js | 122 ++++++++---------- lib/browser/api/navigation-controller.js | 61 ++++----- lib/browser/api/web-contents.js | 25 ++-- lib/common/api/crash-reporter.js | 10 +- lib/renderer/override.js | 14 +- lib/renderer/web-view/web-view.js | 59 ++++----- 10 files changed, 176 insertions(+), 212 deletions(-) diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index f7c9cd97583..8d2d203ee98 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -1,3 +1,5 @@ +'use strict'; + const deprecate = require('electron').deprecate; const session = require('electron').session; const Menu = require('electron').Menu; @@ -89,11 +91,9 @@ deprecate.rename(app, 'terminate', 'quit'); deprecate.event(app, 'finish-launching', 'ready', function() { // give default app a chance to setup default menu. - return setImmediate((function(_this) { - return function() { - return _this.emit('finish-launching'); - }; - })(this)); + setImmediate(() => { + this.emit('finish-launching'); + }); }); deprecate.event(app, 'activate-with-no-open-windows', 'activate', function(event, hasVisibleWindows) { diff --git a/lib/browser/api/auto-updater/auto-updater-win.js b/lib/browser/api/auto-updater/auto-updater-win.js index 1270f8f2bdb..8d584699419 100644 --- a/lib/browser/api/auto-updater/auto-updater-win.js +++ b/lib/browser/api/auto-updater/auto-updater-win.js @@ -28,30 +28,28 @@ AutoUpdater.prototype.checkForUpdates = function() { return this.emitError('Can not find Squirrel'); } this.emit('checking-for-update'); - return squirrelUpdate.download(this.updateURL, (function(_this) { - return function(error, update) { + squirrelUpdate.download(this.updateURL, (error, update) => { + if (error != null) { + return this.emitError(error); + } + if (update == null) { + return this.emit('update-not-available'); + } + this.emit('update-available'); + squirrelUpdate.update(this.updateURL, (error) => { + var date, releaseNotes, version; if (error != null) { - return _this.emitError(error); + return this.emitError(error); } - if (update == null) { - return _this.emit('update-not-available'); - } - _this.emit('update-available'); - return squirrelUpdate.update(_this.updateURL, function(error) { - var date, releaseNotes, version; - if (error != null) { - return _this.emitError(error); - } - releaseNotes = update.releaseNotes, version = update.version; + releaseNotes = update.releaseNotes, version = update.version; - // Following information is not available on Windows, so fake them. - date = new Date; - return _this.emit('update-downloaded', {}, releaseNotes, version, date, _this.updateURL, function() { - return _this.quitAndInstall(); - }); + // Following information is not available on Windows, so fake them. + date = new Date; + this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => { + this.quitAndInstall(); }); - }; - })(this)); + }); + }); }; // Private: Emit both error object and message, this is to keep compatibility diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 1d2f665e5d0..7d99c483944 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -1,3 +1,5 @@ +'use strict'; + const ipcMain = require('electron').ipcMain; const deprecate = require('electron').deprecate; const EventEmitter = require('events').EventEmitter; @@ -33,19 +35,19 @@ BrowserWindow.prototype._init = function() { // window.resizeTo(...) // window.moveTo(...) this.webContents.on('move', (event, size) => { - return this.setBounds(size); + this.setBounds(size); }); // Hide the auto-hide menu when webContents is focused. this.webContents.on('activate', () => { if (process.platform !== 'darwin' && this.isMenuBarAutoHide() && this.isMenuBarVisible()) { - return this.setMenuBarVisibility(false); + this.setMenuBarVisibility(false); } }); // Forward the crashed event. this.webContents.on('crashed', () => { - return this.emit('crashed'); + this.emit('crashed'); }); // Change window title to page title. diff --git a/lib/browser/api/menu-item.js b/lib/browser/api/menu-item.js index 4f449ecc015..f5f94751866 100644 --- a/lib/browser/api/menu-item.js +++ b/lib/browser/api/menu-item.js @@ -1,3 +1,5 @@ +'use strict'; + var MenuItem, methodInBrowserWindow, nextCommandId, rolesMap; nextCommandId = 0; @@ -51,28 +53,25 @@ MenuItem = (function() { throw new Error("Unknown menu type " + this.type); } this.commandId = ++nextCommandId; - this.click = (function(_this) { - return function(focusedWindow) { - - // Manually flip the checked flags when clicked. - var methodName, ref1, ref2; - if ((ref1 = _this.type) === 'checkbox' || ref1 === 'radio') { - _this.checked = !_this.checked; + this.click = (focusedWindow) => { + // Manually flip the checked flags when clicked. + var methodName, ref1, ref2; + if ((ref1 = this.type) === 'checkbox' || ref1 === 'radio') { + this.checked = !this.checked; + } + if (this.role && rolesMap[this.role] && process.platform !== 'darwin' && (focusedWindow != null)) { + methodName = rolesMap[this.role]; + if (methodInBrowserWindow[methodName]) { + return focusedWindow[methodName](); + } else { + return (ref2 = focusedWindow.webContents) != null ? ref2[methodName]() : void 0; } - if (_this.role && rolesMap[_this.role] && process.platform !== 'darwin' && (focusedWindow != null)) { - methodName = rolesMap[_this.role]; - if (methodInBrowserWindow[methodName]) { - return focusedWindow[methodName](); - } else { - return (ref2 = focusedWindow.webContents) != null ? ref2[methodName]() : void 0; - } - } else if (typeof click === 'function') { - return click(_this, focusedWindow); - } else if (typeof _this.selector === 'string' && process.platform === 'darwin') { - return Menu.sendActionToFirstResponder(_this.selector); - } - }; - })(this); + } else if (typeof click === 'function') { + return click(this, focusedWindow); + } else if (typeof this.selector === 'string' && process.platform === 'darwin') { + return Menu.sendActionToFirstResponder(this.selector); + } + }; } MenuItem.prototype.overrideProperty = function(name, defaultValue) { diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index a24f1ae0fb7..202885d826b 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -1,3 +1,5 @@ +'use strict'; + const BrowserWindow = require('electron').BrowserWindow; const MenuItem = require('electron').MenuItem; const EventEmitter = require('events').EventEmitter; @@ -92,65 +94,51 @@ Menu.prototype._init = function() { this.groupsMap = {}; this.items = []; return this.delegate = { - isCommandIdChecked: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.checked : void 0; - }; - })(this), - isCommandIdEnabled: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.enabled : void 0; - }; - })(this), - isCommandIdVisible: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.visible : void 0; - }; - })(this), - getAcceleratorForCommandId: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.accelerator : void 0; - }; - })(this), - getIconForCommandId: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.icon : void 0; - }; - })(this), - executeCommand: (function(_this) { - return function(commandId) { - var ref1; - return (ref1 = _this.commandsMap[commandId]) != null ? ref1.click(BrowserWindow.getFocusedWindow()) : void 0; - }; - })(this), - menuWillShow: (function(_this) { - return function() { - - // Make sure radio groups have at least one menu item seleted. - var checked, group, id, j, len, radioItem, ref1; - ref1 = _this.groupsMap; - for (id in ref1) { - group = ref1[id]; - checked = false; - for (j = 0, len = group.length; j < len; j++) { - radioItem = group[j]; - if (!radioItem.checked) { - continue; - } - checked = true; - break; - } - if (!checked) { - v8Util.setHiddenValue(group[0], 'checked', true); + isCommandIdChecked: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.checked : undefined; + }, + isCommandIdEnabled: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.enabled : undefined; + }, + isCommandIdVisible: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.visible : undefined; + }, + getAcceleratorForCommandId: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.accelerator : undefined; + }, + getIconForCommandId: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.icon : void 0; + }, + executeCommand: (commandId) => { + var command = this.commandsMap[commandId]; + return command != null ? command.click(BrowserWindow.getFocusedWindow()) : undefined; + }, + menuWillShow: () => { + // Make sure radio groups have at least one menu item seleted. + var checked, group, id, j, len, radioItem, ref1; + ref1 = this.groupsMap; + results = []; + for (id in ref1) { + group = ref1[id]; + checked = false; + for (j = 0, len = group.length; j < len; j++) { + radioItem = group[j]; + if (!radioItem.checked) { + continue; } + checked = true; + break; + } + if (!checked) { + v8Util.setHiddenValue(group[0], 'checked', true); } }; - })(this) + } }; }; @@ -208,19 +196,17 @@ Menu.prototype.insert = function(pos, item) { get: function() { return v8Util.getHiddenValue(item, 'checked'); }, - set: (function(_this) { - return function() { - var j, len, otherItem, ref1; - ref1 = _this.groupsMap[item.groupId]; - for (j = 0, len = ref1.length; j < len; j++) { - otherItem = ref1[j]; - if (otherItem !== item) { - v8Util.setHiddenValue(otherItem, 'checked', false); - } + set: () => { + var j, len, otherItem, ref1; + ref1 = this.groupsMap[item.groupId]; + for (j = 0, len = ref1.length; j < len; j++) { + otherItem = ref1[j]; + if (otherItem !== item) { + v8Util.setHiddenValue(otherItem, 'checked', false); } - return v8Util.setHiddenValue(item, 'checked', true); - }; - })(this) + } + return v8Util.setHiddenValue(item, 'checked', true); + } }); this.insertRadioItem(pos, item.commandId, item.label, item.groupId); } diff --git a/lib/browser/api/navigation-controller.js b/lib/browser/api/navigation-controller.js index 80756eb13e4..8c3878a51fa 100644 --- a/lib/browser/api/navigation-controller.js +++ b/lib/browser/api/navigation-controller.js @@ -1,3 +1,5 @@ +'use strict'; + const ipcMain = require('electron').ipcMain; var slice = [].slice; @@ -30,40 +32,33 @@ var NavigationController = (function() { this.currentIndex++; this.history.push(this.webContents._getURL()); } - this.webContents.on('navigation-entry-commited', (function(_this) { - return function(event, url, inPage, replaceEntry) { - var currentEntry; - if (_this.inPageIndex > -1 && !inPage) { - - // Navigated to a new page, clear in-page mark. - _this.inPageIndex = -1; - } else if (_this.inPageIndex === -1 && inPage) { - - // Started in-page navigations. - _this.inPageIndex = _this.currentIndex; + this.webContents.on('navigation-entry-commited', (event, url, inPage, replaceEntry) => { + var currentEntry; + if (this.inPageIndex > -1 && !inPage) { + // Navigated to a new page, clear in-page mark. + this.inPageIndex = -1; + } else if (this.inPageIndex === -1 && inPage) { + // Started in-page navigations. + this.inPageIndex = this.currentIndex; + } + if (this.pendingIndex >= 0) { + // Go to index. + this.currentIndex = this.pendingIndex; + this.pendingIndex = -1; + return this.history[this.currentIndex] = url; + } else if (replaceEntry) { + // Non-user initialized navigation. + return this.history[this.currentIndex] = url; + } else { + // Normal navigation. Clear history. + this.history = this.history.slice(0, this.currentIndex + 1); + currentEntry = this.history[this.currentIndex]; + if ((currentEntry != null ? currentEntry.url : void 0) !== url) { + this.currentIndex++; + return this.history.push(url); } - if (_this.pendingIndex >= 0) { - - // Go to index. - _this.currentIndex = _this.pendingIndex; - _this.pendingIndex = -1; - return _this.history[_this.currentIndex] = url; - } else if (replaceEntry) { - - // Non-user initialized navigation. - return _this.history[_this.currentIndex] = url; - } else { - - // Normal navigation. Clear history. - _this.history = _this.history.slice(0, _this.currentIndex + 1); - currentEntry = _this.history[_this.currentIndex]; - if ((currentEntry != null ? currentEntry.url : void 0) !== url) { - _this.currentIndex++; - return _this.history.push(url); - } - } - }; - })(this)); + } + }); } NavigationController.prototype.loadURL = function(url, options) { diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 9486378264b..c7dd3bc7475 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -153,35 +153,28 @@ let wrapWebContents = function(webContents) { // This error occurs when host could not be found. webContents.on('did-fail-provisional-load', function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; // Calling loadURL during this event might cause crash, so delay the event // until next tick. - return setImmediate((function(_this) { - return function() { - return _this.emit.apply(_this, ['did-fail-load'].concat(slice.call(args))); - }; - })(this)); + setImmediate(() => { + this.emit.apply(this, ['did-fail-load'].concat(slice.call(args))); + }); }); // Delays the page-title-updated event to next tick. webContents.on('-page-title-updated', function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return setImmediate((function(_this) { - return function() { - return _this.emit.apply(_this, ['page-title-updated'].concat(slice.call(args))); - }; - })(this)); + var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + setImmediate(() => { + this.emit.apply(this, ['page-title-updated'].concat(slice.call(args))); + }); }); // Deprecated. deprecate.rename(webContents, 'loadUrl', 'loadURL'); deprecate.rename(webContents, 'getUrl', 'getURL'); deprecate.event(webContents, 'page-title-set', 'page-title-updated', function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; return this.emit.apply(this, ['page-title-set'].concat(slice.call(args))); }); return webContents.printToPDF = function(options, callback) { diff --git a/lib/common/api/crash-reporter.js b/lib/common/api/crash-reporter.js index e3a327118fd..f84e13ebb57 100644 --- a/lib/common/api/crash-reporter.js +++ b/lib/common/api/crash-reporter.js @@ -1,3 +1,5 @@ +'use strict'; + const os = require('os'); const path = require('path'); const spawn = require('child_process').spawn; @@ -52,11 +54,9 @@ var CrashReporter = (function() { deprecate.log('submitURL is now a required option to crashReporter.start'); return; } - start = (function(_this) { - return function() { - return binding.start(_this.productName, companyName, submitURL, autoSubmit, ignoreSystemCrashHandler, extra); - }; - })(this); + start = () => { + binding.start(this.productName, companyName, submitURL, autoSubmit, ignoreSystemCrashHandler, extra); + }; if (process.platform === 'win32') { args = ["--reporter-url=" + submitURL, "--application-name=" + this.productName, "--v=1"]; env = { diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 2b0e48b3dd3..c44218e8a56 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -1,3 +1,5 @@ +'use strict'; + const ipcRenderer = require('electron').ipcRenderer; const remote = require('electron').remote; @@ -37,12 +39,10 @@ var BrowserWindowProxy = (function() { function BrowserWindowProxy(guestId1) { this.guestId = guestId1; this.closed = false; - ipcRenderer.once("ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_" + this.guestId, (function(_this) { - return function() { - BrowserWindowProxy.remove(_this.guestId); - return (_this.closed = true); - }; - })(this)); + ipcRenderer.once("ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_" + this.guestId, () => { + BrowserWindowProxy.remove(this.guestId); + this.closed = true; + }); } BrowserWindowProxy.prototype.close = function() { @@ -182,7 +182,7 @@ if (process.openerId != null) { ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { var hasChanged = _isVisible != isVisible || _isMinimized != isMinimized; - + if (hasChanged) { _isVisible = isVisible; _isMinimized = isMinimized; diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 5b135e0427a..38ee57a96f6 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -86,25 +86,22 @@ var WebViewImpl = (function() { WebViewImpl.prototype.setupFocusPropagation = function() { if (!this.webviewNode.hasAttribute('tabIndex')) { - // needs a tabIndex in order to be focusable. // TODO(fsamuel): It would be nice to avoid exposing a tabIndex attribute // to allow to be focusable. // See http://crbug.com/231664. this.webviewNode.setAttribute('tabIndex', -1); } - this.webviewNode.addEventListener('focus', (function(_this) { - return function() { - // Focus the BrowserPlugin when the takes focus. - return _this.browserPluginNode.focus(); - }; - })(this)); - return this.webviewNode.addEventListener('blur', (function(_this) { - return function() { - // Blur the BrowserPlugin when the loses focus. - return _this.browserPluginNode.blur(); - }; - })(this)); + + // Focus the BrowserPlugin when the takes focus. + this.webviewNode.addEventListener('focus', () => { + this.browserPluginNode.focus(); + }); + + // Blur the BrowserPlugin when the loses focus. + this.webviewNode.addEventListener('blur', () => { + this.browserPluginNode.blur(); + }); }; @@ -178,11 +175,9 @@ var WebViewImpl = (function() { }; WebViewImpl.prototype.createGuest = function() { - return guestViewInternal.createGuest(this.buildParams(), (function(_this) { - return function(event, guestInstanceId) { - return _this.attachWindow(guestInstanceId); - }; - })(this)); + return guestViewInternal.createGuest(this.buildParams(), (event, guestInstanceId) => { + this.attachWindow(guestInstanceId); + }); }; WebViewImpl.prototype.dispatchEvent = function(webViewEvent) { @@ -195,22 +190,18 @@ var WebViewImpl = (function() { var propertyName; propertyName = 'on' + eventName.toLowerCase(); return Object.defineProperty(this.webviewNode, propertyName, { - get: (function(_this) { - return function() { - return _this.on[propertyName]; - }; - })(this), - set: (function(_this) { - return function(value) { - if (_this.on[propertyName]) { - _this.webviewNode.removeEventListener(eventName, _this.on[propertyName]); - } - _this.on[propertyName] = value; - if (value) { - return _this.webviewNode.addEventListener(eventName, value); - } - }; - })(this), + get: () => { + this.on[propertyName]; + }, + set: (value) => { + if (this.on[propertyName]) { + this.webviewNode.removeEventListener(eventName, this.on[propertyName]); + } + this.on[propertyName] = value; + if (value) { + return this.webviewNode.addEventListener(eventName, value); + } + }, enumerable: true }); }; From 0ee34461098005f298ed9be1b0addb845db1f9c5 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 10 Mar 2016 11:59:50 -0800 Subject: [PATCH 0166/1265] Use undefined instead of void 0 --- lib/browser/api/menu.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 202885d826b..83816a9905d 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -112,7 +112,7 @@ Menu.prototype._init = function() { }, getIconForCommandId: (commandId) => { var command = this.commandsMap[commandId]; - return command != null ? command.icon : void 0; + return command != null ? command.icon : undefined; }, executeCommand: (commandId) => { var command = this.commandsMap[commandId]; From 3c11f5dc4d84b7599fe0f314cebc241ef35f3121 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 11:05:48 -0800 Subject: [PATCH 0167/1265] Remove returns from event handlers --- lib/browser/api/browser-window.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 7d99c483944..7e2a8d38c31 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -69,29 +69,29 @@ BrowserWindow.prototype._init = function() { // Though this hack is only needed on OS X when the app is launched from // Finder, we still do it on all platforms in case of other bugs we don't know. this.webContents.once('load-url', function() { - return this.focus(); + this.focus(); }); // Redirect focus/blur event to app instance too. this.on('blur', (event) => { - return app.emit('browser-window-blur', event, this); + app.emit('browser-window-blur', event, this); }); this.on('focus', (event) => { - return app.emit('browser-window-focus', event, this); + app.emit('browser-window-focus', event, this); }); // Evented visibilityState changes this.on('show', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); + this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('hide', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); + this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('minimize', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); + this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); this.on('restore', () => { - return this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); + this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()); }); // Notify the creation of the window. @@ -99,15 +99,15 @@ BrowserWindow.prototype._init = function() { // Be compatible with old APIs. this.webContents.on('devtools-focused', () => { - return this.emit('devtools-focused'); + this.emit('devtools-focused'); }); this.webContents.on('devtools-opened', () => { - return this.emit('devtools-opened'); + this.emit('devtools-opened'); }); this.webContents.on('devtools-closed', () => { - return this.emit('devtools-closed'); + this.emit('devtools-closed'); }); - return Object.defineProperty(this, 'devToolsWebContents', { + Object.defineProperty(this, 'devToolsWebContents', { enumerable: true, configurable: false, get: function() { From 0e5e230c037ee62909b2472fa997ea052b39f091 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 11:12:47 -0800 Subject: [PATCH 0168/1265] Remove lint errors due to rebase --- lib/browser/api/menu.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 83816a9905d..cfb00bd4527 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -122,7 +122,6 @@ Menu.prototype._init = function() { // Make sure radio groups have at least one menu item seleted. var checked, group, id, j, len, radioItem, ref1; ref1 = this.groupsMap; - results = []; for (id in ref1) { group = ref1[id]; checked = false; @@ -137,7 +136,7 @@ Menu.prototype._init = function() { if (!checked) { v8Util.setHiddenValue(group[0], 'checked', true); } - }; + } } }; }; From 28e9d87d86e5565dc46c3aba1aca1d9e37a3c9f8 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 11:16:59 -0800 Subject: [PATCH 0169/1265] Add back return in getter --- lib/renderer/web-view/web-view.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 38ee57a96f6..554b2f04cbe 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -191,7 +191,7 @@ var WebViewImpl = (function() { propertyName = 'on' + eventName.toLowerCase(); return Object.defineProperty(this.webviewNode, propertyName, { get: () => { - this.on[propertyName]; + return this.on[propertyName]; }, set: (value) => { if (this.on[propertyName]) { From 3556507ab984fc0ac0bdd6fe5d4da52cd29e0e9a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 11 Mar 2016 14:08:14 -0800 Subject: [PATCH 0170/1265] Use arrow functions for this binding --- lib/renderer/web-view/web-view-attributes.js | 40 +++++++++----------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index bb7847fe163..e85fe716187 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -44,16 +44,12 @@ class WebViewAttribute { // Defines this attribute as a property on the webview node. defineProperty() { return Object.defineProperty(this.webViewImpl.webviewNode, this.name, { - get: (function(_this) { - return function() { - return _this.getValue(); - }; - })(this), - set: (function(_this) { - return function(value) { - return _this.setValue(value); - }; - })(this), + get: () => { + return this.getValue(); + }, + set: (value) => { + return this.setValue(value); + }, enumerable: true }); } @@ -203,20 +199,18 @@ class SrcAttribute extends WebViewAttribute { // spawns off a new process. setupMutationObserver() { var params; - this.observer = new MutationObserver((function(_this) { - return function(mutations) { - var i, len, mutation, newValue, oldValue; - for (i = 0, len = mutations.length; i < len; i++) { - mutation = mutations[i]; - oldValue = mutation.oldValue; - newValue = _this.getValue(); - if (oldValue !== newValue) { - return; - } - _this.handleMutation(oldValue, newValue); + this.observer = new MutationObserver((mutations) => { + var i, len, mutation, newValue, oldValue; + for (i = 0, len = mutations.length; i < len; i++) { + mutation = mutations[i]; + oldValue = mutation.oldValue; + newValue = this.getValue(); + if (oldValue !== newValue) { + return; } - }; - })(this)); + this.handleMutation(oldValue, newValue); + } + }); params = { attributes: true, attributeOldValue: true, From 71fb6840694aef4d39450c6e45609918c2566f58 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 12 Mar 2016 09:17:28 +0900 Subject: [PATCH 0171/1265] spec: Skip webview.executeJavaScript in Travis on OS X It is very easy to get timeout. --- spec/webview-spec.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index ba3913e2e47..5963709e6f0 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -568,7 +568,9 @@ describe(' tag', function() { }); it('can return the result of the executed script', function(done) { - this.timeout(50000); + if (process.env.TRAVIS === 'true' && process.platform == 'darwin') + return done(); + var listener = function() { var jsScript = "'4'+2"; webview.executeJavaScript(jsScript, false, function(result) { From 0e1bb989132e20b317735c8c134580f85d5e6714 Mon Sep 17 00:00:00 2001 From: Habib Rehman Date: Sat, 12 Mar 2016 00:26:29 +0000 Subject: [PATCH 0172/1265] Fix broken/outdated link and push up the version --- docs/tutorial/debugging-main-process.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/tutorial/debugging-main-process.md b/docs/tutorial/debugging-main-process.md index 6fbb858bc28..c7a373f0a45 100644 --- a/docs/tutorial/debugging-main-process.md +++ b/docs/tutorial/debugging-main-process.md @@ -40,11 +40,11 @@ $ npm install git+https://git@github.com/enlight/node-pre-gyp.git#detect-electro ### 4. Recompile the `node-inspector` `v8` modules for electron (change the target to your electron version number) ```bash -$ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-to-build --directory node_modules/v8-debug/ --dist-url=https://atom.io/download/atom-shell reinstall -$ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall +$ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback-to-build --directory node_modules/v8-debug/ --dist-url=https://atom.io/download/atom-shell reinstall +$ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall ``` -See also [How to install native modules](how-to-install-native-modules). +See also [How to install native modules](using-native-node-modules.md). ### 5. Enable debug mode for Electron From b10f196d169ebc5bf8c274a8fb3ac15c93c15458 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 12 Mar 2016 09:54:10 +0900 Subject: [PATCH 0173/1265] Bump v0.37.0 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 4 ++-- package.json | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/atom.gyp b/atom.gyp index 27b7ecd256b..969a0665f9f 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.36.11', + 'version%': '0.37.0', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 267df223e2b..6b504728ae3 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.36.11 + 0.37.0 CFBundleShortVersionString - 0.36.11 + 0.37.0 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 222c4ac4610..bdffd90effd 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,36,11,0 - PRODUCTVERSION 0,36,11,0 + FILEVERSION 0,37,0,0 + PRODUCTVERSION 0,37,0,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.36.11" + VALUE "FileVersion", "0.37.0" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.36.11" + VALUE "ProductVersion", "0.37.0" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 362e4dc7b88..1b1aee905ce 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -6,8 +6,8 @@ #define ATOM_VERSION_H #define ATOM_MAJOR_VERSION 0 -#define ATOM_MINOR_VERSION 36 -#define ATOM_PATCH_VERSION 11 +#define ATOM_MINOR_VERSION 37 +#define ATOM_PATCH_VERSION 0 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 343f1baa8fc..6b6abb5bc68 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.36.11", + "version": "0.37.0", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From c9375688464f0e82435f481845810919f9fc9a73 Mon Sep 17 00:00:00 2001 From: "Brian R. Bondy" Date: Fri, 11 Mar 2016 20:38:53 -0500 Subject: [PATCH 0174/1265] Fix libffmpeg.dylib path for install_name_tool --- atom.gyp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom.gyp b/atom.gyp index 969a0665f9f..37a2c5d3a0a 100644 --- a/atom.gyp +++ b/atom.gyp @@ -489,7 +489,7 @@ 'action': [ 'install_name_tool', '-change', - '@loader_path/libffmpeg.dylib', + '/usr/local/lib/libffmpeg.dylib', '@rpath/libffmpeg.dylib', '${BUILT_PRODUCTS_DIR}/<(product_name) Framework.framework/Versions/A/<(product_name) Framework', ], From 96d271e57ce9e2eb6e9b2b611b7c513109c1fed8 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 13 Mar 2016 06:10:00 +0900 Subject: [PATCH 0175/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/browser-window.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index c5030e04d1a..1ebf7743c2f 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -401,6 +401,10 @@ var win = new BrowserWindow({ width: 800, height: 600 }); 윈도우에 포커스를 맞춥니다. +### `win.blur()` + +윈도우의 포커스를 없앱니다. + ### `win.isFocused()` 윈도우가 포커스되었는지 여부를 반환합니다. From 7569d180c9f73a22f0ea9a3373f6552bd759c230 Mon Sep 17 00:00:00 2001 From: Todd Wolfson Date: Sat, 12 Mar 2016 18:05:01 -0600 Subject: [PATCH 0176/1265] Added support for window.location on window.open windows --- lib/browser/guest-window-manager.js | 4 ++-- lib/renderer/override.js | 9 +++++++++ spec/chromium-spec.js | 26 ++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 50c6a62eb0c..bdd32af7a61 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -101,8 +101,8 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function(event, guest ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function() { var args, guestId, method, ref1; - guestId = arguments[1], method = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : []; - return (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0; + event = arguments[0], guestId = arguments[1], method = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : []; + return event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0; }); ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function(event, guestId, message, targetOrigin, sourceOrigin) { diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 2b0e48b3dd3..6717db931dc 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -57,6 +57,15 @@ var BrowserWindowProxy = (function() { return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'blur'); }; + Object.defineProperty(BrowserWindowProxy.prototype, 'location', { + get: function() { + return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'getURL'); + }, + set: function(url) { + return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'loadURL', url); + } + }); + BrowserWindowProxy.prototype.postMessage = function(message, targetOrigin) { if (targetOrigin == null) { targetOrigin = '*'; diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 67b2d263204..71cef125618 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -193,6 +193,32 @@ describe('chromium feature', function() { window.addEventListener('message', listener); b = window.open("file://" + fixtures + "/pages/window-open-size.html", '', "show=no,width=" + size.width + ",height=" + size.height); }); + + it('defines a window.location getter', function(done) { + var b, targetURL; + targetURL = "file://" + fixtures + "/pages/base-page.html"; + b = window.open(targetURL); + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { + assert.equal(b.location, targetURL); + b.close(); + done(); + }); + }); + + it('defines a window.location setter', function(done) { + // Load a page that definitely won't redirect + var b; + b = window.open("about:blank"); + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { + // When it loads, redirect + b.location = "file://" + fixtures + "/pages/base-page.html"; + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { + // After our second redirect, cleanup and callback + b.close(); + done(); + }); + }); + }); }); describe('window.opener', function() { From 78c66da9e80c61d9d5d2cf70bccb1a6dda23e7ad Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 13 Mar 2016 10:11:15 +0900 Subject: [PATCH 0177/1265] Update brightray: dealy loading powrprof.dll --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index c1f3bb4ecf4..d6bafa3ac1b 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit c1f3bb4ecf4cacb33bf56b9ebd3656a4defbeb64 +Subproject commit d6bafa3ac1b56b24e8944ebbc87ed51ad417a21d From d96e03c40251f53fb5724b7081373d0c0a1a96b6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 13 Mar 2016 10:11:26 +0900 Subject: [PATCH 0178/1265] Bump v0.37.1 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index 37a2c5d3a0a..24456ca479d 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.0', + 'version%': '0.37.1', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 6b504728ae3..613fa39e9da 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.37.0 + 0.37.1 CFBundleShortVersionString - 0.37.0 + 0.37.1 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index bdffd90effd..3b587f62da8 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,0,0 - PRODUCTVERSION 0,37,0,0 + FILEVERSION 0,37,1,0 + PRODUCTVERSION 0,37,1,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.0" + VALUE "FileVersion", "0.37.1" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.0" + VALUE "ProductVersion", "0.37.1" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 1b1aee905ce..27b3fec626f 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 0 +#define ATOM_PATCH_VERSION 1 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 6b6abb5bc68..a4e3686bffd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.0", + "version": "0.37.1", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From 29609b6e5d272bb71fbb9b4eccfe50cb08f3e9fb Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Sun, 13 Mar 2016 14:15:11 +0800 Subject: [PATCH 0179/1265] add powerMonitor first --- docs-translations/zh-CN/api/power-monitor.md | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs-translations/zh-CN/api/power-monitor.md diff --git a/docs-translations/zh-CN/api/power-monitor.md b/docs-translations/zh-CN/api/power-monitor.md new file mode 100644 index 00000000000..3394b4a284e --- /dev/null +++ b/docs-translations/zh-CN/api/power-monitor.md @@ -0,0 +1,36 @@ +# powerMonitor + +`power-monitor`模块是用来监听能源区改变的.只能在主进程中使用.在 `app` 模块的 `ready` 事件触发之后就不能使用这个模块了. + +例如: + +```javascript +app.on('ready', function() { + require('electron').powerMonitor.on('suspend', function() { + console.log('The system is going to sleep'); + }); +}); +``` + +## 事件 + +`power-monitor` 模块可以触发下列事件: + +### Event: 'suspend' + +在系统挂起的时候触发. + +### Event: 'resume' + +在系统恢复继续工作的时候触发. +Emitted when system is resuming. + +### Event: 'on-ac' + +在系统使用交流电的时候触发. +Emitted when the system changes to AC power. + +### Event: 'on-battery' + +在系统使用电池电源的时候触发. +Emitted when system changes to battery power. \ No newline at end of file From d96836e608ac33b501cb1d139313d97727d35197 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Sun, 13 Mar 2016 22:06:19 +0800 Subject: [PATCH 0180/1265] add power-save-blocker first --- .../zh-CN/api/power-save-blocker.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs-translations/zh-CN/api/power-save-blocker.md diff --git a/docs-translations/zh-CN/api/power-save-blocker.md b/docs-translations/zh-CN/api/power-save-blocker.md new file mode 100644 index 00000000000..3a045eaea77 --- /dev/null +++ b/docs-translations/zh-CN/api/power-save-blocker.md @@ -0,0 +1,48 @@ +# powerSaveBlocker + +`powerSaveBlocker` 模块是用来阻止应用系统进入睡眠模式的,因此这允许应用保持系统和屏幕继续工作. + +例如: + +```javascript +const powerSaveBlocker = require('electron').powerSaveBlocker; + +var id = powerSaveBlocker.start('prevent-display-sleep'); +console.log(powerSaveBlocker.isStarted(id)); + +powerSaveBlocker.stop(id); +``` + +## 方法 + +`powerSaveBlocker` 模块有如下方法: + +### `powerSaveBlocker.start(type)` + +* `type` String - 强行保存阻塞类型. + * `prevent-app-suspension` - 阻止应用挂起. + 保持系统活跃,但是允许屏幕不亮. 用例: + 下载文件或者播放音频. + * `prevent-display-sleep`- 阻止应用进入休眠. 保持系统和屏幕活跃,屏幕一直亮. 用例: 播放音频. + +开始阻止系统进入睡眠模式.返回一个整数,这个整数标识了保持活跃的blocker. + +**注意:** `prevent-display-sleep` 有更高的优先级 +`prevent-app-suspension`. 只有最高优先级生效. 换句话说, `prevent-display-sleep` 优先级永远高于 +`prevent-app-suspension`. + +例如, A 请求调用了 `prevent-app-suspension`, B请求调用了 `prevent-display-sleep`. `prevent-display-sleep` +将一直工作,直到B停止调用. 在那之后, `prevent-app-suspension` +才起效. + +### `powerSaveBlocker.stop(id)` + +* `id` Integer - 通过 `powerSaveBlocker.start` 返回的保持活跃的 blocker id. + +让指定blocker 停止活跃. + +### `powerSaveBlocker.isStarted(id)` + +* `id` Integer - 通过 `powerSaveBlocker.start` 返回的保持活跃的 blocker id. + +返回 boolean, 是否对应的 `powerSaveBlocker` 已经启动. \ No newline at end of file From 48064ee7e9a81ed431649e883d42e8e0908da4e4 Mon Sep 17 00:00:00 2001 From: Robo Date: Mon, 14 Mar 2016 03:53:39 +0530 Subject: [PATCH 0181/1265] browser: fix retrieving webcontents from associated process id --- atom/browser/atom_browser_client.cc | 9 ++------- atom/browser/atom_permission_manager.cc | 16 ++++++---------- 2 files changed, 8 insertions(+), 17 deletions(-) diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index ca12723bb37..63a1ea46b16 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -46,11 +46,6 @@ namespace atom { namespace { -// The default routing id of WebContents. -// In Electron each RenderProcessHost only has one WebContents, so this ID is -// same for every WebContents. -int kDefaultRoutingID = 1; - // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; @@ -278,8 +273,8 @@ brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( void AtomBrowserClient::WebNotificationAllowed( int render_process_id, const base::Callback& callback) { - content::WebContents* web_contents = content::WebContents::FromRenderViewHost( - content::RenderViewHost::FromID(render_process_id, kDefaultRoutingID)); + content::WebContents* web_contents = + WebContentsPreferences::GetWebContentsFromProcessID(render_process_id); if (!web_contents) { callback.Run(false); return; diff --git a/atom/browser/atom_permission_manager.cc b/atom/browser/atom_permission_manager.cc index 720d1f93b32..f7523c07ff8 100644 --- a/atom/browser/atom_permission_manager.cc +++ b/atom/browser/atom_permission_manager.cc @@ -6,6 +6,7 @@ #include +#include "atom/browser/web_contents_preferences.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/permission_type.h" #include "content/public/browser/render_frame_host.h" @@ -17,17 +18,12 @@ namespace atom { namespace { -// Must be kept in sync with atom_browser_client.cc -int kDefaultRoutingID = 2; - bool WebContentsDestroyed(int process_id) { - auto rvh = content::RenderViewHost::FromID(process_id, kDefaultRoutingID); - if (rvh) { - auto contents = content::WebContents::FromRenderViewHost(rvh); - return contents->IsBeingDestroyed(); - } - - return true; + auto contents = + WebContentsPreferences::GetWebContentsFromProcessID(process_id); + if (!contents) + return true; + return contents->IsBeingDestroyed(); } } // namespace From 8378cbb1e84bad2380ef833147b79ddc2226bccf Mon Sep 17 00:00:00 2001 From: Robo Date: Mon, 14 Mar 2016 06:49:45 +0530 Subject: [PATCH 0182/1265] webcontents: provide position of match with found-in-page event --- atom/browser/api/atom_api_web_contents.cc | 1 + docs/api/web-contents.md | 1 + docs/api/web-view-tag.md | 1 + spec/webview-spec.js | 13 +++++++++++-- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index c8b597704cd..4a548cb4a33 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -456,6 +456,7 @@ void WebContents::FindReply(content::WebContents* web_contents, result.Set("requestId", request_id); result.Set("selectionArea", selection_rect); result.Set("finalUpdate", final_update); + result.Set("activeMatchOrdinal", active_match_ordinal); Emit("found-in-page", result); } else if (final_update) { result.Set("requestId", request_id); diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 8eda16b6860..5295b79ceb3 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -259,6 +259,7 @@ Returns: * `result` Object * `requestId` Integer * `finalUpdate` Boolean - Indicates if more responses are to follow. + * `activeMatchOrdinal` Integer (optional) - Position of the active match. * `matches` Integer (optional) - Number of Matches. * `selectionArea` Object (optional) - Coordinates of first match region. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index fa48ef60f3f..cba48e40db1 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -573,6 +573,7 @@ Returns: * `result` Object * `requestId` Integer * `finalUpdate` Boolean - Indicates if more responses are to follow. + * `activeMatchOrdinal` Integer (optional) - Position of the active match. * `matches` Integer (optional) - Number of Matches. * `selectionArea` Object (optional) - Coordinates of first match region. diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 5963709e6f0..2d0a6282be3 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -642,12 +642,21 @@ describe(' tag', function() { describe('found-in-page event', function() { it('emits when a request is made', function(done) { var requestId = null; + var totalMatches = null; + var activeMatchOrdinal = []; var listener = function(e) { assert.equal(e.result.requestId, requestId); if (e.result.finalUpdate) { assert.equal(e.result.matches, 3); - webview.stopFindInPage("clearSelection"); - done(); + totalMatches = e.result.matches; + listener2(); + } else { + activeMatchOrdinal.push(e.result.activeMatchOrdinal); + if (e.result.activeMatchOrdinal == totalMatches) { + assert.deepEqual(activeMatchOrdinal, [1, 2, 3]); + webview.stopFindInPage("clearSelection"); + done(); + } } }; var listener2 = function() { From 92a9c49a77b59c71408baad2483783747e41391d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 10:39:33 +0900 Subject: [PATCH 0183/1265] Update brightray for atom/brightray#203 --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index d6bafa3ac1b..bde17bffdf5 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit d6bafa3ac1b56b24e8944ebbc87ed51ad417a21d +Subproject commit bde17bffdf5ff978d5d831bdebb62d12bca6c715 From b3da5370c06e5e0c7755ba633ae0e1bcef7ca640 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:08:09 -0700 Subject: [PATCH 0184/1265] Add a new method to get the representation of an image --- atom/common/api/atom_api_native_image.h | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/common/api/atom_api_native_image.h b/atom/common/api/atom_api_native_image.h index 1f0fe946ba5..8bc21304041 100644 --- a/atom/common/api/atom_api_native_image.h +++ b/atom/common/api/atom_api_native_image.h @@ -61,6 +61,7 @@ class NativeImage : public mate::Wrappable { private: v8::Local ToPNG(v8::Isolate* isolate); v8::Local ToJPEG(v8::Isolate* isolate, int quality); + v8::Local AsNativeRepresentation(v8::Isolate* isolate, mate::Arguments* args); std::string ToDataURL(); bool IsEmpty(); gfx::Size GetSize(); From 262abc43f80811747c8689b85a2343ff42966a02 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:08:53 -0700 Subject: [PATCH 0185/1265] First hack at being able to return NSImage pointers --- atom/common/api/atom_api_native_image.cc | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 69ead046458..aac11fdfaaf 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -58,6 +58,20 @@ ScaleFactorPair kScaleFactorPairs[] = { { "@2.5x" , 2.5f }, }; +enum NativeRepresentation { + INVALID = 0, + AS_NSIMAGE, +}; + +struct NativeRepresentationPair { + const char* name; + NativeRepresentation rep; +}; + +NativeRepresentationPair kNativeRepresentations[] { + { "nsimage", NativeRepresentation::AS_NSIMAGE }, +}; + float GetScaleFactorFromPath(const base::FilePath& path) { std::string filename(path.BaseName().RemoveExtension().AsUTF8Unsafe()); @@ -184,6 +198,7 @@ mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) .SetMethod("toPng", &NativeImage::ToPNG) .SetMethod("toJpeg", &NativeImage::ToJPEG) + .SetMethod("asNativeRepresentation", &NativeImage::AsNativeRepresentation) .SetMethod("toDataURL", &NativeImage::ToDataURL) .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. .SetMethod("isEmpty", &NativeImage::IsEmpty) @@ -221,6 +236,47 @@ std::string NativeImage::ToDataURL() { return data_url; } +v8::Local NativeImage::AsNativeRepresentation(v8::Isolate* isolate, mate::Arguments* args) { + NativeRepresentation desiredRep = NativeRepresentation::INVALID; + void* ptr = nullptr; + std::string type; + + if (!args->GetNext(&type)) { + args->ThrowError(); + goto out; + } + + for (const NativeRepresentationPair& item : kNativeRepresentations) { + if (type.compare(item.name) == 0) { + desiredRep = item.rep; + break; + } + } + + if (desiredRep == NativeRepresentation::INVALID) { + args->ThrowError(); + goto out; + } + + switch (desiredRep) { +#if defined(OS_MACOSX) + case NativeRepresentation::AS_NSIMAGE: + ptr = reinterpret_cast(image_.AsNSImage()); + break; +#endif + default: + args->ThrowError(); + break; + } + +out: + + return node::Buffer::Copy( + isolate, + reinterpret_cast(ptr), + sizeof(void*)).ToLocalChecked(); +} + bool NativeImage::IsEmpty() { return image_.IsEmpty(); } From 5dea4b9b1cdc402e36749aa64b2e6e515e04f5fb Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:11:43 -0700 Subject: [PATCH 0186/1265] Add documentation --- docs/api/native-image.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/api/native-image.md b/docs/api/native-image.md index 515e89fba1a..2cae12feb47 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -133,6 +133,13 @@ Returns a [Buffer][buffer] that contains the image's `JPEG` encoded data. Returns the data URL of the image. +### `image.asNativeRepresentation(type)` + +Returns a pointer to an underlying native type (encoded as a [Buffer][buffer]) which can be used with native APIs. Note that in many cases, this pointer is a weak pointer to the underlying native image not a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. + +* `type` String (**required**) - one of: + * `nsimage` - (OS X only) a pointer to an `NSImage` + ### `image.isEmpty()` Returns a boolean whether the image is empty. From 7233c83874e6444a96045bffe511c87bf866361f Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:18:03 -0700 Subject: [PATCH 0187/1265] Linting --- atom/common/api/atom_api_native_image.cc | 19 +++++++++++-------- atom/common/api/atom_api_native_image.h | 4 +++- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index aac11fdfaaf..7a84f999949 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -198,7 +198,8 @@ mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) .SetMethod("toPng", &NativeImage::ToPNG) .SetMethod("toJpeg", &NativeImage::ToJPEG) - .SetMethod("asNativeRepresentation", &NativeImage::AsNativeRepresentation) + .SetMethod("asNativeRepresentation", + &NativeImage::AsNativeRepresentation) .SetMethod("toDataURL", &NativeImage::ToDataURL) .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. .SetMethod("isEmpty", &NativeImage::IsEmpty) @@ -236,28 +237,30 @@ std::string NativeImage::ToDataURL() { return data_url; } -v8::Local NativeImage::AsNativeRepresentation(v8::Isolate* isolate, mate::Arguments* args) { +v8::Local NativeImage::AsNativeRepresentation( + v8::Isolate* isolate, + mate::Arguments* args) { NativeRepresentation desiredRep = NativeRepresentation::INVALID; void* ptr = nullptr; std::string type; - + if (!args->GetNext(&type)) { args->ThrowError(); goto out; } - + for (const NativeRepresentationPair& item : kNativeRepresentations) { if (type.compare(item.name) == 0) { desiredRep = item.rep; break; } } - + if (desiredRep == NativeRepresentation::INVALID) { args->ThrowError(); goto out; } - + switch (desiredRep) { #if defined(OS_MACOSX) case NativeRepresentation::AS_NSIMAGE: @@ -268,9 +271,9 @@ v8::Local NativeImage::AsNativeRepresentation(v8::Isolate* isolate, m args->ThrowError(); break; } - + out: - + return node::Buffer::Copy( isolate, reinterpret_cast(ptr), diff --git a/atom/common/api/atom_api_native_image.h b/atom/common/api/atom_api_native_image.h index 8bc21304041..8b1329d2848 100644 --- a/atom/common/api/atom_api_native_image.h +++ b/atom/common/api/atom_api_native_image.h @@ -61,7 +61,9 @@ class NativeImage : public mate::Wrappable { private: v8::Local ToPNG(v8::Isolate* isolate); v8::Local ToJPEG(v8::Isolate* isolate, int quality); - v8::Local AsNativeRepresentation(v8::Isolate* isolate, mate::Arguments* args); + v8::Local AsNativeRepresentation( + v8::Isolate* isolate, + mate::Arguments* args); std::string ToDataURL(); bool IsEmpty(); gfx::Size GetSize(); From 248ac5c37b6eeeaefca70d32cbc3adf737a7da93 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:25:49 -0700 Subject: [PATCH 0188/1265] Add unit tests --- spec/api-native-image-spec.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 043a914578c..587ea876f29 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -34,5 +34,32 @@ describe('nativeImage module', () => { assert.equal(image.getSize().height, 190); assert.equal(image.getSize().width, 538); }); + + it('Gets an NSImage pointer on OS X', () => { + if (process.platform !== 'darwin') return; + + const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; + const image = nativeImage.createFromPath(imagePath); + const nsimage = image.asNativeRepresentation('nsimage'); + + assert.equal(nsimage.length, 8); + + // If all bytes are null, that's Bad + assert.equal(nsimage.reduce((acc,x) => acc || (x != 0)), true); + }); + + it('Throws when asNativeRepresentation gets a bogus value', () => { + const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; + const image = nativeImage.createFromPath(imagePath); + + let shouldDie = true; + try { + image.asNativeRepresentation('__foobar__'); + } catch (e) { + shouldDie = false; + } + + assert.equal(shouldDie, false); + }); }); }); From 63d917482226d5ce86038262fcd1993604883bbd Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Sun, 13 Mar 2016 20:27:44 -0700 Subject: [PATCH 0189/1265] :fire: build warning on Win32 --- atom/common/api/atom_api_native_image.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 7a84f999949..6c22830f674 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -267,6 +267,7 @@ v8::Local NativeImage::AsNativeRepresentation( ptr = reinterpret_cast(image_.AsNSImage()); break; #endif + case NativeRepresentation::INVALID: default: args->ThrowError(); break; From 9a13d559e9c774c2f84a77af2663f8a81001ca30 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 13:59:31 +0900 Subject: [PATCH 0190/1265] Leak the JavascriptEnvironment on exit This is to work around the bug that V8 would be waiting for background tasks to finish on exit, while somehow it waits forever in Electron, more about this can be found at https://github.com/atom/electron/issues/4767. On the other handle there is actually no need to gracefully shutdown V8 on exit in the main process, we already ensured all necessary resources get cleaned up, and it would make quitting faster. --- atom/browser/atom_browser_main_parts.cc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index a046f34287e..a711c1c8d2b 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -46,6 +46,14 @@ AtomBrowserMainParts::AtomBrowserMainParts() } AtomBrowserMainParts::~AtomBrowserMainParts() { + // Leak the JavascriptEnvironment on exit. + // This is to work around the bug that V8 would be waiting for background + // tasks to finish on exit, while somehow it waits forever in Electron, more + // about this can be found at https://github.com/atom/electron/issues/4767. + // On the other handle there is actually no need to gracefully shutdown V8 + // on exit in the main process, we already ensured all necessary resources get + // cleaned up, and it would make quitting faster. + ignore_result(js_env_.release()); } // static @@ -172,14 +180,6 @@ void AtomBrowserMainParts::PostMainMessageLoopRun() { ++iter; callback.Run(); } - - // Destroy JavaScript environment immediately after running destruction - // callbacks. - gc_timer_.Stop(); - node_debugger_.reset(); - atom_bindings_.reset(); - node_bindings_.reset(); - js_env_.reset(); } } // namespace atom From 152e6af4b4c962d118a14e719544e4c4fdd08d55 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 14:54:45 +0900 Subject: [PATCH 0191/1265] spec: Add test case for #4785 --- spec/api-app-spec.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index cbf8223401c..1b12f6f733c 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -7,7 +7,11 @@ const app = remote.require('electron').app; const BrowserWindow = remote.require('electron').BrowserWindow; describe('electron module', function() { - it ('can prevent exposing internal modules to require', function(done) { + it('allows old style require by default', function() { + require('shell'); + }); + + it('can prevent exposing internal modules to require', function(done) { const electron = require('electron'); const clipboard = require('clipboard'); assert.equal(typeof clipboard, 'object'); From 81a16b424f5760f091885d7ec3d2708d91aa2cf9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 16:28:01 +0900 Subject: [PATCH 0192/1265] Add extension to filename automatically for GTK+ save dialog --- atom/browser/ui/file_dialog_gtk.cc | 34 +++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/atom/browser/ui/file_dialog_gtk.cc b/atom/browser/ui/file_dialog_gtk.cc index ed79449655f..5a82a849395 100644 --- a/atom/browser/ui/file_dialog_gtk.cc +++ b/atom/browser/ui/file_dialog_gtk.cc @@ -39,7 +39,8 @@ class FileChooserDialog { const std::string& title, const base::FilePath& default_path, const Filters& filters) - : dialog_scope_(parent_window) { + : dialog_scope_(parent_window), + filters_(filters) { const char* confirm_text = GTK_STOCK_OK; if (action == GTK_FILE_CHOOSER_ACTION_SAVE) confirm_text = GTK_STOCK_SAVE; @@ -111,7 +112,7 @@ class FileChooserDialog { base::FilePath GetFileName() const { gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_)); - base::FilePath path(filename); + base::FilePath path = AddExtensionForFilename(filename); g_free(filename); return path; } @@ -121,7 +122,8 @@ class FileChooserDialog { GSList* filenames = gtk_file_chooser_get_filenames( GTK_FILE_CHOOSER(dialog_)); for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) { - base::FilePath path(static_cast(iter->data)); + base::FilePath path = AddExtensionForFilename( + static_cast(iter->data)); g_free(iter->data); paths.push_back(path); } @@ -135,11 +137,13 @@ class FileChooserDialog { private: void AddFilters(const Filters& filters); + base::FilePath AddExtensionForFilename(const gchar* filename) const; atom::NativeWindow::DialogScope dialog_scope_; GtkWidget* dialog_; + Filters filters_; SaveDialogCallback save_callback_; OpenDialogCallback open_callback_; @@ -184,6 +188,30 @@ void FileChooserDialog::AddFilters(const Filters& filters) { } } +base::FilePath FileChooserDialog::AddExtensionForFilename( + const gchar* filename) const { + base::FilePath path(filename); + GtkFileFilter* selected_filter = + gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog_)); + if (!selected_filter) + return path; + + GSList* filters = gtk_file_chooser_list_filters(GTK_FILE_CHOOSER(dialog_)); + int i = g_slist_index(filters, selected_filter); + g_slist_free(filters); + if (i >= filters_.size()) + return path; + + const auto& extensions = filters_[i].second; + for (const auto& extension : extensions) { + if (extension == "*" || path.MatchesExtension("." + extension)) + return path; + } + + return path.AddExtension(extensions[0]); +} + + } // namespace bool ShowOpenDialog(atom::NativeWindow* parent_window, From 06a8db8a66c4ccb07bf1c329d4ee6f71ba56a1f5 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Mon, 14 Mar 2016 15:43:04 +0800 Subject: [PATCH 0193/1265] add protocol && session first --- docs-translations/zh-CN/api/protocol.md | 183 +++++++++ docs-translations/zh-CN/api/session.md | 481 ++++++++++++++++++++++++ 2 files changed, 664 insertions(+) create mode 100644 docs-translations/zh-CN/api/protocol.md create mode 100644 docs-translations/zh-CN/api/session.md diff --git a/docs-translations/zh-CN/api/protocol.md b/docs-translations/zh-CN/api/protocol.md new file mode 100644 index 00000000000..a7dab97c5d5 --- /dev/null +++ b/docs-translations/zh-CN/api/protocol.md @@ -0,0 +1,183 @@ +# 协议 + +`protocol` 模块可以注册一个自定义协议,或者使用一个已经存在的协议. + +例子,使用一个与 `file://` 功能相似的协议 : + +```javascript +const electron = require('electron'); +const app = electron.app; +const path = require('path'); + +app.on('ready', function() { + var protocol = electron.protocol; + protocol.registerFileProtocol('atom', function(request, callback) { + var url = request.url.substr(7); + callback({path: path.normalize(__dirname + '/' + url)}); + }, function (error) { + if (error) + console.error('Failed to register protocol') + }); +}); +``` + +**注意:** 这个模块只有在 `app` 模块的 `ready` 事件触发之后才可使用. + +## 方法 + +`protocol` 模块有如下方法: + +### `protocol.registerStandardSchemes(schemes)` + +* `schemes` Array - 将一个自定义的方案注册为标准的方案. + +一个标准的 `scheme` 遵循 RFC 3986 的 +[generic URI syntax](https://tools.ietf.org/html/rfc3986#section-3) 标准. 这包含了 `file:` 和 `filesystem:`. + +### `protocol.registerServiceWorkerSchemes(schemes)` + +* `schemes` Array - 将一个自定义的方案注册为处理 service workers. + +### `protocol.registerFileProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +注册一个协议,用来发送响应文件.当通过这个协议来发起一个请求的时候,将使用 `handler(request, callback)` 来调用 +`handler` .当 `scheme` 被成功注册或者完成(错误)时失败,将使用 `completion(null)` 调用 `completion`. + +* `request` Object + * `url` String + * `referrer` String + * `method` String + * `uploadData` Array (可选) +* `callback` Function + +`uploadData` 是一个 `data` 对象数组: + +* `data` Object + * `bytes` Buffer - 被发送的内容. + * `file` String - 上传的文件路径. + +为了处理请求,调用 `callback` 时需要使用文件路径或者一个带 `path` 参数的对象, 例如 `callback(filePath)` 或 +`callback({path: filePath})`. + +当不使用任何参数调用 `callback` 时,你可以指定一个数字或一个带有 `error` 参数的对象,来标识 `request` 失败.你可以使用的 error number 可以参考 +[net error list][net-error]. + +默认 `scheme` 会被注册为一个 `http:` 协议,它与遵循 "generic URI syntax" 规则的协议解析不同,例如 `file:` ,所以你或许应该调用 `protocol.registerStandardSchemes` 来创建一个标准的 scheme. + +### `protocol.registerBufferProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +注册一个 `scheme` 协议,用来发送响应 `Buffer` . + +这个方法的用法类似 `registerFileProtocol`,除非使用一个 `Buffer` 对象,或一个有 `data`, +`mimeType`, 和 `charset` 属性的对象来调用 `callback` . + +例子: + +```javascript +protocol.registerBufferProtocol('atom', function(request, callback) { + callback({mimeType: 'text/html', data: new Buffer('
Response
')}); +}, function (error) { + if (error) + console.error('Failed to register protocol') +}); +``` + +### `protocol.registerStringProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +注册一个 `scheme` 协议,用来发送响应 `String` . + +这个方法的用法类似 `registerFileProtocol`,除非使用一个 `String` 对象,或一个有 `data`, +`mimeType`, 和 `charset` 属性的对象来调用 `callback` . + +### `protocol.registerHttpProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +注册一个 `scheme` 协议,用来发送 HTTP 请求作为响应. + +这个方法的用法类似 `registerFileProtocol`,除非使用一个 `redirectRequest` 对象,或一个有 `url`, `method`, +`referrer`, `uploadData` 和 `session` 属性的对象来调用 `callback` . + +* `redirectRequest` Object + * `url` String + * `method` String + * `session` Object (可选) + * `uploadData` Object (可选) + +默认这个 HTTP 请求会使用当前 session .如果你想使用不同的session值,你应该设置 `session` 为 `null`. + +POST 请求应当包含 `uploadData` 对象. + +* `uploadData` object + * `contentType` String - 内容的 MIME type. + * `data` String - 被发送的内容. + +### `protocol.unregisterProtocol(scheme[, completion])` + +* `scheme` String +* `completion` Function (可选) + +注销自定义协议 `scheme`. + +### `protocol.isProtocolHandled(scheme, callback)` + +* `scheme` String +* `callback` Function + +将使用一个布尔值来调用 `callback` ,这个布尔值标识了是否已经存在 `scheme` 的句柄了. + +### `protocol.interceptFileProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +拦截 `scheme` 协议并且使用 `handler` 作为协议的新的句柄来发送响应文件. + +### `protocol.interceptStringProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +拦截 `scheme` 协议并且使用 `handler` 作为协议的新的句柄来发送响应 `String`. + +### `protocol.interceptBufferProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (可选) + +拦截 `scheme` 协议并且使用 `handler` 作为协议的新的句柄来发送响应 `Buffer`. + +### `protocol.interceptHttpProtocol(scheme, handler[, completion])` + +* `scheme` String +* `handler` Function +* `completion` Function (optional) + +拦截 `scheme` 协议并且使用 `handler` 作为协议的新的句柄来发送新的响应 HTTP 请求. +Intercepts `scheme` protocol and uses `handler` as the protocol's new handler +which sends a new HTTP request as a response. + +### `protocol.uninterceptProtocol(scheme[, completion])` + +* `scheme` String +* `completion` Function +取消对 `scheme` 的拦截,使用它的原始句柄进行处理. + +[net-error]: https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h \ No newline at end of file diff --git a/docs-translations/zh-CN/api/session.md b/docs-translations/zh-CN/api/session.md new file mode 100644 index 00000000000..b9664c08e65 --- /dev/null +++ b/docs-translations/zh-CN/api/session.md @@ -0,0 +1,481 @@ +# session + +`session` 模块可以用来创建一个新的 `Session` 对象. + +你也可以通过使用 [`webContents`](web-contents.md) 的属性 `session` 来使用一个已有页面的 `session` ,`webContents` 是[`BrowserWindow`](browser-window.md) 的属性. + +```javascript +const BrowserWindow = require('electron').BrowserWindow; + +var win = new BrowserWindow({ width: 800, height: 600 }); +win.loadURL("http://github.com"); + +var ses = win.webContents.session; +``` + +## 方法 + +`session` 模块有如下方法: + +### session.fromPartition(partition) + +* `partition` String + +从字符串 `partition` 返回一个新的 `Session` 实例. + +如果 `partition` 以 `persist:` 开头,那么这个page将使用一个持久的 session,这个 session 将对应用的所有 page 可用.如果没前缀,这个 page 将使用一个历史 session.如果 `partition` 为空,那么将返回应用的默认 session . + +## 属性 + +`session` 模块有如下属性: + +### session.defaultSession + +返回应用的默认 session 对象. + +## Class: Session + +可以在 `session` 模块中创建一个 `Session` 对象 : + +```javascript +const session = require('electron').session; + +var ses = session.fromPartition('persist:name'); +``` + +### 实例事件 + +实例 `Session` 有以下事件: + +#### Event: 'will-download' + +* `event` Event +* `item` [DownloadItem](download-item.md) +* `webContents` [WebContents](web-contents.md) + +当 Electron 将要从 `webContents` 下载 `item` 时触发. + +调用 `event.preventDefault()` 可以取消下载,并且在进程的下个 tick中,这个 `item` 也不可用. + +```javascript +session.defaultSession.on('will-download', function(event, item, webContents) { + event.preventDefault(); + require('request')(item.getURL(), function(data) { + require('fs').writeFileSync('/somewhere', data); + }); +}); +``` + +### 实例方法 + +实例 `Session` 有以下方法: + +#### `ses.cookies` + +`cookies` 赋予你全力来查询和修改 cookies. 例如: + +```javascript +// 查询所有 cookies. +session.defaultSession.cookies.get({}, function(error, cookies) { + console.log(cookies); +}); + +// 查询与指定 url 相关的所有 cookies. +session.defaultSession.cookies.get({ url : "http://www.github.com" }, function(error, cookies) { + console.log(cookies); +}); + +// 设置 cookie; +// may overwrite equivalent cookies if they exist. +var cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" }; +session.defaultSession.cookies.set(cookie, function(error) { + if (error) + console.error(error); +}); +``` + +#### `ses.cookies.get(filter, callback)` + +* `filter` Object + * `url` String (可选) - 与获取 cookies 相关的 + `url`.不设置的话就是从所有 url 获取 cookies . + * `name` String (可选) - 通过 name 过滤 cookies. + * `domain` String (可选) - 获取对应域名或子域名的 cookies . + * `path` String (可选) - 获取对应路径的 cookies . + * `secure` Boolean (可选) - 通过安全性过滤 cookies. + * `session` Boolean (可选) - 过滤掉 session 或 持久的 cookies. +* `callback` Function + +发送一个请求,希望获得所有匹配 `details` 的 cookies, +在完成的时候,将通过 `callback(error, cookies)` 调用 `callback`. + +`cookies`是一个 `cookie` 对象. + +* `cookie` Object + * `name` String - cookie 名. + * `value` String - cookie值. + * `domain` String - cookie域名. + * `hostOnly` String - 是否 cookie 是一个 host-only cookie. + * `path` String - cookie路径. + * `secure` Boolean - 是否是安全 cookie. + * `httpOnly` Boolean - 是否只是 HTTP cookie. + * `session` Boolean - cookie 是否是一个 session cookie 或一个带截至日期的持久 + cookie . + * `expirationDate` Double (可选) - cookie的截至日期,数值为UNIX纪元以来的秒数. 对session cookies 不提供. + +#### `ses.cookies.set(details, callback)` + +* `details` Object + * `url` String - 与获取 cookies 相关的 + `url`. + * `name` String - cookie 名. 忽略默认为空. + * `value` String - cookie 值. 忽略默认为空. + * `domain` String - cookie的域名. 忽略默认为空. + * `path` String - cookie 的路径. 忽略默认为空. + * `secure` Boolean - 是否已经进行了安全性标识. 默认为 + false. + * `session` Boolean - 是否已经 HttpOnly 标识. 默认为 false. + * `expirationDate` Double - cookie的截至日期,数值为UNIX纪元以来的秒数. 如果忽略, cookie 变为 session cookie. +* `callback` Function + +使用 `details` 设置 cookie, 完成时使用 `callback(error)` 掉哟个 `callback` . + +#### `ses.cookies.remove(url, name, callback)` + +* `url` String - 与 cookies 相关的 + `url`. +* `name` String - 需要删除的 cookie 名. +* `callback` Function + +删除匹配 `url` 和 `name` 的 cookie, 完成时使用 `callback()`调用`callback`. + +#### `ses.getCacheSize(callback)` + +* `callback` Function + * `size` Integer - 单位 bytes 的缓存 size. + +返回 session 的当前缓存 size . + +#### `ses.clearCache(callback)` + +* `callback` Function - 操作完成时调用 + +清空 session 的 HTTP 缓存. + +#### `ses.clearStorageData([options, ]callback)` + +* `options` Object (可选) + * `origin` String - 应当遵循 `window.location.origin` 的格式 + `scheme://host:port`. + * `storages` Array - 需要清理的 storages 类型, 可以包含 : + `appcache`, `cookies`, `filesystem`, `indexdb`, `local storage`, + `shadercache`, `websql`, `serviceworkers` + * `quotas` Array - 需要清理的类型指标, 可以包含: + `temporary`, `persistent`, `syncable`. +* `callback` Function - 操作完成时调用. + +清除 web storages 的数据. + +#### `ses.flushStorageData()` + +将没有写入的 DOMStorage 写入磁盘. + +#### `ses.setProxy(config, callback)` + +* `config` Object + * `pacScript` String - 与 PAC 文件相关的 URL. + * `proxyRules` String - 代理使用规则. +* `callback` Function - 操作完成时调用. + +设置 proxy settings. + +当 `pacScript` 和 `proxyRules` 一同提供时,将忽略 `proxyRules`,并且使用 `pacScript` 配置 . + +`proxyRules` 需要遵循下面的规则: + +``` +proxyRules = schemeProxies[";"] +schemeProxies = ["="] +urlScheme = "http" | "https" | "ftp" | "socks" +proxyURIList = [","] +proxyURL = ["://"][":"] +``` + +例子: + +* `http=foopy:80;ftp=foopy2` - 为 `http://` URL 使用 HTTP 代理 `foopy:80` , 和为 `ftp://` URL + HTTP 代理 `foopy2:80` . +* `foopy:80` - 为所有 URL 使用 HTTP 代理 `foopy:80` . +* `foopy:80,bar,direct://` - 为所有 URL 使用 HTTP 代理 `foopy:80` , 如果 `foopy:80` 不可用,则切换使用 `bar`, 再往后就不使用代理了. +* `socks4://foopy` - 为所有 URL 使用 SOCKS v4 代理 `foopy:1080`. +* `http=foopy,socks5://bar.com` - 为所有 URL 使用 HTTP 代理 `foopy`, 如果 `foopy`不可用,则切换到 SOCKS5 代理 `bar.com`. +* `http=foopy,direct://` - 为所有http url 使用 HTTP 代理,如果 `foopy`不可用,则不使用代理. +* `http=foopy;socks=foopy2` - 为所有http url 使用 `foopy` 代理,为所有其他 url 使用 `socks4://foopy2` 代理. + +### `ses.resolveProxy(url, callback)` + +* `url` URL +* `callback` Function + +解析 `url` 的代理信息.当请求完成的时候使用 `callback(proxy)` 调用 `callback`. + +#### `ses.setDownloadPath(path)` + +* `path` String - 下载地址 + +设置下载保存地址,默认保存地址为各自 app 应用的 `Downloads`目录. + +#### `ses.enableNetworkEmulation(options)` + +* `options` Object + * `offline` Boolean - 是否模拟网络故障. + * `latency` Double - 每毫秒的 RTT + * `downloadThroughput` Double - 每 Bps 的下载速率. + * `uploadThroughput` Double - 每 Bps 的上载速率. + +通过给定配置的 `session` 来模拟网络. + +```javascript +// 模拟 GPRS 连接,使用的 50kbps 流量,500 毫秒的 rtt. +window.webContents.session.enableNetworkEmulation({ + latency: 500, + downloadThroughput: 6400, + uploadThroughput: 6400 +}); + +// 模拟网络故障. +window.webContents.session.enableNetworkEmulation({offline: true}); +``` + +#### `ses.disableNetworkEmulation()` + +停止所有已经使用 `session` 的活跃模拟网络. +重置为原始网络类型. + +#### `ses.setCertificateVerifyProc(proc)` + +* `proc` Function + +为 `session` 设置证书验证过程,当请求一个服务器的证书验证时,使用 `proc(hostname, certificate, callback)` 调用 `proc`.调用 `callback(true)` 来接收证书,调用 `callback(false)` 来拒绝验证证书. + +调用了 `setCertificateVerifyProc(null)` ,则将会回复到默认证书验证过程. + +```javascript +myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, callback) { + if (hostname == 'github.com') + callback(true); + else + callback(false); +}); +``` + +#### `ses.setPermissionRequestHandler(handler)` + +* `handler` Function + * `webContents` Object - [WebContents](web-contents.md) 请求许可. + * `permission` String - 枚举了 'media', 'geolocation', 'notifications', 'midiSysex', 'pointerLock', 'fullscreen'. + * `callback` Function - 允许或禁止许可. + +为对应 `session` 许可请求设置响应句柄.调用 `callback(true)` 接收许可,调用 `callback(false)` 禁止许可. + +```javascript +session.fromPartition(partition).setPermissionRequestHandler(function(webContents, permission, callback) { + if (webContents.getURL() === host) { + if (permission == "notifications") { + callback(false); // denied. + return; + } + } + + callback(true); +}); +``` + +#### `ses.clearHostResolverCache([callback])` + +* `callback` Function (可选) - 操作结束调用. + +清除主机解析缓存. + +#### `ses.webRequest` + +在其生命周期的不同阶段,`webRequest` API 设置允许拦截并修改请求内容. + +每个 API 接收一可选的 `filter` 和 `listener`,当 API 事件发生的时候使用 `listener(details)` 调用 `listener`,`details` 是一个用来描述请求的对象.为 `listener` 使用 `null` 则会退定事件. + +`filter` 是一个拥有 `urls` 属性的对象,这是一个 url 模式数组,这用来过滤掉不匹配指定 url 模式的请求.如果忽略 `filter` ,那么所有请求都将可以成功匹配. + +所有事件的 `listener` 都有一个回调事件,当 `listener` 完成它的工作的时候,它将使用一个 `response` 对象来调用. + +```javascript +// 将所有请求的代理都修改为下列 url. +var filter = { + urls: ["https://*.github.com/*", "*://electron.github.io"] +}; + +session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, callback) { + details.requestHeaders['User-Agent'] = "MyAgent"; + callback({cancel: false, requestHeaders: details.requestHeaders}); +}); +``` + +#### `ses.webRequest.onBeforeRequest([filter, ]listener)` + +* `filter` Object +* `listener` Function + +当一个请求即将开始的时候,使用 `listener(details, callback)` 调用 `listener`. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `uploadData` Array (可选) +* `callback` Function + +`uploadData` 是一个 `data` 数组对象: + +* `data` Object + * `bytes` Buffer - 被发送的内容. + * `file` String - 上载文件路径. + +`callback` 必须使用一个 `response` 对象来调用: + +* `response` Object + * `cancel` Boolean (可选) + * `redirectURL` String (可选) - 原始请求阻止发送或完成,而不是重定向. + +#### `ses.webRequest.onBeforeSendHeaders([filter, ]listener)` + +* `filter` Object +* `listener` Function + +一旦请求报文头可用了,在发送 HTTP 请求的之前,使用 `listener(details, callback)` 调用 `listener`.这也许会在服务器发起一个tcp 连接,但是在发送任何 http 数据之前发生. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `requestHeaders` Object +* `callback` Function + +必须使用一个 `response` 对象来调用 `callback` : + +* `response` Object + * `cancel` Boolean (可选) + * `requestHeaders` Object (可选) - 如果提供了,将使用这些 headers 来创建请求. + +#### `ses.webRequest.onSendHeaders([filter, ]listener)` + +* `filter` Object +* `listener` Function + +在一个请求正在发送到服务器的时候,使用 `listener(details)` 来调用 `listener` ,之前 `onBeforeSendHeaders` 修改部分响应可用,同时取消监听. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `requestHeaders` Object + +#### `ses.webRequest.onHeadersReceived([filter,] listener)` + +* `filter` Object +* `listener` Function + +当 HTTP 请求报文头已经到达的时候,使用 `listener(details, callback)` 调用 `listener` . + +* `details` Object + * `id` String + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `statusLine` String + * `statusCode` Integer + * `responseHeaders` Object +* `callback` Function + +必须使用一个 `response` 对象来调用 `callback` : + +* `response` Object + * `cancel` Boolean + * `responseHeaders` Object (可选) - 如果提供, 服务器将假定使用这些头来响应. + +#### `ses.webRequest.onResponseStarted([filter, ]listener)` + +* `filter` Object +* `listener` Function + +当响应body的首字节到达的时候,使用 `listener(details)` 调用 `listener`.对 http 请求来说,这意味着状态线和响应头可用了. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `responseHeaders` Object + * `fromCache` Boolean - 标识响应是否来自磁盘 + cache. + * `statusCode` Integer + * `statusLine` String + +#### `ses.webRequest.onBeforeRedirect([filter, ]listener)` + +* `filter` Object +* `listener` Function + +当服务器的重定向初始化正要启动时,使用 `listener(details)` 调用 `listener`. + +* `details` Object + * `id` String + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `redirectURL` String + * `statusCode` Integer + * `ip` String (可选) - 请求的真实服务器ip 地址 + * `fromCache` Boolean + * `responseHeaders` Object + +#### `ses.webRequest.onCompleted([filter, ]listener)` + +* `filter` Object +* `listener` Function + +当请求完成的时候,使用 `listener(details)` 调用 `listener`. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `responseHeaders` Object + * `fromCache` Boolean + * `statusCode` Integer + * `statusLine` String + +#### `ses.webRequest.onErrorOccurred([filter, ]listener)` + +* `filter` Object +* `listener` Function + +当一个错误发生的时候,使用 `listener(details)` 调用 `listener`. + +* `details` Object + * `id` Integer + * `url` String + * `method` String + * `resourceType` String + * `timestamp` Double + * `fromCache` Boolean + * `error` String - 错误描述. \ No newline at end of file From c2797e186446ff456b1f74450f1e5fc1b4aa6836 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 17:08:32 +0900 Subject: [PATCH 0194/1265] Replace extension with the one in filter --- atom/browser/ui/file_dialog_gtk.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/ui/file_dialog_gtk.cc b/atom/browser/ui/file_dialog_gtk.cc index 5a82a849395..6d19a2eda46 100644 --- a/atom/browser/ui/file_dialog_gtk.cc +++ b/atom/browser/ui/file_dialog_gtk.cc @@ -208,7 +208,7 @@ base::FilePath FileChooserDialog::AddExtensionForFilename( return path; } - return path.AddExtension(extensions[0]); + return path.ReplaceExtension(extensions[0]); } From e92d002eec310fd9b534bf7694c017490746fdaf Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 14 Mar 2016 17:22:09 +0900 Subject: [PATCH 0195/1265] Bump v0.37.2 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index 24456ca479d..df7ec4ed329 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.1', + 'version%': '0.37.2', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 613fa39e9da..06405d836b4 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.37.1 + 0.37.2 CFBundleShortVersionString - 0.37.1 + 0.37.2 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 3b587f62da8..be2e5666bbf 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,1,0 - PRODUCTVERSION 0,37,1,0 + FILEVERSION 0,37,2,0 + PRODUCTVERSION 0,37,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.1" + VALUE "FileVersion", "0.37.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.37.1" + VALUE "ProductVersion", "0.37.2" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 27b3fec626f..8821ec4e159 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 1 +#define ATOM_PATCH_VERSION 2 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index a4e3686bffd..21ac10cff25 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.1", + "version": "0.37.2", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From f8f3fba433190437c400ca1814ace640200671b3 Mon Sep 17 00:00:00 2001 From: Robo Date: Sun, 13 Mar 2016 09:46:33 +0530 Subject: [PATCH 0196/1265] webview: allow setting background color --- atom/browser/api/atom_api_web_contents.cc | 6 ---- atom/browser/api/atom_api_web_contents.h | 1 - atom/browser/web_view_guest_delegate.cc | 34 +++----------------- atom/browser/web_view_guest_delegate.h | 6 ---- atom/common/api/api_messages.h | 2 ++ atom/renderer/atom_render_view_observer.cc | 9 ++++++ atom/renderer/atom_render_view_observer.h | 1 + lib/browser/guest-view-manager.js | 8 ----- lib/renderer/web-view/guest-view-internal.js | 3 -- lib/renderer/web-view/web-view-attributes.js | 15 --------- lib/renderer/web-view/web-view-constants.js | 1 - 11 files changed, 17 insertions(+), 69 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index c8b597704cd..e5ea7e32a29 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1100,11 +1100,6 @@ void WebContents::SetSize(const SetSizeParams& params) { guest_delegate_->SetSize(params); } -void WebContents::SetAllowTransparency(bool allow) { - if (guest_delegate_) - guest_delegate_->SetAllowTransparency(allow); -} - bool WebContents::IsGuest() const { return type_ == WEB_VIEW; } @@ -1202,7 +1197,6 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("setSize", &WebContents::SetSize) - .SetMethod("setAllowTransparency", &WebContents::SetAllowTransparency) .SetMethod("isGuest", &WebContents::IsGuest) .SetMethod("getWebPreferences", &WebContents::GetWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index d98b838fb46..b734dc304df 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -131,7 +131,6 @@ class WebContents : public mate::TrackableObject, // Methods for creating . void SetSize(const SetSizeParams& params); - void SetAllowTransparency(bool allow); bool IsGuest() const; // Callback triggered on permission response. diff --git a/atom/browser/web_view_guest_delegate.cc b/atom/browser/web_view_guest_delegate.cc index 38f0fb1783f..47fcc204a4d 100644 --- a/atom/browser/web_view_guest_delegate.cc +++ b/atom/browser/web_view_guest_delegate.cc @@ -5,6 +5,7 @@ #include "atom/browser/web_view_guest_delegate.h" #include "atom/browser/api/atom_api_web_contents.h" +#include "atom/common/api/api_messages.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" @@ -22,8 +23,7 @@ const int kDefaultHeight = 300; } // namespace WebViewGuestDelegate::WebViewGuestDelegate() - : guest_opaque_(true), - guest_host_(nullptr), + : guest_host_(nullptr), auto_size_enabled_(false), is_full_page_plugin_(false), api_web_contents_(nullptr) { @@ -96,23 +96,6 @@ void WebViewGuestDelegate::SetSize(const SetSizeParams& params) { auto_size_enabled_ = enable_auto_size; } -void WebViewGuestDelegate::SetAllowTransparency(bool allow) { - if (guest_opaque_ != allow) - return; - - auto render_view_host = web_contents()->GetRenderViewHost(); - guest_opaque_ = !allow; - if (!render_view_host->GetWidget()->GetView()) - return; - - if (guest_opaque_) { - render_view_host->GetWidget()->GetView()->SetBackgroundColorToDefault(); - } else { - render_view_host->GetWidget()->GetView()->SetBackgroundColor( - SK_ColorTRANSPARENT); - } -} - void WebViewGuestDelegate::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { @@ -121,16 +104,9 @@ void WebViewGuestDelegate::HandleKeyboardEvent( } void WebViewGuestDelegate::RenderViewReady() { - // We don't want to accidentally set the opacity of an interstitial page. - // WebContents::GetRenderWidgetHostView will return the RWHV of an - // interstitial page if one is showing at this time. We only want opacity - // to apply to web pages. - auto render_view_host_view = - web_contents()->GetRenderViewHost()->GetWidget()->GetView(); - if (guest_opaque_) - render_view_host_view->SetBackgroundColorToDefault(); - else - render_view_host_view->SetBackgroundColor(SK_ColorTRANSPARENT); + // Set default UA-dependent background as transparent. + api_web_contents_->Send(new AtomViewMsg_SetTransparentBackground( + api_web_contents_->routing_id())); } void WebViewGuestDelegate::DidCommitProvisionalLoadForFrame( diff --git a/atom/browser/web_view_guest_delegate.h b/atom/browser/web_view_guest_delegate.h index 65e0bcde191..d4549e8dba4 100644 --- a/atom/browser/web_view_guest_delegate.h +++ b/atom/browser/web_view_guest_delegate.h @@ -49,9 +49,6 @@ class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate, // and normal sizes. void SetSize(const SetSizeParams& params); - // Sets the transparency of the guest. - void SetAllowTransparency(bool allow); - // Transfer the keyboard event to embedder. void HandleKeyboardEvent(content::WebContents* source, const content::NativeWebKeyboardEvent& event); @@ -85,9 +82,6 @@ class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate, // Returns the default size of the guestview. gfx::Size GetDefaultSize() const; - // Stores whether the contents of the guest can be transparent. - bool guest_opaque_; - // The WebContents that attaches this guest view. content::WebContents* embedder_web_contents_; diff --git a/atom/common/api/api_messages.h b/atom/common/api/api_messages.h index eeb26614847..e98f1bdfba0 100644 --- a/atom/common/api/api_messages.h +++ b/atom/common/api/api_messages.h @@ -37,3 +37,5 @@ IPC_MESSAGE_ROUTED2(AtomViewMsg_Message, // Sent by the renderer when the draggable regions are updated. IPC_MESSAGE_ROUTED1(AtomViewHostMsg_UpdateDraggableRegions, std::vector /* regions */) + +IPC_MESSAGE_ROUTED0(AtomViewMsg_SetTransparentBackground) diff --git a/atom/renderer/atom_render_view_observer.cc b/atom/renderer/atom_render_view_observer.cc index cdbdb3d7c3c..19eaec9e07b 100644 --- a/atom/renderer/atom_render_view_observer.cc +++ b/atom/renderer/atom_render_view_observer.cc @@ -22,6 +22,7 @@ #include "ipc/ipc_message_macros.h" #include "net/base/net_module.h" #include "net/grit/net_resources.h" +#include "third_party/skia/include/core/SkColor.h" #include "third_party/WebKit/public/web/WebDraggableRegion.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" @@ -113,6 +114,8 @@ bool AtomRenderViewObserver::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AtomRenderViewObserver, message) IPC_MESSAGE_HANDLER(AtomViewMsg_Message, OnBrowserMessage) + IPC_MESSAGE_HANDLER(AtomViewMsg_SetTransparentBackground, + OnSetTransparentBackground) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -148,4 +151,10 @@ void AtomRenderViewObserver::OnBrowserMessage(const base::string16& channel, } } +void AtomRenderViewObserver::OnSetTransparentBackground() { + if (!render_view()->GetWebView()) + return; + render_view()->GetWebView()->setBaseBackgroundColor(SK_ColorTRANSPARENT); +} + } // namespace atom diff --git a/atom/renderer/atom_render_view_observer.h b/atom/renderer/atom_render_view_observer.h index 4b9d59f3fa0..3fcaeaa331f 100644 --- a/atom/renderer/atom_render_view_observer.h +++ b/atom/renderer/atom_render_view_observer.h @@ -32,6 +32,7 @@ class AtomRenderViewObserver : public content::RenderViewObserver { void OnBrowserMessage(const base::string16& channel, const base::ListValue& args); + void OnSetTransparentBackground(); // Weak reference to renderer client. AtomRendererClient* renderer_client_; diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index b41b9b3a0f5..574207dd5b1 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -131,9 +131,6 @@ var createGuest = function(embedder, params) { } this.loadURL(params.src, opts); } - if (params.allowtransparency != null) { - this.setAllowTransparency(params.allowtransparency); - } return guest.allowPopups = params.allowpopups; }); @@ -229,11 +226,6 @@ ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', function(event, id, params) return (ref1 = guestInstances[id]) != null ? ref1.guest.setSize(params) : void 0; }); -ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', function(event, id, allowtransparency) { - var ref1; - return (ref1 = guestInstances[id]) != null ? ref1.guest.setAllowTransparency(allowtransparency) : void 0; -}); - // Returns WebContents from its guest id. exports.getGuest = function(id) { var ref1; diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index a7427abd631..c6e46fab954 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -106,7 +106,4 @@ module.exports = { setSize: function(guestInstanceId, params) { return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params); }, - setAllowTransparency: function(guestInstanceId, allowtransparency) { - return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', guestInstanceId, allowtransparency); - } }; diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index bb7847fe163..e47b42c0261 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -81,20 +81,6 @@ class BooleanAttribute extends WebViewAttribute { } } -// Attribute that specifies whether transparency is allowed in the webview. -class AllowTransparencyAttribute extends BooleanAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_ALLOWTRANSPARENCY, webViewImpl); - } - - handleMutation() { - if (!this.webViewImpl.guestInstanceId) { - return; - } - return guestViewInternal.setAllowTransparency(this.webViewImpl.guestInstanceId, this.getValue()); - } -} - // Attribute used to define the demension limits of autosizing. class AutosizeDimensionAttribute extends WebViewAttribute { constructor(name, webViewImpl) { @@ -298,7 +284,6 @@ class BlinkFeaturesAttribute extends WebViewAttribute { // Sets up all of the webview attributes. WebViewImpl.prototype.setupWebViewAttributes = function() { this.attributes = {}; - this.attributes[webViewConstants.ATTRIBUTE_ALLOWTRANSPARENCY] = new AllowTransparencyAttribute(this); this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE] = new AutosizeAttribute(this); this.attributes[webViewConstants.ATTRIBUTE_PARTITION] = new PartitionAttribute(this); this.attributes[webViewConstants.ATTRIBUTE_SRC] = new SrcAttribute(this); diff --git a/lib/renderer/web-view/web-view-constants.js b/lib/renderer/web-view/web-view-constants.js index de2a571f5d5..297941aa801 100644 --- a/lib/renderer/web-view/web-view-constants.js +++ b/lib/renderer/web-view/web-view-constants.js @@ -1,6 +1,5 @@ module.exports = { // Attributes. - ATTRIBUTE_ALLOWTRANSPARENCY: 'allowtransparency', ATTRIBUTE_AUTOSIZE: 'autosize', ATTRIBUTE_MAXHEIGHT: 'maxheight', ATTRIBUTE_MAXWIDTH: 'maxwidth', From fd53a4b24daffa1e2bcec5d3a5467ac3ea9a4b95 Mon Sep 17 00:00:00 2001 From: Robo Date: Mon, 14 Mar 2016 19:24:04 +0530 Subject: [PATCH 0197/1265] modify default background for all render views --- atom/browser/web_view_guest_delegate.cc | 7 ------- atom/browser/web_view_guest_delegate.h | 1 - atom/common/api/api_messages.h | 2 -- atom/renderer/atom_render_view_observer.cc | 9 --------- atom/renderer/atom_render_view_observer.h | 1 - atom/renderer/atom_renderer_client.cc | 4 ++++ 6 files changed, 4 insertions(+), 20 deletions(-) diff --git a/atom/browser/web_view_guest_delegate.cc b/atom/browser/web_view_guest_delegate.cc index 47fcc204a4d..6abb9713bfa 100644 --- a/atom/browser/web_view_guest_delegate.cc +++ b/atom/browser/web_view_guest_delegate.cc @@ -5,7 +5,6 @@ #include "atom/browser/web_view_guest_delegate.h" #include "atom/browser/api/atom_api_web_contents.h" -#include "atom/common/api/api_messages.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" @@ -103,12 +102,6 @@ void WebViewGuestDelegate::HandleKeyboardEvent( embedder_web_contents_->GetDelegate()->HandleKeyboardEvent(source, event); } -void WebViewGuestDelegate::RenderViewReady() { - // Set default UA-dependent background as transparent. - api_web_contents_->Send(new AtomViewMsg_SetTransparentBackground( - api_web_contents_->routing_id())); -} - void WebViewGuestDelegate::DidCommitProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& url, ui::PageTransition transition_type) { diff --git a/atom/browser/web_view_guest_delegate.h b/atom/browser/web_view_guest_delegate.h index d4549e8dba4..95888ff749f 100644 --- a/atom/browser/web_view_guest_delegate.h +++ b/atom/browser/web_view_guest_delegate.h @@ -55,7 +55,6 @@ class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate, protected: // content::WebContentsObserver: - void RenderViewReady() override; void DidCommitProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& url, ui::PageTransition transition_type) override; diff --git a/atom/common/api/api_messages.h b/atom/common/api/api_messages.h index e98f1bdfba0..eeb26614847 100644 --- a/atom/common/api/api_messages.h +++ b/atom/common/api/api_messages.h @@ -37,5 +37,3 @@ IPC_MESSAGE_ROUTED2(AtomViewMsg_Message, // Sent by the renderer when the draggable regions are updated. IPC_MESSAGE_ROUTED1(AtomViewHostMsg_UpdateDraggableRegions, std::vector /* regions */) - -IPC_MESSAGE_ROUTED0(AtomViewMsg_SetTransparentBackground) diff --git a/atom/renderer/atom_render_view_observer.cc b/atom/renderer/atom_render_view_observer.cc index 19eaec9e07b..cdbdb3d7c3c 100644 --- a/atom/renderer/atom_render_view_observer.cc +++ b/atom/renderer/atom_render_view_observer.cc @@ -22,7 +22,6 @@ #include "ipc/ipc_message_macros.h" #include "net/base/net_module.h" #include "net/grit/net_resources.h" -#include "third_party/skia/include/core/SkColor.h" #include "third_party/WebKit/public/web/WebDraggableRegion.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" @@ -114,8 +113,6 @@ bool AtomRenderViewObserver::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AtomRenderViewObserver, message) IPC_MESSAGE_HANDLER(AtomViewMsg_Message, OnBrowserMessage) - IPC_MESSAGE_HANDLER(AtomViewMsg_SetTransparentBackground, - OnSetTransparentBackground) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -151,10 +148,4 @@ void AtomRenderViewObserver::OnBrowserMessage(const base::string16& channel, } } -void AtomRenderViewObserver::OnSetTransparentBackground() { - if (!render_view()->GetWebView()) - return; - render_view()->GetWebView()->setBaseBackgroundColor(SK_ColorTRANSPARENT); -} - } // namespace atom diff --git a/atom/renderer/atom_render_view_observer.h b/atom/renderer/atom_render_view_observer.h index 3fcaeaa331f..4b9d59f3fa0 100644 --- a/atom/renderer/atom_render_view_observer.h +++ b/atom/renderer/atom_render_view_observer.h @@ -32,7 +32,6 @@ class AtomRenderViewObserver : public content::RenderViewObserver { void OnBrowserMessage(const base::string16& channel, const base::ListValue& args); - void OnSetTransparentBackground(); // Weak reference to renderer client. AtomRendererClient* renderer_client_; diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index a996bd0efb2..50ff109a2fc 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -25,6 +25,7 @@ #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "content/public/renderer/render_thread.h" +#include "content/public/renderer/render_view.h" #include "ipc/ipc_message_macros.h" #include "third_party/WebKit/public/web/WebCustomElement.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" @@ -131,6 +132,9 @@ void AtomRendererClient::RenderFrameCreated( } void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) { + // Set default UA-dependent background as transparent. + render_view->GetWebView()->setBaseBackgroundColor(SK_ColorTRANSPARENT); + new printing::PrintWebViewHelper(render_view); new AtomRenderViewObserver(render_view, this); } From cdc7b8d15e881f12c1ff3cba7dd92fb2fd759730 Mon Sep 17 00:00:00 2001 From: Robo Date: Tue, 15 Mar 2016 07:51:36 +0530 Subject: [PATCH 0198/1265] devtools: fix filesyatem api usage and use prefs to track filesystem paths --- atom/browser/atom_browser_context.cc | 1 + atom/browser/common_web_contents_delegate.cc | 119 +++++++++++++------ atom/browser/common_web_contents_delegate.h | 6 +- chromium_src/chrome/common/pref_names.cc | 1 + chromium_src/chrome/common/pref_names.h | 1 + 5 files changed, 86 insertions(+), 42 deletions(-) diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index 2ff9a510db4..d6724ff5338 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -194,6 +194,7 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) { PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); pref_registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); + pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); } bool AtomBrowserContext::AllowNTLMCredentialsForDomain(const GURL& origin) { diff --git a/atom/browser/common_web_contents_delegate.cc b/atom/browser/common_web_contents_delegate.cc index 07cc20c7d10..62e854ac565 100644 --- a/atom/browser/common_web_contents_delegate.cc +++ b/atom/browser/common_web_contents_delegate.cc @@ -4,17 +4,22 @@ #include "atom/browser/common_web_contents_delegate.h" +#include #include #include +#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_javascript_dialog_manager.h" #include "atom/browser/native_window.h" #include "atom/browser/ui/file_dialog.h" #include "atom/browser/web_dialog_helper.h" #include "base/files/file_util.h" +#include "base/prefs/pref_service.h" +#include "base/prefs/scoped_user_pref_update.h" #include "chrome/browser/printing/print_preview_message_handler.h" #include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/ui/browser_dialogs.h" +#include "chrome/common/pref_names.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" @@ -36,6 +41,8 @@ namespace atom { namespace { +const char kRootName[] = ""; + struct FileSystem { FileSystem() { } @@ -53,14 +60,14 @@ struct FileSystem { }; std::string RegisterFileSystem(content::WebContents* web_contents, - const base::FilePath& path, - std::string* registered_name) { + const base::FilePath& path) { auto isolated_context = storage::IsolatedContext::GetInstance(); + std::string root_name(kRootName); std::string file_system_id = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeNativeLocal, std::string(), path, - registered_name); + &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); @@ -80,13 +87,12 @@ std::string RegisterFileSystem(content::WebContents* web_contents, FileSystem CreateFileSystemStruct( content::WebContents* web_contents, const std::string& file_system_id, - const std::string& registered_name, const std::string& file_system_path) { const GURL origin = web_contents->GetURL().GetOrigin(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( - origin, file_system_id, registered_name); + origin, file_system_id, kRootName); return FileSystem(file_system_name, root_url, file_system_path); } @@ -114,6 +120,26 @@ void AppendToFile(const base::FilePath& path, base::AppendToFile(path, content.data(), content.size()); } +PrefService* GetPrefService(content::WebContents* web_contents) { + auto context = web_contents->GetBrowserContext(); + return static_cast(context)->prefs(); +} + +std::set GetAddedFileSystemPaths( + content::WebContents* web_contents) { + auto pref_service = GetPrefService(web_contents); + const base::DictionaryValue* file_system_paths_value = + pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); + std::set result; + if (file_system_paths_value) { + base::DictionaryValue::Iterator it(*file_system_paths_value); + for (; !it.IsAtEnd(); it.Advance()) { + result.insert(it.key()); + } + } + return result; +} + } // namespace CommonWebContentsDelegate::CommonWebContentsDelegate() @@ -278,6 +304,34 @@ void CommonWebContentsDelegate::DevToolsAppendToFile( base::Unretained(this), url)); } +void CommonWebContentsDelegate::DevToolsRequestFileSystems() { + auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); + if (file_system_paths.empty()) { + base::ListValue empty_file_system_value; + web_contents_->CallClientFunction("DevToolsAPI.fileSystemsLoaded", + &empty_file_system_value, + nullptr, nullptr); + return; + } + + std::vector file_systems; + for (auto file_system_path : file_system_paths) { + base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); + std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), + path); + FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), + file_system_id, + file_system_path); + file_systems.push_back(file_system); + } + + base::ListValue file_system_value; + for (size_t i = 0; i < file_systems.size(); ++i) + file_system_value.Append(CreateFileSystemValue(file_systems[i])); + web_contents_->CallClientFunction("DevToolsAPI.fileSystemsLoaded", + &file_system_value, nullptr, nullptr); +} + void CommonWebContentsDelegate::DevToolsAddFileSystem( const base::FilePath& file_system_path) { base::FilePath path = file_system_path; @@ -293,32 +347,26 @@ void CommonWebContentsDelegate::DevToolsAddFileSystem( path = paths[0]; } - std::string registered_name; std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), - path, - ®istered_name); - - WorkspaceMap::iterator it = saved_paths_.find(file_system_id); - if (it != saved_paths_.end()) + path); + auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); + if (file_system_paths.find(path.AsUTF8Unsafe()) != file_system_paths.end()) return; - saved_paths_[file_system_id] = path; - FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), - file_system_id, - registered_name, - path.AsUTF8Unsafe()); + file_system_id, + path.AsUTF8Unsafe()); + scoped_ptr file_system_value( + CreateFileSystemValue(file_system)); - scoped_ptr error_string_value( - new base::StringValue(std::string())); - scoped_ptr file_system_value; - if (!file_system.file_system_path.empty()) - file_system_value.reset(CreateFileSystemValue(file_system)); - web_contents_->CallClientFunction( - "DevToolsAPI.fileSystemAdded", - error_string_value.get(), - file_system_value.get(), - nullptr); + auto pref_service = GetPrefService(GetDevToolsWebContents()); + DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); + update.Get()->SetWithoutPathExpansion( + path.AsUTF8Unsafe(), base::Value::CreateNullValue()); + + web_contents_->CallClientFunction("DevToolsAPI.fileSystemAdded", + file_system_value.get(), + nullptr, nullptr); } void CommonWebContentsDelegate::DevToolsRemoveFileSystem( @@ -326,21 +374,18 @@ void CommonWebContentsDelegate::DevToolsRemoveFileSystem( if (!web_contents_) return; + std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()-> RevokeFileSystemByPath(file_system_path); - for (auto it = saved_paths_.begin(); it != saved_paths_.end(); ++it) - if (it->second == file_system_path) { - saved_paths_.erase(it); - break; - } + auto pref_service = GetPrefService(GetDevToolsWebContents()); + DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); + update.Get()->RemoveWithoutPathExpansion(path, nullptr); - base::StringValue file_system_path_value(file_system_path.AsUTF8Unsafe()); - web_contents_->CallClientFunction( - "DevToolsAPI.fileSystemRemoved", - &file_system_path_value, - nullptr, - nullptr); + base::StringValue file_system_path_value(path); + web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", + &file_system_path_value, + nullptr, nullptr); } void CommonWebContentsDelegate::OnDevToolsSaveToFile( diff --git a/atom/browser/common_web_contents_delegate.h b/atom/browser/common_web_contents_delegate.h index 83ef2850bd9..61ff63793df 100644 --- a/atom/browser/common_web_contents_delegate.h +++ b/atom/browser/common_web_contents_delegate.h @@ -83,6 +83,7 @@ class CommonWebContentsDelegate bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; + void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const base::FilePath& path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; @@ -128,11 +129,6 @@ class CommonWebContentsDelegate typedef std::map PathsMap; PathsMap saved_files_; - // Maps file system id to file path, used by the file system requests - // sent from devtools. - typedef std::map WorkspaceMap; - WorkspaceMap saved_paths_; - DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate); }; diff --git a/chromium_src/chrome/common/pref_names.cc b/chromium_src/chrome/common/pref_names.cc index 3e3a73b9983..23235cd1f4b 100644 --- a/chromium_src/chrome/common/pref_names.cc +++ b/chromium_src/chrome/common/pref_names.cc @@ -8,5 +8,6 @@ namespace prefs { const char kSelectFileLastDirectory[] = "selectfile.last_directory"; const char kDownloadDefaultDirectory[] = "download.default_directory"; +const char kDevToolsFileSystemPaths[] = "devtools.file_system_paths"; } // namespace prefs diff --git a/chromium_src/chrome/common/pref_names.h b/chromium_src/chrome/common/pref_names.h index 542a2d2c733..5101c720133 100644 --- a/chromium_src/chrome/common/pref_names.h +++ b/chromium_src/chrome/common/pref_names.h @@ -8,5 +8,6 @@ namespace prefs { extern const char kSelectFileLastDirectory[]; extern const char kDownloadDefaultDirectory[]; +extern const char kDevToolsFileSystemPaths[]; } // namespace prefs From e3e6cd6fd8d3b55677be9972c38a8dcaf5ea6a7d Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 14 Mar 2016 19:48:40 -0700 Subject: [PATCH 0199/1265] Remove type parameter --- atom/common/api/atom_api_native_image.cc | 50 ++---------------------- 1 file changed, 4 insertions(+), 46 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 6c22830f674..3932921646e 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -58,20 +58,6 @@ ScaleFactorPair kScaleFactorPairs[] = { { "@2.5x" , 2.5f }, }; -enum NativeRepresentation { - INVALID = 0, - AS_NSIMAGE, -}; - -struct NativeRepresentationPair { - const char* name; - NativeRepresentation rep; -}; - -NativeRepresentationPair kNativeRepresentations[] { - { "nsimage", NativeRepresentation::AS_NSIMAGE }, -}; - float GetScaleFactorFromPath(const base::FilePath& path) { std::string filename(path.BaseName().RemoveExtension().AsUTF8Unsafe()); @@ -240,40 +226,12 @@ std::string NativeImage::ToDataURL() { v8::Local NativeImage::AsNativeRepresentation( v8::Isolate* isolate, mate::Arguments* args) { - NativeRepresentation desiredRep = NativeRepresentation::INVALID; - void* ptr = nullptr; - std::string type; - - if (!args->GetNext(&type)) { - args->ThrowError(); - goto out; - } - - for (const NativeRepresentationPair& item : kNativeRepresentations) { - if (type.compare(item.name) == 0) { - desiredRep = item.rep; - break; - } - } - - if (desiredRep == NativeRepresentation::INVALID) { - args->ThrowError(); - goto out; - } - - switch (desiredRep) { #if defined(OS_MACOSX) - case NativeRepresentation::AS_NSIMAGE: - ptr = reinterpret_cast(image_.AsNSImage()); - break; + void* ptr = reinterpret_cast(image_.AsNSImage()); +#else + args.ThrowError(); + return v8::Undefined(isolate); #endif - case NativeRepresentation::INVALID: - default: - args->ThrowError(); - break; - } - -out: return node::Buffer::Copy( isolate, From d344c1e408324a39c703183c7541ea444d5ba18f Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 14 Mar 2016 19:50:31 -0700 Subject: [PATCH 0200/1265] AsNativeRepresentation => getNativeHandle --- atom/common/api/atom_api_native_image.cc | 6 +++--- atom/common/api/atom_api_native_image.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 3932921646e..d616b428330 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -184,8 +184,8 @@ mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) .SetMethod("toPng", &NativeImage::ToPNG) .SetMethod("toJpeg", &NativeImage::ToJPEG) - .SetMethod("asNativeRepresentation", - &NativeImage::AsNativeRepresentation) + .SetMethod("getNativeHandle", + &NativeImage::GetNativeHandle) .SetMethod("toDataURL", &NativeImage::ToDataURL) .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. .SetMethod("isEmpty", &NativeImage::IsEmpty) @@ -223,7 +223,7 @@ std::string NativeImage::ToDataURL() { return data_url; } -v8::Local NativeImage::AsNativeRepresentation( +v8::Local NativeImage::GetNativeHandle( v8::Isolate* isolate, mate::Arguments* args) { #if defined(OS_MACOSX) diff --git a/atom/common/api/atom_api_native_image.h b/atom/common/api/atom_api_native_image.h index 8b1329d2848..145f5ff1dcd 100644 --- a/atom/common/api/atom_api_native_image.h +++ b/atom/common/api/atom_api_native_image.h @@ -61,7 +61,7 @@ class NativeImage : public mate::Wrappable { private: v8::Local ToPNG(v8::Isolate* isolate); v8::Local ToJPEG(v8::Isolate* isolate, int quality); - v8::Local AsNativeRepresentation( + v8::Local GetNativeHandle( v8::Isolate* isolate, mate::Arguments* args); std::string ToDataURL(); From f59752bf4f7829bdcd3f0cd967938afea9bf62c6 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 14 Mar 2016 19:51:37 -0700 Subject: [PATCH 0201/1265] Update the docs to match --- docs/api/native-image.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/api/native-image.md b/docs/api/native-image.md index 2cae12feb47..c33f35c6fe5 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -133,12 +133,11 @@ Returns a [Buffer][buffer] that contains the image's `JPEG` encoded data. Returns the data URL of the image. -### `image.asNativeRepresentation(type)` +### `image.getNativeHandle()` Returns a pointer to an underlying native type (encoded as a [Buffer][buffer]) which can be used with native APIs. Note that in many cases, this pointer is a weak pointer to the underlying native image not a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. -* `type` String (**required**) - one of: - * `nsimage` - (OS X only) a pointer to an `NSImage` +Returns a [Buffer][buffer] that represents a pointer to a native type - on OS X, this type is an NSImage object. ### `image.isEmpty()` From ae701977c6972cf615a5f17045e1de5fedd672e0 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 15 Mar 2016 11:13:43 +0800 Subject: [PATCH 0202/1265] add web-contents first --- docs-translations/zh-CN/api/web-contents.md | 861 ++++++++++++++++++++ 1 file changed, 861 insertions(+) create mode 100644 docs-translations/zh-CN/api/web-contents.md diff --git a/docs-translations/zh-CN/api/web-contents.md b/docs-translations/zh-CN/api/web-contents.md new file mode 100644 index 00000000000..1b7011bb0fa --- /dev/null +++ b/docs-translations/zh-CN/api/web-contents.md @@ -0,0 +1,861 @@ +# webContents + +`webContents` 是一个 +[事件发出者](http://nodejs.org/api/events.html#events_class_events_eventemitter). + +它负责渲染并控制网页,也是 [`BrowserWindow`](browser-window.md) 对象的属性.一个使用 `webContents` 的例子: + +```javascript +const BrowserWindow = require('electron').BrowserWindow; + +var win = new BrowserWindow({width: 800, height: 1500}); +win.loadURL("http://github.com"); + +var webContents = win.webContents; +``` + +## 事件 + +`webContents` 对象可发出下列事件: + +### Event: 'did-finish-load' + +当导航完成时发出事件,`onload` 事件也完成. + +### Event: 'did-fail-load' + +返回: + +* `event` Event +* `errorCode` Integer +* `errorDescription` String +* `validatedURL` String + +这个事件类似 `did-finish-load` ,但是是在加载失败或取消加载时发出, 例如, `window.stop()` 请求结束.错误代码的完整列表和它们的含义都可以在 [here](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h) 找到. + +### Event: 'did-frame-finish-load' + +返回: + +* `event` Event +* `isMainFrame` Boolean + +当一个 frame 导航完成的时候发出事件. + +### Event: 'did-start-loading' + +当 tab 的spinner 开始 spinning的时候. + +### Event: 'did-stop-loading' + +当 tab 的spinner 结束 spinning的时候. + +### Event: 'did-get-response-details' + +返回: + +* `event` Event +* `status` Boolean +* `newURL` String +* `originalURL` String +* `httpResponseCode` Integer +* `requestMethod` String +* `referrer` String +* `headers` Object + +当有关请求资源的详细信息可用的时候发出事件. +`status` 标识了 socket链接来下载资源. + +### Event: 'did-get-redirect-request' + +返回: + +* `event` Event +* `oldURL` String +* `newURL` String +* `isMainFrame` Boolean +* `httpResponseCode` Integer +* `requestMethod` String +* `referrer` String +* `headers` Object + +当在请求资源时收到重定向的时候发出事件. + +### Event: 'dom-ready' + +返回: + +* `event` Event + +当指定 frame 中的 文档加载完成的时候发出事件. + +### Event: 'page-favicon-updated' + +返回: + +* `event` Event +* `favicons` Array - Array of URLs + +当 page 收到图标 url 的时候发出事件. + +### Event: 'new-window' + +返回: + +* `event` Event +* `url` String +* `frameName` String +* `disposition` String - 可为 `default`, `foreground-tab`, `background-tab`, + `new-window` 和 `other`. +* `options` Object - 创建新的 `BrowserWindow`时使用的参数. + +当 page 请求打开指定 url 窗口的时候发出事件.这可以是通过 `window.open` 或一个外部连接如 `` 发出的请求. + +默认指定 `url` 的 `BrowserWindow` 会被创建. + +调用 `event.preventDefault()` 可以用来阻止打开窗口. + +### Event: 'will-navigate' + +返回: + +* `event` Event +* `url` String + +当用户或 page 想要开始导航的时候发出事件.它可在当 `window.location` 对象改变或用户点击 page 中的链接的时候发生. + +当使用 api(如 `webContents.loadURL` 和 `webContents.back`) 以编程方式来启动导航的时候,这个事件将不会发出. + +它也不会在页内跳转发生, 例如点击锚链接或更新 `window.location.hash`.使用 `did-navigate-in-page` 事件可以达到目的. + +调用 `event.preventDefault()` 可以阻止导航. + +### Event: 'did-navigate' + +返回: + +* `event` Event +* `url` String + +当一个导航结束时候发出事件. + +页内跳转时不会发出这个事件,例如点击锚链接或更新 `window.location.hash`.使用 `did-navigate-in-page` 事件可以达到目的. + +### Event: 'did-navigate-in-page' + +返回: + +* `event` Event +* `url` String + +当页内导航发生的时候发出事件. + +当页内导航发生的时候,page 的url 改变,但是不会跳出界面.例如当点击锚链接时或者 DOM 的 `hashchange` 事件发生. + +### Event: 'crashed' + +当渲染进程崩溃的时候发出事件. + +### Event: 'plugin-crashed' + +返回: + +* `event` Event +* `name` String +* `version` String + +当插件进程崩溃时候发出事件. + +### Event: 'destroyed' + +当 `webContents` 被删除的时候发出事件. + +### Event: 'devtools-opened' + +当开发者工具栏打开的时候发出事件. + +### Event: 'devtools-closed' + +当开发者工具栏关闭时候发出事件. + +### Event: 'devtools-focused' + +当开发者工具栏获得焦点或打开的时候发出事件. + +### Event: 'certificate-error' + +返回: + +* `event` Event +* `url` URL +* `error` String - The error code +* `certificate` Object + * `data` Buffer - PEM encoded data + * `issuerName` String +* `callback` Function + +当验证证书或 `url` 失败的时候发出事件. + +使用方法类似 [`app` 的 `certificate-error` 事件](app.md#event-certificate-error). + +### Event: 'select-client-certificate' + +返回: + +* `event` Event +* `url` URL +* `certificateList` [Objects] + * `data` Buffer - PEM encoded data + * `issuerName` String - Issuer's Common Name +* `callback` Function + +当请求客户端证书的时候发出事件. + +使用方法类似 [`app` 的 `select-client-certificate` 事件](app.md#event-select-client-certificate). + +### Event: 'login' + +返回: + +* `event` Event +* `request` Object + * `method` String + * `url` URL + * `referrer` URL +* `authInfo` Object + * `isProxy` Boolean + * `scheme` String + * `host` String + * `port` Integer + * `realm` String +* `callback` Function + +当 `webContents` 想做基本验证的时候发出事件. + +使用方法类似 [the `login` event of `app`](app.md#event-login). + +### Event: 'found-in-page' + +返回: + +* `event` Event +* `result` Object + * `requestId` Integer + * `finalUpdate` Boolean - 标识是否还有更多的值可以查看. + * `matches` Integer (可选) - 匹配数量. + * `selectionArea` Object (可选) - 协调首个匹配位置. + +当使用 [`webContents.findInPage`](web-contents.md#webcontentsfindinpage) 进行页内查找并且找到可用值得时候发出事件. + +### Event: 'media-started-playing' + +当媒体开始播放的时候发出事件. + +### Event: 'media-paused' + +当媒体停止播放的时候发出事件. + +### Event: 'did-change-theme-color' + +当page 的主题色时候发出事件.这通常由于引入了一个 meta 标签 : + +```html + +``` + +### Event: 'cursor-changed' + +返回: + +* `event` Event +* `type` String +* `image` NativeImage (可选) +* `scale` Float (可选) + +当鼠标的类型发生改变的时候发出事件. `type` 的参数可以是 `default`, +`crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, +`ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, +`ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, +`row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, +`s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, +`cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, +`not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing`, `custom`. + +如果 `type` 参数值为 `custom`, `image` 参数会在一个`NativeImage` 中控制自定义鼠标图片, 并且 `scale` 会控制图片的缩放比例. + +## 实例方法 + +`webContents` 对象有如下的实例方法: + +### `webContents.loadURL(url[, options])` + +* `url` URL +* `options` Object (可选) + * `httpReferrer` String - A HTTP Referrer url. + * `userAgent` String - 产生请求的用户代理 + * `extraHeaders` String - 以 "\n" 分隔的额外头 + +在窗口中加载 `url` , `url` 必须包含协议前缀, +比如 `http://` 或 `file://`. 如果加载想要忽略 http 缓存,可以使用 `pragma` 头来达到目的. + +```javascript +const options = {"extraHeaders" : "pragma: no-cache\n"} +webContents.loadURL(url, options) +``` + +### `webContents.downloadURL(url)` + +* `url` URL + +初始化一个指定 `url` 的资源下载,不导航跳转. `session` 的 `will-download` 事件会触发. + +### `webContents.getURL()` + +返回当前page 的 url. + +```javascript +var win = new BrowserWindow({width: 800, height: 600}); +win.loadURL("http://github.com"); + +var currentURL = win.webContents.getURL(); +``` + +### `webContents.getTitle()` + +返回当前page 的 标题. + +### `webContents.isLoading()` + +返回一个布尔值,标识当前页是否正在加载. + +### `webContents.isWaitingForResponse()` + +返回一个布尔值,标识当前页是否正在等待主要资源的第一次响应. + +### `webContents.stop()` + +停止还为开始的导航. + +### `webContents.reload()` + +重载当前页. + +### `webContents.reloadIgnoringCache()` + +重载当前页,忽略缓存. + +### `webContents.canGoBack()` + +返回一个布尔值,标识浏览器是否能回到前一个page. + +### `webContents.canGoForward()` + +返回一个布尔值,标识浏览器是否能前往下一个page. + +### `webContents.canGoToOffset(offset)` + +* `offset` Integer + +返回一个布尔值,标识浏览器是否能前往指定 `offset` 的page. + +### `webContents.clearHistory()` + +清除导航历史. + +### `webContents.goBack()` + +让浏览器回退到前一个page. + +### `webContents.goForward()` + +让浏览器回前往下一个page. + +### `webContents.goToIndex(index)` + +* `index` Integer + +让浏览器回前往指定 `index` 的page. + +### `webContents.goToOffset(offset)` + +* `offset` Integer + +导航到相对于当前页的偏移位置页. + +### `webContents.isCrashed()` + +渲染进程是否崩溃. + +### `webContents.setUserAgent(userAgent)` + +* `userAgent` String + +重写本页用户代理. + +### `webContents.getUserAgent()` + +返回一个 `String` ,标识本页用户代理信息. + +### `webContents.insertCSS(css)` + +* `css` String + +为当前页插入css. + +### `webContents.executeJavaScript(code[, userGesture, callback])` + +* `code` String +* `userGesture` Boolean (可选) +* `callback` Function (可选) - 脚本执行完成后调用的回调函数. + * `result` + +评估 page `代码`. + +浏览器窗口中的一些 HTML API ,例如 `requestFullScreen`,只能被用户手势请求.设置 `userGesture` 为 `true` 可以取消这个限制. + +### `webContents.setAudioMuted(muted)` + +* `muted` Boolean + +减缓当前也的 audio 的播放速度. + +### `webContents.isAudioMuted()` + +返回一个布尔值,标识当前页是否减缓了 audio 的播放速度. + +### `webContents.undo()` + +执行网页的编辑命令 `undo` . + +### `webContents.redo()` + +执行网页的编辑命令 `redo` . + +### `webContents.cut()` + +执行网页的编辑命令 `cut` . + +### `webContents.copy()` + +执行网页的编辑命令 `copy` . + +### `webContents.paste()` + +执行网页的编辑命令 `paste` . + +### `webContents.pasteAndMatchStyle()` + +执行网页的编辑命令 `pasteAndMatchStyle` . + +### `webContents.delete()` + +执行网页的编辑命令 `delete` . + +### `webContents.selectAll()` + +执行网页的编辑命令 `selectAll` . + +### `webContents.unselect()` + +执行网页的编辑命令 `unselect` . + +### `webContents.replace(text)` + +* `text` String + +执行网页的编辑命令 `replace` . + +### `webContents.replaceMisspelling(text)` + +* `text` String + +执行网页的编辑命令 `replaceMisspelling` . + +### `webContents.insertText(text)` + +* `text` String + +插入 `text` 到获得了焦点的元素. + +### `webContents.findInPage(text[, options])` + +* `text` String - 查找内容, 不能为空. +* `options` Object (可选) + * `forward` Boolean - 是否向前或向后查找, 默认为 `true`. + * `findNext` Boolean - 当前操作是否是第一次查找或下一次查找, + 默认为 `false`. + * `matchCase` Boolean - 查找是否区分大小写, + 默认为 `false`. + * `wordStart` Boolean -是否仅以首字母查找. + 默认为 `false`. + * `medialCapitalAsWordStart` Boolean - 是否结合 `wordStart`,如果匹配是大写字母开头,后面接小写字母或无字母,那么就接受这个词中匹配.接受几个其它的合成词匹配, 默认为 `false`. + +发起请求,在网页中查找所有与 `text` 相匹配的项,并且返回一个 `Integer` 来表示这个请求用的请求Id.这个请求结果可以通过订阅 + [`found-in-page`](web-contents.md#event-found-in-page) 事件来取得. + +### `webContents.stopFindInPage(action)` + +* `action` String - 指定一个行为来接替停止 + [`webContents.findInPage`](web-contents.md#webcontentfindinpage) 请求. + * `clearSelection` - 转变为一个普通的 selection. + * `keepSelection` - 清除 selection. + * `activateSelection` - 获取焦点并点击 selection node. + +使用给定的 `action` 来为 `webContents` 停止任何 `findInPage` 请求. + +```javascript +webContents.on('found-in-page', function(event, result) { + if (result.finalUpdate) + webContents.stopFindInPage("clearSelection"); +}); + +const requestId = webContents.findInPage("api"); +``` + +### `webContents.hasServiceWorker(callback)` + +* `callback` Function + +检查是否有任何 ServiceWorker 注册了,并且返回一个布尔值,来作为 `callback`响应的标识. + +### `webContents.unregisterServiceWorker(callback)` + +* `callback` Function + +如果存在任何 ServiceWorker ,则全部注销,并且当JS承诺执行行或JS拒绝执行而失败的时候,返回一个布尔值,它标识了相应的 `callback`. + +### `webContents.print([options])` + +* `options` Object (可选) + * `silent` Boolean - 不需要请求用户的打印设置. 默认为 `false`. + * `printBackground` Boolean - 打印背景和网页图片. 默认为 `false`. + +打印窗口的网页. 当设置 `silent` 为 `false` 的时候,Electron 将使用系统默认的打印机和打印方式来打印. + +在网页中调用 `window.print()` 和 调用 `webContents.print({silent: false, printBackground: false})`具有相同的作用. + +**注意:** 在 Windows, 打印 API 依赖于 `pdf.dll`. 如果你的应用不使用任何的打印, 你可以安全删除 `pdf.dll` 来减少二进制文件的size. + +### `webContents.printToPDF(options, callback)` + +* `options` Object + * `marginsType` Integer - 指定使用的 margin type. 默认 margin 使用 0, 无 margin 使用 1, 最小化 margin 使用 2. + * `pageSize` String - 指定生成的PDF文件的page size. 可以是 `A3`, + `A4`, `A5`, `Legal`, `Letter` 和 `Tabloid`. + * `printBackground` Boolean - 是否打印 css 背景. + * `printSelectionOnly` Boolean - 是否只打印选中的部分. + * `landscape` Boolean - landscape 为 `true`, portrait 为 `false`. +* `callback` Function + +打印窗口的网页为 pdf ,使用 Chromium 预览打印的自定义设置. + +完成时使用 `callback(error, data)` 调用 `callback` . `data` 是一个 `Buffer` ,包含了生成的 pdf 数据. + +默认,空的 `options` 被视为 : + +```javascript +{ + marginsType: 0, + printBackground: false, + printSelectionOnly: false, + landscape: false +} +``` + +```javascript +const BrowserWindow = require('electron').BrowserWindow; +const fs = require('fs'); + +var win = new BrowserWindow({width: 800, height: 600}); +win.loadURL("http://github.com"); + +win.webContents.on("did-finish-load", function() { + // Use default printing options + win.webContents.printToPDF({}, function(error, data) { + if (error) throw error; + fs.writeFile("/tmp/print.pdf", data, function(error) { + if (error) + throw error; + console.log("Write PDF successfully."); + }) + }) +}); +``` + +### `webContents.addWorkSpace(path)` + +* `path` String + +添加指定的路径给开发者工具栏的 workspace.必须在 DevTools 创建之后使用它 : + +```javascript +mainWindow.webContents.on('devtools-opened', function() { + mainWindow.webContents.addWorkSpace(__dirname); +}); +``` + +### `webContents.removeWorkSpace(path)` + +* `path` String + +从开发者工具栏的 workspace 删除指定的路径. + +### `webContents.openDevTools([options])` + +* `options` Object (可选) + * `detach` Boolean - 在一个新窗口打开开发者工具栏 + +打开开发者工具栏. + +### `webContents.closeDevTools()` + +关闭开发者工具栏. + +### `webContents.isDevToolsOpened()` + +返回布尔值,开发者工具栏是否打开. + +### `webContents.isDevToolsFocused()` + +返回布尔值,开发者工具栏视图是否获得焦点. + +### `webContents.toggleDevTools()` + +Toggles 开发者工具. + +### `webContents.inspectElement(x, y)` + +* `x` Integer +* `y` Integer + +在 (`x`, `y`) 开始检测元素. + +### `webContents.inspectServiceWorker()` + +为 service worker 上下文打开开发者工具栏. + +### `webContents.send(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (可选) + +通过 `channel` 发送异步消息给渲染进程,你也可发送任意的参数.参数应该在 JSON 内部序列化,并且此后没有函数或原形链被包括了. + +渲染进程可以通过使用 `ipcRenderer` 监听 `channel` 来处理消息. + +例子,从主进程向渲染进程发送消息 : + +```javascript +// 主进程. +var window = null; +app.on('ready', function() { + window = new BrowserWindow({width: 800, height: 600}); + window.loadURL('file://' + __dirname + '/index.html'); + window.webContents.on('did-finish-load', function() { + window.webContents.send('ping', 'whoooooooh!'); + }); +}); +``` + +```html + + + + + + +``` + +### `webContents.enableDeviceEmulation(parameters)` + +`parameters` Object, properties: + +* `screenPosition` String - 指定需要模拟的屏幕 + (默认 : `desktop`) + * `desktop` + * `mobile` +* `screenSize` Object - 设置模拟屏幕 size (screenPosition == mobile) + * `width` Integer - 设置模拟屏幕 width + * `height` Integer - 设置模拟屏幕 height +* `viewPosition` Object - 在屏幕放置 view + (screenPosition == mobile) (默认: `{x: 0, y: 0}`) + * `x` Integer - 设置偏移左上角的x轴 + * `y` Integer - 设置偏移左上角的y轴 +* `deviceScaleFactor` Integer - 设置设备比例因子 (如果为0,默认为原始屏幕比例) (默认: `0`) +* `viewSize` Object - 设置模拟视图 size (空表示不覆盖) + * `width` Integer - 设置模拟视图 width + * `height` Integer - 设置模拟视图 height +* `fitToView` Boolean - 如果有必要的话,是否把模拟视图按比例缩放来适应可用空间 (默认: `false`) +* `offset` Object - 可用空间内的模拟视图偏移 (不在适应模式) (默认: `{x: 0, y: 0}`) + * `x` Float - 设置相对左上角的x轴偏移值 + * `y` Float - 设置相对左上角的y轴偏移值 +* `scale` Float - 可用空间内的模拟视图偏移 (不在适应视图模式) (默认: `1`) + +使用给定的参数来开启设备模拟. + +### `webContents.disableDeviceEmulation()` + +使用 `webContents.enableDeviceEmulation` 关闭设备模拟. + +### `webContents.sendInputEvent(event)` + +* `event` Object + * `type` String (**必需**) - 事件类型,可以是 `mouseDown`, + `mouseUp`, `mouseEnter`, `mouseLeave`, `contextMenu`, `mouseWheel`, + `mouseMove`, `keyDown`, `keyUp`, `char`. + * `modifiers` Array - 事件的 modifiers 数组, 可以是 + include `shift`, `control`, `alt`, `meta`, `isKeypad`, `isAutoRepeat`, + `leftButtonDown`, `middleButtonDown`, `rightButtonDown`, `capsLock`, + `numLock`, `left`, `right`. + +向 page 发送一个输入 `event` . + +对键盘事件来说,`event` 对象还有如下属性 : + +* `keyCode` String (**必需**) - 特点是将作为键盘事件发送. 可用的 key codes [Accelerator](accelerator.md). + + +对鼠标事件来说,`event` 对象还有如下属性 : + +* `x` Integer (**required**) +* `y` Integer (**required**) +* `button` String - button 按下, 可以是 `left`, `middle`, `right` +* `globalX` Integer +* `globalY` Integer +* `movementX` Integer +* `movementY` Integer +* `clickCount` Integer + +对鼠标滚轮事件来说,`event` 对象还有如下属性 : + +* `deltaX` Integer +* `deltaY` Integer +* `wheelTicksX` Integer +* `wheelTicksY` Integer +* `accelerationRatioX` Integer +* `accelerationRatioY` Integer +* `hasPreciseScrollingDeltas` Boolean +* `canScroll` Boolean + +### `webContents.beginFrameSubscription(callback)` + +* `callback` Function + +开始订阅 提交 事件和捕获数据帧,当有 提交 事件时,使用 `callback(frameBuffer)` 调用 `callback`. + +`frameBuffer` 是一个包含原始像素数据的 `Buffer`,像素数据是按照 32bit BGRA 格式有效存储的,但是实际情况是取决于处理器的字节顺序的(大多数的处理器是存放小端序的,如果是在大端序的处理器上,数据是 32bit ARGB 格式). + +### `webContents.endFrameSubscription()` + +停止订阅帧提交事件. + +### `webContents.savePage(fullPath, saveType, callback)` + +* `fullPath` String - 文件的完整路径. +* `saveType` String - 指定保存类型. + * `HTMLOnly` - 只保存html. + * `HTMLComplete` - 保存整个 page 内容. + * `MHTML` - 保存完整的 html 为 MHTML. +* `callback` Function - `function(error) {}`. + * `error` Error + +如果保存界面过程初始化成功,返回 true. + +```javascript +win.loadURL('https://github.com'); + +win.webContents.on('did-finish-load', function() { + win.webContents.savePage('/tmp/test.html', 'HTMLComplete', function(error) { + if (!error) + console.log("Save page successfully"); + }); +}); +``` + +## 实例属性 + +`WebContents` 对象也有下列属性: + +### `webContents.session` + +返回这个 `webContents` 使用的 [session](session.md) 对象. + +### `webContents.hostWebContents` + +返回这个 `webContents` 的父 `webContents` . + +### `webContents.devToolsWebContents` + +获取这个 `WebContents` 的开发者工具栏的 `WebContents` . + +**注意:** 用户不可保存这个对象,因为当开发者工具栏关闭的时候它的值为 `null` . + +### `webContents.debugger` + +调试 API 为 [remote debugging protocol][rdp] 提供交替传送. + +```javascript +try { + win.webContents.debugger.attach("1.1"); +} catch(err) { + console.log("Debugger attach failed : ", err); +}; + +win.webContents.debugger.on('detach', function(event, reason) { + console.log("Debugger detached due to : ", reason); +}); + +win.webContents.debugger.on('message', function(event, method, params) { + if (method == "Network.requestWillBeSent") { + if (params.request.url == "https://www.github.com") + win.webContents.debugger.detach(); + } +}) + +win.webContents.debugger.sendCommand("Network.enable"); +``` + +#### `webContents.debugger.attach([protocolVersion])` + +* `protocolVersion` String (可选) - 请求调试协议版本. + +添加 `webContents` 调试. + +#### `webContents.debugger.isAttached()` + +返回一个布尔值,标识是否已经给 `webContents` 添加了调试. + +#### `webContents.debugger.detach()` + +删除 `webContents` 调试. + +#### `webContents.debugger.sendCommand(method[, commandParams, callback])` + +* `method` String - 方法名, 应该是由远程调试协议定义的方法. +* `commandParams` Object (可选) - 请求参数为 JSON 对象. +* `callback` Function (可选) - Response + * `error` Object - 错误消息,标识命令失败. + * `result` Object - 回复在远程调试协议中由 'returns'属性定义的命令描述. + +发送给定命令给调试目标. + +#### Event: 'detach' + +* `event` Event +* `reason` String - 拆分调试器原因. + +在调试 session 结束时发出事件.这在 `webContents` 关闭时或 `webContents` 请求开发者工具栏时发生. + +#### Event: 'message' + +* `event` Event +* `method` String - 方法名. +* `params` Object - 在远程调试协议中由 'parameters' 属性定义的事件参数. + +每当调试目标发出事件时发出. + +[rdp]: https://developer.chrome.com/devtools/docs/debugger-protocol \ No newline at end of file From 3ee4790dab54385a4cd83a2fab8deb185b19c902 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 14 Mar 2016 20:36:48 -0700 Subject: [PATCH 0203/1265] Automatically set app user model ID We shouldn't ask users to figure out this piece of Windows Arcana when they're using Squirrel, let's just do it automatically. --- lib/browser/init.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lib/browser/init.js b/lib/browser/init.js index e1105df9b13..471cc3a5a0a 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -78,6 +78,35 @@ app.on('quit', function(event, exitCode) { return process.emit('exit', exitCode); }); +if (process.platform === 'win32') { + // If we are a Squirrel.Windows-installed app, set app user model ID + // so that users don't have to do this. + // + // Squirrel packages are always of the form: + // + // PACKAGE-NAME + // - Update.exe + // - app-VERSION + // - OUREXE.exe + // + // Squirrel itself will always set the shortcut's App User Model ID to the + // form `com.squirrel.PACKAGE-NAME.OUREXE`. We need to call + // app.setAppUserModelId with a matching identifier so that renderer processes + // will inherit this value. + var updateDotExe = path.join( + path.dirname(process.execPath), + '..', + 'update.exe'); + + if (fs.statSyncNoException(updateDotExe)) { + var packageDir = path.dirname(path.resolve(updateDotExe)); + var packageName = path.basename(packageDir); + var exeName = path.basename(process.execPath).replace(/\.exe$/i, ''); + + app.setAppUserModelId(`com.squirrel.${packageName}.${exeName}`); + } +} + // Map process.exit to app.exit, which quits gracefully. process.exit = app.exit; From 665d3166ed02a3d169f69d3a52cd5fad2996803e Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Mon, 14 Mar 2016 21:00:58 -0700 Subject: [PATCH 0204/1265] Update the tests --- spec/api-native-image-spec.js | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 587ea876f29..e411fb11002 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -40,26 +40,12 @@ describe('nativeImage module', () => { const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); - const nsimage = image.asNativeRepresentation('nsimage'); + const nsimage = image.getNativeHandle(); assert.equal(nsimage.length, 8); // If all bytes are null, that's Bad assert.equal(nsimage.reduce((acc,x) => acc || (x != 0)), true); }); - - it('Throws when asNativeRepresentation gets a bogus value', () => { - const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; - const image = nativeImage.createFromPath(imagePath); - - let shouldDie = true; - try { - image.asNativeRepresentation('__foobar__'); - } catch (e) { - shouldDie = false; - } - - assert.equal(shouldDie, false); - }); }); }); From 3c007d1333f7908e32d6b644f43547e5bf0ecc7a Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 15 Mar 2016 14:00:40 +0800 Subject: [PATCH 0205/1265] add tray first --- docs-translations/zh-CN/api/tray.md | 205 ++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 docs-translations/zh-CN/api/tray.md diff --git a/docs-translations/zh-CN/api/tray.md b/docs-translations/zh-CN/api/tray.md new file mode 100644 index 00000000000..d5647871ac7 --- /dev/null +++ b/docs-translations/zh-CN/api/tray.md @@ -0,0 +1,205 @@ +# Tray + +用一个 `Tray` 来表示一个图标,这个图标处于正在运行的系统的通知区 ,通常被添加到一个 context menu 上. + +```javascript +const electron = require('electron'); +const app = electron.app; +const Menu = electron.Menu; +const Tray = electron.Tray; + +var appIcon = null; +app.on('ready', function(){ + appIcon = new Tray('/path/to/my/icon'); + var contextMenu = Menu.buildFromTemplate([ + { label: 'Item1', type: 'radio' }, + { label: 'Item2', type: 'radio' }, + { label: 'Item3', type: 'radio', checked: true }, + { label: 'Item4', type: 'radio' } + ]); + appIcon.setToolTip('This is my application.'); + appIcon.setContextMenu(contextMenu); +}); + +``` + +__平台限制:__ + +* 在 Linux, 如果支持应用指示器则使用它,否则使用 `GtkStatusIcon` 代替. +* 在 Linux ,配置了只有有了应用指示器的支持, 你必须安装 `libappindicator1` 来让 tray icon 执行. +* 应用指示器只有在它拥有 context menu 时才会显示. +* 当在linux 上使用了应用指示器,将忽略点击事件. +* 在 Linux,为了让单独的 `MenuItem` 起效,需要再次调用 `setContextMenu` .例如: + +```javascript +contextMenu.items[2].checked = false; +appIcon.setContextMenu(contextMenu); +``` +如果想在所有平台保持完全相同的行为,不应该依赖点击事件,而是一直将一个 context menu 添加到 tray icon. + +## Class: Tray + +`Tray` 是一个 [事件发出者][event-emitter]. + +### `new Tray(image)` + +* `image` [NativeImage](native-image.md) + +创建一个与 `image` 相关的 icon. + +## 事件 + +`Tray` 模块可发出下列事件: + +**注意:** 一些事件只能在特定的os中运行,已经标明. + +### Event: 'click' + +* `event` Event + * `altKey` Boolean + * `shiftKey` Boolean + * `ctrlKey` Boolean + * `metaKey` Boolean +* `bounds` Object - tray icon 的 bounds. + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer + +当tray icon被点击的时候发出事件. + +__注意:__ `bounds` 只在 OS X 和 Windows 上起效. + +### Event: 'right-click' _OS X_ _Windows_ + +* `event` Event + * `altKey` Boolean + * `shiftKey` Boolean + * `ctrlKey` Boolean + * `metaKey` Boolean +* `bounds` Object - tray icon 的 bounds. + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer + +当tray icon被鼠标右键点击的时候发出事件. + +### Event: 'double-click' _OS X_ _Windows_ + +* `event` Event + * `altKey` Boolean + * `shiftKey` Boolean + * `ctrlKey` Boolean + * `metaKey` Boolean +* `bounds` Object - tray icon 的 bounds. + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer + +当tray icon被双击的时候发出事件. + +### Event: 'balloon-show' _Windows_ + +当tray 气泡显示的时候发出事件. + +### Event: 'balloon-click' _Windows_ + +当tray 气泡被点击的时候发出事件. + +### Event: 'balloon-closed' _Windows_ + +当tray 气泡关闭的时候发出事件,因为超时或人为关闭. + +### Event: 'drop' _OS X_ + +当tray icon上的任何可拖动项被删除的时候发出事件. + +### Event: 'drop-files' _OS X_ + +* `event` +* `files` Array - 已删除文件的路径. + +当tray icon上的可拖动文件被删除的时候发出事件. + +### Event: 'drag-enter' _OS X_ + +当一个拖动操作进入tray icon的时候发出事件. + +### Event: 'drag-leave' _OS X_ + +当一个拖动操作离开tray icon的时候发出事件. +Emitted when a drag operation exits the tray icon. + +### Event: 'drag-end' _OS X_ + +当一个拖动操作在tray icon上或其它地方停止拖动的时候发出事件. + +## 方法 + +`Tray` 模块有以下方法: + +**Note:** 一些方法只能在特定的os中运行,已经标明. + +### `Tray.destroy()` + +立刻删除 tray icon. + +### `Tray.setImage(image)` + +* `image` [NativeImage](native-image.md) + +让 `image` 与 tray icon 关联起来. + +### `Tray.setPressedImage(image)` _OS X_ + +* `image` [NativeImage](native-image.md) + +当在 OS X 上按压 tray icon 的时候, 让 `image` 与 tray icon 关联起来. + +### `Tray.setToolTip(toolTip)` + +* `toolTip` String + +为 tray icon 设置 hover text. + +### `Tray.setTitle(title)` _OS X_ + +* `title` String + +在状态栏沿着 tray icon 设置标题. + +### `Tray.setHighlightMode(highlight)` _OS X_ + +* `highlight` Boolean + +当 tray icon 被点击的时候,是否设置它的背景色变为高亮(blue).默认为 true. + +### `Tray.displayBalloon(options)` _Windows_ + +* `options` Object + * `icon` [NativeImage](native-image.md) + * `title` String + * `content` String + +展示一个 tray balloon. + +### `Tray.popUpContextMenu([menu, position])` _OS X_ _Windows_ + +* `menu` Menu (optional) +* `position` Object (可选) - 上托位置. + * `x` Integer + * `y` Integer + +从 tray icon 上托出 context menu . 当划过 `menu` 的时候, `menu` 显示,代替 tray 的 context menu . + +`position` 只在 windows 上可用,默认为 (0, 0) . + +### `Tray.setContextMenu(menu)` + +* `menu` Menu + +为这个 icon 设置 context menu . + +[event-emitter]: http://nodejs.org/api/events.html#events_class_events_eventemitter \ No newline at end of file From c2c91b6477a8842234d194bde62320e339e5d4b4 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 15 Mar 2016 15:11:28 +0800 Subject: [PATCH 0206/1265] add three render process's files first --- .../zh-CN/api/desktop-capturer.md | 64 +++++++++++ docs-translations/zh-CN/api/ipc-renderer.md | 69 ++++++++++++ docs-translations/zh-CN/api/web-frame.md | 101 ++++++++++++++++++ 3 files changed, 234 insertions(+) create mode 100644 docs-translations/zh-CN/api/desktop-capturer.md create mode 100644 docs-translations/zh-CN/api/ipc-renderer.md create mode 100644 docs-translations/zh-CN/api/web-frame.md diff --git a/docs-translations/zh-CN/api/desktop-capturer.md b/docs-translations/zh-CN/api/desktop-capturer.md new file mode 100644 index 00000000000..954520d05ea --- /dev/null +++ b/docs-translations/zh-CN/api/desktop-capturer.md @@ -0,0 +1,64 @@ +# desktopCapturer + +`desktopCapturer` 模块可用来获取可用资源,这个资源可通过 `getUserMedia` 捕获得到. + +```javascript +// 在渲染进程中. +var desktopCapturer = require('electron').desktopCapturer; + +desktopCapturer.getSources({types: ['window', 'screen']}, function(error, sources) { + if (error) throw error; + for (var i = 0; i < sources.length; ++i) { + if (sources[i].name == "Electron") { + navigator.webkitGetUserMedia({ + audio: false, + video: { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: sources[i].id, + minWidth: 1280, + maxWidth: 1280, + minHeight: 720, + maxHeight: 720 + } + } + }, gotStream, getUserMediaError); + return; + } + } +}); + +function gotStream(stream) { + document.querySelector('video').src = URL.createObjectURL(stream); +} + +function getUserMediaError(e) { + console.log('getUserMediaError'); +} +``` + +当调用 `navigator.webkitGetUserMedia` 时创建一个约束对象,如果使用 `desktopCapturer` 的资源,必须设置 `chromeMediaSource` 为 `"desktop"` ,并且 `audio` 为 `false`. + +如果你想捕获整个桌面的 audio 和 video,你可以设置 `chromeMediaSource` 为 `"screen"` ,和 `audio` 为 `true`. +当使用这个方法的时候,不可以指定一个 `chromeMediaSourceId`. + +## 方法 + +`desktopCapturer` 模块有如下方法: + +### `desktopCapturer.getSources(options, callback)` + +* `options` Object + * `types` Array - 一个 String 数组,列出了可以捕获的桌面资源类型, 可用类型为 `screen` 和 `window`. + * `thumbnailSize` Object (可选) - 建议缩略可被缩放的 size, 默认为 `{width: 150, height: 150}`. +* `callback` Function + +发起一个请求,获取所有桌面资源,当请求完成的时候使用 `callback(error, sources)` 调用 `callback` . + +`sources` 是一个 `Source` 对象数组, 每个 `Source` 表示了一个捕获的屏幕或单独窗口,并且有如下属性 : +* `id` String - 在 `navigator.webkitGetUserMedia` 中使用的捕获窗口或屏幕的 id . 格式为 `window:XX` 祸 + `screen:XX`,`XX` 是一个随机数. +* `name` String - 捕获窗口或屏幕的描述名 . 如果资源为屏幕,名字为 `Entire Screen` 或 `Screen `; 如果资源为窗口, 名字为窗口的标题. +* `thumbnail` [NativeImage](NativeImage.md) - 缩略图. + +**注意:** 不能保证 `source.thumbnail` 的 size 和 `options` 中的 `thumnbailSize` 一直一致. 它也取决于屏幕或窗口的缩放比例. \ No newline at end of file diff --git a/docs-translations/zh-CN/api/ipc-renderer.md b/docs-translations/zh-CN/api/ipc-renderer.md new file mode 100644 index 00000000000..beeaa6d7623 --- /dev/null +++ b/docs-translations/zh-CN/api/ipc-renderer.md @@ -0,0 +1,69 @@ +# ipcRenderer + +`ipcRenderer` 模块是一个 +[EventEmitter](https://nodejs.org/api/events.html) 类的实例. 它提供了有限的方法,你可以从渲染进程向主进程发送同步或异步消息. 也可以收到主进程的相应. + +查看 [ipcMain](ipc-main.md) 代码例子. + +## 消息监听 + +`ipcRenderer` 模块有下列方法来监听事件: + +### `ipcRenderer.on(channel, listener)` + +* `channel` String +* `listener` Function + +监听 `channel`, 当有新消息到达,使用 `listener(event, args...)` 调用 `listener` . + +### `ipcRenderer.once(channel, listener)` + +* `channel` String +* `listener` Function + +为这个事件添加一个一次性 `listener` 函数.这个 `listener` 将在下一次有新消息被发送到 `channel` 的时候被请求调用,之后就被删除了. + +### `ipcRenderer.removeListener(channel, listener)` + +* `channel` String +* `listener` Function + +从指定的 `channel` 中的监听者数组删除指定的 `listener` . + +### `ipcRenderer.removeAllListeners([channel])` + +* `channel` String (optional) + +删除所有的监听者,或者删除指定 `channel` 中的全部. + +## 发送消息 + +`ipcRenderer` 模块有如下方法来发送消息: + +### `ipcRenderer.send(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (可选) + +通过 `channel` 向主进程发送异步消息,也可以发送任意参数.参数会被JSON序列化,之后就不会包含函数或原型链. + +主进程通过使用 `ipcMain` 模块来监听 `channel`,从而处理消息. + +### `ipcRenderer.sendSync(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (可选) + +通过 `channel` 向主进程发送同步消息,也可以发送任意参数.参数会被JSON序列化,之后就不会包含函数或原型链. + +主进程通过使用 `ipcMain` 模块来监听 `channel`,从而处理消息, +通过 `event.returnValue` 来响应. + +__注意:__ 发送同步消息将会阻塞整个渲染进程,除非你知道你在做什么,否则就永远不要用它 . + +### `ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (可选) + +类似 `ipcRenderer.send` ,但是它的事件将发往 host page 的 `` 元素,而不是主进程. \ No newline at end of file diff --git a/docs-translations/zh-CN/api/web-frame.md b/docs-translations/zh-CN/api/web-frame.md new file mode 100644 index 00000000000..d278e942713 --- /dev/null +++ b/docs-translations/zh-CN/api/web-frame.md @@ -0,0 +1,101 @@ +# webFrame + +`web-frame` 模块允许你自定义如何渲染当前网页 . + +例子,放大当前页到 200%. + +```javascript +var webFrame = require('electron').webFrame; + +webFrame.setZoomFactor(2); +``` + +## 方法 + +`web-frame` 模块有如下方法: + +### `webFrame.setZoomFactor(factor)` + +* `factor` Number - 缩放参数. + +将缩放参数修改为指定的参数值.缩放参数是百分制的,所以 300% = 3.0. + +### `webFrame.getZoomFactor()` + +返回当前缩放参数值. + +### `webFrame.setZoomLevel(level)` + +* `level` Number - 缩放水平 + +将缩放水平修改为指定的水平值. 原始 size 为 0 ,并且每次增长都表示放大 20% 或缩小 20%,默认限制为原始 size 的 300% 到 50% 之间 . + +### `webFrame.getZoomLevel()` + +返回当前缩放水平值. + +### `webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)` + +* `minimumLevel` Number +* `maximumLevel` Number + +设置缩放水平的最大值和最小值. + +### `webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)` + +* `language` String +* `autoCorrectWord` Boolean +* `provider` Object + +为输入框或文本域设置一个拼写检查 provider . + +`provider` 必须是一个对象,它有一个 `spellCheck` 方法,这个方法返回扫过的单词是否拼写正确 . + +例子,使用 [node-spellchecker][spellchecker] 作为一个 provider: + +```javascript +webFrame.setSpellCheckProvider("en-US", true, { + spellCheck: function(text) { + return !(require('spellchecker').isMisspelled(text)); + } +}); +``` + +### `webFrame.registerURLSchemeAsSecure(scheme)` + +* `scheme` String + +注册 `scheme` 为一个安全的 scheme. + + +安全的 schemes 不会引发混合内容 warnings.例如, `https` 和 +`data` 是安全的 schemes ,因为它们不能被活跃网络攻击而失效. + +### `webFrame.registerURLSchemeAsBypassingCSP(scheme)` + +* `scheme` String + +忽略当前网页内容的安全策略,直接从 `scheme` 加载. + +### `webFrame.registerURLSchemeAsPrivileged(scheme)` + +* `scheme` String + +通过资源的内容安全策略,注册 `scheme` 为安全的 scheme,允许注册 ServiceWorker并且支持 fetch API. + +### `webFrame.insertText(text)` + +* `text` String + +向获得焦点的原色插入内容 . + +### `webFrame.executeJavaScript(code[, userGesture])` + +* `code` String +* `userGesture` Boolean (可选) - 默认为 `false`. + +评估页面代码 . + +在浏览器窗口中,一些 HTML APIs ,例如 `requestFullScreen`,只可以通过用户手势来使用.设置`userGesture` 为 `true` 可以突破这个限制 . + +[spellchecker]: https://github.com/atom/node-spellchecker \ No newline at end of file From b105bf59c129e2f6320e74923333d3c3a6a6f1e5 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Tue, 15 Mar 2016 17:03:48 +0800 Subject: [PATCH 0207/1265] add last api files first --- docs-translations/zh-CN/api/clipboard.md | 117 +++++++++++++++ docs-translations/zh-CN/api/crash-reporter.md | 61 ++++++++ docs-translations/zh-CN/api/native-image.md | 142 ++++++++++++++++++ docs-translations/zh-CN/api/screen.md | 135 +++++++++++++++++ 4 files changed, 455 insertions(+) create mode 100644 docs-translations/zh-CN/api/clipboard.md create mode 100644 docs-translations/zh-CN/api/crash-reporter.md create mode 100644 docs-translations/zh-CN/api/native-image.md create mode 100644 docs-translations/zh-CN/api/screen.md diff --git a/docs-translations/zh-CN/api/clipboard.md b/docs-translations/zh-CN/api/clipboard.md new file mode 100644 index 00000000000..77aa6d65c0b --- /dev/null +++ b/docs-translations/zh-CN/api/clipboard.md @@ -0,0 +1,117 @@ +# clipboard + +`clipboard` 模块提供方法来供复制和粘贴操作 . +下面例子展示了如何将一个字符串写道 clipboard 上: + +```javascript +const clipboard = require('electron').clipboard; +clipboard.writeText('Example String'); +``` + +在 X Window 系统上, 有一个可选的 clipboard. 你可以为每个方法使用 `selection` 来控制它: + +```javascript +clipboard.writeText('Example String', 'selection'); +console.log(clipboard.readText('selection')); +``` + +## 方法 + +`clipboard` 模块有以下方法: + +**注意:** 测试 APIs 已经标明,并且在将来会被删除 . + +### `clipboard.readText([type])` + +* `type` String (可选) + +以纯文本形式从 clipboard 返回内容 . + +### `clipboard.writeText(text[, type])` + +* `text` String +* `type` String (可选) + +以纯文本形式向 clipboard 添加内容 . + +### `clipboard.readHtml([type])` + +* `type` String (可选) + +返回 clipboard 中的标记内容. + +### `clipboard.writeHtml(markup[, type])` + +* `markup` String +* `type` String (可选) + +向 clipboard 添加 `markup` 内容 . + +### `clipboard.readImage([type])` + +* `type` String (可选) + +从 clipboard 中返回 [NativeImage](native-image.md) 内容. + +### `clipboard.writeImage(image[, type])` + +* `image` [NativeImage](native-image.md) +* `type` String (可选) + +向 clipboard 中写入 `image` . + +### `clipboard.readRtf([type])` + +* `type` String (可选) + +从 clipboard 中返回 RTF 内容. + +### `clipboard.writeRtf(text[, type])` + +* `text` String +* `type` String (可选) + +向 clipboard 中写入 RTF 格式的 `text` . + +### `clipboard.clear([type])` + +* `type` String (可选) + +清空 clipboard 内容. + +### `clipboard.availableFormats([type])` + +* `type` String (可选) + +返回 clipboard 支持的格式数组 . + +### `clipboard.has(data[, type])` _Experimental_ + +* `data` String +* `type` String (可选) + +返回 clipboard 是否支持指定 `data` 的格式. + +```javascript +console.log(clipboard.has('

selection

')); +``` + +### `clipboard.read(data[, type])` _Experimental_ + +* `data` String +* `type` String (可选) + +读取 clipboard 的 `data`. + +### `clipboard.write(data[, type])` + +* `data` Object + * `text` String + * `html` String + * `image` [NativeImage](native-image.md) +* `type` String (可选) + +```javascript +clipboard.write({text: 'test', html: "test"}); +``` +向 clipboard 写入 `data` . \ No newline at end of file diff --git a/docs-translations/zh-CN/api/crash-reporter.md b/docs-translations/zh-CN/api/crash-reporter.md new file mode 100644 index 00000000000..a4646401ad8 --- /dev/null +++ b/docs-translations/zh-CN/api/crash-reporter.md @@ -0,0 +1,61 @@ +# crashReporter + +`crash-reporter` 模块开启发送应用崩溃报告. + +下面是一个自动提交崩溃报告给服务器的例子 : + +```javascript +const crashReporter = require('electron').crashReporter; + +crashReporter.start({ + productName: 'YourName', + companyName: 'YourCompany', + submitURL: 'https://your-domain.com/url-to-submit', + autoSubmit: true +}); +``` + +## 方法 + +`crash-reporter` 模块有如下方法: + +### `crashReporter.start(options)` + +* `options` Object + * `companyName` String + * `submitURL` String - 崩溃报告发送的路径,以post方式. + * `productName` String (可选) - 默认为 `Electron`. + * `autoSubmit` Boolean - 是否自动提交. + 默认为 `true`. + * `ignoreSystemCrashHandler` Boolean - 默认为 `false`. + * `extra` Object - 一个你可以定义的对象,附带在崩溃报告上一起发送 . 只有字符串属性可以被正确发送,不支持嵌套对象. + +只可以在使用其它 `crashReporter` APIs 之前使用这个方法. + +**注意:** 在 OS X, Electron 使用一个新的 `crashpad` 客户端, 与 Windows 和 Linux 的 `breakpad` 不同. 为了开启崩溃点搜集,你需要在主进程和其它每个你需要搜集崩溃报告的渲染进程中调用 `crashReporter.start` API 来初始化 `crashpad`. + +### `crashReporter.getLastCrashReport()` + +返回最后一个崩溃报告的日期和 ID.如果没有过崩溃报告发送过来,或者还没有开始崩溃报告搜集,将返回 `null` . + +### `crashReporter.getUploadedReports()` + +返回所有上载的崩溃报告,每个报告包含了上载日期和 ID. + +## crash-reporter Payload + +崩溃报告将发送下面的数据给 `POST` 型的 `提交 URL` : + +* `ver` String - Electron 版本. +* `platform` String - 例如 'win32'. +* `process_type` String - 例如 'renderer'. +* `guid` String - 例如 '5e1286fc-da97-479e-918b-6bfb0c3d1c72' +* `_version` String - `package.json` 版本. +* `_productName` String - `crashReporter` `options` + 对象中的产品名字. +* `prod` String - 基础产品名字. 这种情况为 Electron. +* `_companyName` String - `crashReporter` `options` + 对象中的公司名字. +* `upload_file_minidump` File - 崩溃报告为文件. +* `crashReporter` 中的 `extra` 对象的所有等级和一个属性. + `options` object \ No newline at end of file diff --git a/docs-translations/zh-CN/api/native-image.md b/docs-translations/zh-CN/api/native-image.md new file mode 100644 index 00000000000..cb2569922b2 --- /dev/null +++ b/docs-translations/zh-CN/api/native-image.md @@ -0,0 +1,142 @@ +# nativeImage + +在 Electron 中, 对所有创建 images 的 api 来说, 你可以使用文件路径或 `nativeImage` 实例. 如果使用 `null` ,将创建一个空的image 对象. + +例如, 当创建一个 tray 或设置窗口的图标时候,你可以使用一个字符串的图片路径 : + +```javascript +var appIcon = new Tray('/Users/somebody/images/icon.png'); +var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'}); +``` + +或者从剪切板中读取图片,它返回的是 `nativeImage`: + +```javascript +var image = clipboard.readImage(); +var appIcon = new Tray(image); +``` + +## 支持的格式 + +当前支持 `PNG` 和 `JPEG` 图片格式. 推荐 `PNG` ,因为它支持透明和无损压缩. + +在 Windows, 你也可以使用 `ICO` 图标的格式. + +## 高分辨率图片 + +如果平台支持 high-DPI,你可以在图片基础路径后面添加 `@2x` ,可以标识它为高分辨率的图片. + +例如,如果 `icon.png` 是一个普通图片并且拥有标准分辨率,然后 `icon@2x.png`将被当作高分辨率的图片处理,它将拥有双倍 DPI 密度. + +如果想同时支持展示不同分辨率的图片,你可以将拥有不同size 的图片放在同一个文件夹下,不用 DPI 后缀.例如 : + +```text +images/ +├── icon.png +├── icon@2x.png +└── icon@3x.png +``` + + +```javascript +var appIcon = new Tray('/Users/somebody/images/icon.png'); +``` + +也支持下面这些 DPI 后缀: + +* `@1x` +* `@1.25x` +* `@1.33x` +* `@1.4x` +* `@1.5x` +* `@1.8x` +* `@2x` +* `@2.5x` +* `@3x` +* `@4x` +* `@5x` + +## 模板图片 + +模板图片由黑色和清色(和一个 alpha 通道)组成. +模板图片不是单独使用的,而是通常和其它内容混合起来创建期望的最终效果. + +最常见的用力是将模板图片用到菜单栏图片上,所以它可以同时适应亮、黑不同的菜单栏. + +**注意:** 模板图片只在 OS X 上可用. + +为了将图片标识为一个模板图片,它的文件名应当以 `Template` 结尾. 例如: + +* `xxxTemplate.png` +* `xxxTemplate@2x.png` + +## 方法 + +`nativeImage` 类有如下方法: + +### `nativeImage.createEmpty()` + +创建一个空的 `nativeImage` 实例. + +### `nativeImage.createFromPath(path)` + +* `path` String + +从指定 `path` 创建一个新的 `nativeImage` 实例 . + +### `nativeImage.createFromBuffer(buffer[, scaleFactor])` + +* `buffer` [Buffer][buffer] +* `scaleFactor` Double (可选) + +从 `buffer` 创建一个新的 `nativeImage` 实例 .默认 `scaleFactor` 是 1.0. + +### `nativeImage.createFromDataURL(dataURL)` + +* `dataURL` String + +从 `dataURL` 创建一个新的 `nativeImage` 实例 . + +## 实例方法 + +`nativeImage` 有如下方法: + +```javascript +const nativeImage = require('electron').nativeImage; + +var image = nativeImage.createFromPath('/Users/somebody/images/icon.png'); +``` + +### `image.toPng()` + +返回一个 [Buffer][buffer] ,它包含了图片的 `PNG` 编码数据. + +### `image.toJpeg(quality)` + +* `quality` Integer (**必须**) - 在 0 - 100 之间. + +返回一个 [Buffer][buffer] ,它包含了图片的 `JPEG` 编码数据. + +### `image.toDataURL()` + +返回图片数据的 URL. + +### `image.isEmpty()` + +返回一个 boolean ,标识图片是否为空. + +### `image.getSize()` + +返回图片的 size. + +[buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer + +### `image.setTemplateImage(option)` + +* `option` Boolean + +将图片标识为模板图片. + +### `image.isTemplateImage()` + +返回一个 boolean ,标识图片是否是模板图片. \ No newline at end of file diff --git a/docs-translations/zh-CN/api/screen.md b/docs-translations/zh-CN/api/screen.md new file mode 100644 index 00000000000..0de4c975afb --- /dev/null +++ b/docs-translations/zh-CN/api/screen.md @@ -0,0 +1,135 @@ +# screen + +`screen` 模块检索屏幕的 size,显示,鼠标位置等的信息.在 `app` 模块的`ready` 事件触发之前不可使用这个模块. + +`screen` 是一个 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). + +**注意:** 在渲染进程 / 开发者工具栏, `window.screen` 是一个预设值的 DOM +属性, 所以这样写 `var screen = require('electron').screen` 将不会工作. +在我们下面的例子, 我们取代使用可变名字的 `electronScreen`. +一个例子,创建一个充满真个屏幕的窗口 : + +```javascript +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; + +var mainWindow; + +app.on('ready', function() { + var electronScreen = electron.screen; + var size = electronScreen.getPrimaryDisplay().workAreaSize; + mainWindow = new BrowserWindow({ width: size.width, height: size.height }); +}); +``` + +另一个例子,在次页外创建一个窗口: + +```javascript +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; + +var mainWindow; + +app.on('ready', function() { + var electronScreen = electron.screen; + var displays = electronScreen.getAllDisplays(); + var externalDisplay = null; + for (var i in displays) { + if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) { + externalDisplay = displays[i]; + break; + } + } + + if (externalDisplay) { + mainWindow = new BrowserWindow({ + x: externalDisplay.bounds.x + 50, + y: externalDisplay.bounds.y + 50 + }); + } +}); +``` + +## `Display` 对象 + +`Display` 对象表示了物力方式连接系统. 一个伪造的 `Display` 或许存在于一个无头系统中,或者一个 `Display` 相当于一个远程的、虚拟的 display. + +* `display` object + * `id` Integer - 与display 相关的唯一性标志. + * `rotation` Integer - 可以是 0, 1, 2, 3, 每个代表了屏幕旋转的度数 0, 90, 180, 270. + * `scaleFactor` Number - Output device's pixel scale factor. + * `touchSupport` String - 可以是 `available`, `unavailable`, `unknown`. + * `bounds` Object + * `size` Object + * `workArea` Object + * `workAreaSize` Object + +## 事件 + +`screen` 模块有如下事件: + +### Event: 'display-added' + +返回: + +* `event` Event +* `newDisplay` Object + +当添加了 `newDisplay` 时发出事件 + +### Event: 'display-removed' + +返回: + +* `event` Event +* `oldDisplay` Object + +当移出了 `oldDisplay` 时发出事件 + +### Event: 'display-metrics-changed' + +返回: + +* `event` Event +* `display` Object +* `changedMetrics` Array + +当一个 `display` 中的一个或更多的 metrics 改变时发出事件. +`changedMetrics` 是一个用来描述这个改变的数组.可能的变化为 `bounds`, +`workArea`, `scaleFactor` 和 `rotation`. + +## 方法 + +`screen` 模块有如下方法: + +### `screen.getCursorScreenPoint()` + +返回当前鼠标的绝对路径 . + +### `screen.getPrimaryDisplay()` + +返回最主要的 display. + +### `screen.getAllDisplays()` + +返回一个当前可用的 display 数组. + +### `screen.getDisplayNearestPoint(point)` + +* `point` Object + * `x` Integer + * `y` Integer + +返回离指定点最近的 display. + +### `screen.getDisplayMatching(rect)` + +* `rect` Object + * `x` Integer + * `y` Integer + * `width` Integer + * `height` Integer + +返回与提供的边界范围最密切相关的 display. \ No newline at end of file From dbb8a6bf52887252fd8f92046c1104c6ac4c07b0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 15 Mar 2016 21:08:43 +0900 Subject: [PATCH 0208/1265] Update brightray for atom/brightray#204 --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index bde17bffdf5..c7abfaafc70 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit bde17bffdf5ff978d5d831bdebb62d12bca6c715 +Subproject commit c7abfaafc70bdc22604574a8ed2b8c8a7c0e27d3 From 492269a0fdc2a19a39ece921ed6fe636838bcb46 Mon Sep 17 00:00:00 2001 From: Thanasis Polychronakis Date: Tue, 15 Mar 2016 15:49:34 +0200 Subject: [PATCH 0209/1265] More info for crash reporter form type and payload --- docs/api/crash-reporter.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 98465dffc97..5a7ff720bfd 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -54,7 +54,7 @@ ID. ## crash-reporter Payload -The crash reporter will send the following data to the `submitURL` as `POST`: +The crash reporter will send the following data to the `submitURL` as a `multipart/form-data` `POST`: * `ver` String - The version of Electron. * `platform` String - e.g. 'win32'. @@ -66,6 +66,6 @@ The crash reporter will send the following data to the `submitURL` as `POST`: * `prod` String - Name of the underlying product. In this case Electron. * `_companyName` String - The company name in the `crashReporter` `options` object. -* `upload_file_minidump` File - The crash report as file. +* `upload_file_minidump` File - The crash report as file, a binary. * All level one properties of the `extra` object in the `crashReporter`. `options` object From 12f218c747850a66aefb2caf8686785d0d89583c Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 16 Mar 2016 10:26:49 +0800 Subject: [PATCH 0210/1265] add build-system-overview first --- .../development/build-system-overview.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 docs-translations/zh-CN/development/build-system-overview.md diff --git a/docs-translations/zh-CN/development/build-system-overview.md b/docs-translations/zh-CN/development/build-system-overview.md new file mode 100644 index 00000000000..20b0ff185fe --- /dev/null +++ b/docs-translations/zh-CN/development/build-system-overview.md @@ -0,0 +1,42 @@ +# Build System Overview + +Electron 使用 `gyp` 来生成项目 ,使用 `ninja` 来编译项目. 项目配置可以在 `.gyp` 和 `.gypi` 文件中找到. + +## Gyp 文件 + +下面的 `gyp` 文件包含了编译 Electron 的主要规则 : + +* `atom.gyp` 定义了 Electron 它自己是怎样被编译的. +* `common.gypi` 调整 node 的编译配置,来让它结合 Chromium 一起编译. +* `vendor/brightray/brightray.gyp` 定义了 `brightray` 是如何被编译的,并且包含了默认配置来连接到 Chromium. +* `vendor/brightray/brightray.gypi` 包含了常用的创建配置. + +## 创建组件 + +在 Chromium 还是一个相当大的项目的时候,最后链接阶段会花了好几分钟,这让开发变得很困难. 为了解决这个困难,Chromium 引入了 "component build" ,这让每个创建的组建都是分隔开的共享库,让链接更快,但是这浪费了文件大小和性能. + +在 Electron 中,我们采用了一个非常相似的方法 : 在创建 `Debug` , 二进制文件会被链接进入一个 Chromium 组件的共享版本库来达到快速链接; 在创建 `Release`, 二进制文件会被链接进入一个静态版本库, 所以我们可以有最小的二进制文件size和最佳的体验. + +## Minimal Bootstrapping + +在运行 bootstrap 脚本的时候,所有的 Chromium 预编译二进制文件会被下载.默认静态库和共享库会被下载,并且项目的最后大小会在 800MB 到 2GB 之间,这取决于平台类型. + +默认,`libchromiumcontent` 是从 Amazon Web Services 上下载下来的.如果设置了 `LIBCHROMIUMCONTENT_MIRROR` 环境变量,bootstrap脚本会从这里下载下来. [`libchromiumcontent-qiniu-mirror`](https://github.com/hokein/libchromiumcontent-qiniu-mirror) 是 `libchromiumcontent` 的映射.如果你不能连接 AWS,你可以切换下载路径:`export LIBCHROMIUMCONTENT_MIRROR=http://7xk3d2.dl1.z0.glb.clouddn.com/` +如果只是想快速搭建一个 Electron 的测试或开发环境,可以通过 `--dev` 参数只下载共享版本库: + +```bash +$ ./script/bootstrap.py --dev +$ ./script/build.py -c D +``` + +## Two-Phase Project Generation + +在 `Release` 和 `Debug` 编译的时候后,Electron 链接了不同配置的库 .然而 `gyp`不支持为不同的配置文件进行不同的链接设置. + +为了规避这个问题,Electron 在运行 `gyp` 的时候,使用了一个 `gyp` 的变量 `libchromiumcontent_component`来控制应该使用哪个链接设置,并且只生成一个目标. + +## Target Names + +与大多数的项目不同,它们使用 `Release` 和 `Debug` 作为目标名字,而 Electron 使用使用的是 `R` 和 `D`.这是因为如果只定义了一个 `Release` 或 `Debug` 编译配置,`gyp` 会随机崩溃,并且在同一时候,Electron 只生成一个目标,如上所述. + +这只对开发者可用,如果想重新编译 Electron ,将不会成功. \ No newline at end of file From 3eac767e729d59d76f67379ee72ef5b02b8291d6 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 16 Mar 2016 11:54:33 +0800 Subject: [PATCH 0211/1265] add build-instructions three first --- .../development/build-instructions-linux.md | 123 ++++++++++++++++ .../development/build-instructions-osx.md | 62 ++++++++ .../development/build-instructions-windows.md | 136 ++++++++++++++++++ .../development/build-system-overview.md | 16 +-- 4 files changed, 329 insertions(+), 8 deletions(-) create mode 100644 docs-translations/zh-CN/development/build-instructions-linux.md create mode 100644 docs-translations/zh-CN/development/build-instructions-osx.md create mode 100644 docs-translations/zh-CN/development/build-instructions-windows.md diff --git a/docs-translations/zh-CN/development/build-instructions-linux.md b/docs-translations/zh-CN/development/build-instructions-linux.md new file mode 100644 index 00000000000..0f76e78b9a5 --- /dev/null +++ b/docs-translations/zh-CN/development/build-instructions-linux.md @@ -0,0 +1,123 @@ +# Build Instructions (Linux) + +遵循下面的引导,在 Linux 上构建 Electron . + +## Prerequisites + +* Python 2.7.x. 一些发行版如 CentOS 仍然使用 Python 2.6.x ,所以或许需要 check 你的 Python 版本,使用 `python -V`. +* Node.js v0.12.x. 有很多方法来安装 Node. 可以从 [Node.js](http://nodejs.org)下载原文件并且编译它 .也可以作为一个标准的用户在 home 目录下安装 node .或者尝试使用仓库 [NodeSource](https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories). +* Clang 3.4 或更新的版本. +* GTK+开发头文件和libnotify. + +在 Ubuntu, 安装下面的库 : + +```bash +$ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \ + libnotify-dev libgnome-keyring-dev libgconf2-dev \ + libasound2-dev libcap-dev libcups2-dev libxtst-dev \ + libxss1 libnss3-dev gcc-multilib g++-multilib +``` + +在 Fedora, 安装下面的库 : + +```bash +$ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring-devel \ + xorg-x11-server-utils libcap-devel cups-devel libXtst-devel \ + alsa-lib-devel libXrandr-devel GConf2-devel nss-devel +``` + +其它版本的也许提供了相似的包来安装,通过包管理器,例如 pacman. +或一个可以编译源文件的. + +## 使用虚拟机 + +如果在虚拟机上构建 Electron,你需要一个固定大小的设备,至少需要 25 gigabytes . + +## 获取代码 + +```bash +$ git clone https://github.com/atom/electron.git +``` + +## Bootstrapping + +bootstrap 脚本也是必要下载的构建依赖,来创建项目文件.需要使用 Python 2.7.x 来让脚本成功执行.正确下载文件会花费较长的时间. +注意我们使用的是 `ninja` 来构建 Electron,所以没有生成 `Makefile` 项目. + +```bash +$ cd electron +$ ./script/bootstrap.py -v +``` + +### 交叉编译 + +如果想创建一个 `arm` target ,应当还要下载下面的依赖 : + +```bash +$ sudo apt-get install libc6-dev-armhf-cross linux-libc-dev-armhf-cross \ + g++-arm-linux-gnueabihf +``` + +为了编译 `arm` 或 `ia32` targets, 你应当为 `bootstrap.py` 脚本使用 +`--target_arch` 参数: + +```bash +$ ./script/bootstrap.py -v --target_arch=arm +``` + +## 构建 + +创建 `Release` 、 `Debug` target: + +```bash +$ ./script/build.py +``` + +这个脚本也许会在目录 `out/R` 下创建一个巨大的可执行的 Electron . 文件大小或许会超过 1.3 gigabytes. 原因是 Release target 二进制文件包含了 调试符号 .运行 `create-dist.py` 脚本来减小文件的 size : + +```bash +$ ./script/create-dist.py +``` +这会在 `dist` 目录下创建一个有大量小文件的工作空间. 运行 create-dist.py 脚本之后, 或许你想删除仍然在 `out/R` 下的 1.3+ gigabyte 二进制文件. + +可以只创建 `Debug` target: + +```bash +$ ./script/build.py -c D +``` + +创建完毕, 可以在 `out/D`下面找到 `electron`. + +## Cleaning + +删除构建文件 : + +```bash +$ ./script/clean.py +``` + +## 解决问题 + +确保你已经安装了所有的依赖 . + +### Error While Loading Shared Libraries: libtinfo.so.5 + +预构建的 `clang` 会尝试链接到 `libtinfo.so.5`. 取决于 host 架构, 适当的使用 `libncurses`: + +```bash +$ sudo ln -s /usr/lib/libncurses.so.5 /usr/lib/libtinfo.so.5 +``` + +## Tests + +测试你的修改是否符合项目代码风格,使用: + +```bash +$ ./script/cpplint.py +``` + +测试有效性使用: + +```bash +$ ./script/test.py +``` \ No newline at end of file diff --git a/docs-translations/zh-CN/development/build-instructions-osx.md b/docs-translations/zh-CN/development/build-instructions-osx.md new file mode 100644 index 00000000000..18074a3085a --- /dev/null +++ b/docs-translations/zh-CN/development/build-instructions-osx.md @@ -0,0 +1,62 @@ +# Build Instructions (OS X) + +遵循下面的引导,在 OS X 上构建 Electron . + +## 前提 + +* OS X >= 10.8 +* [Xcode](https://developer.apple.com/technologies/tools/) >= 5.1 +* [node.js](http://nodejs.org) (外部) + +如果你通过 Homebrew 使用 Python 下载,需要安装下面的 Python 模块: + +* pyobjc + +## 获取代码 + +```bash +$ git clone https://github.com/atom/electron.git +``` + +## Bootstrapping + +bootstrap 脚本也是必要下载的构建依赖,来创建项目文件.注意我们使用的是 `ninja` 来构建 Electron,所以没有生成 Xcode 项目. + +```bash +$ cd electron +$ ./script/bootstrap.py -v +``` + +## 构建 + +创建 `Release` 、 `Debug` target: + +```bash +$ ./script/build.py +``` + +可以只创建 `Debug` target: + +```bash +$ ./script/build.py -c D +``` + +创建完毕, 可以在 `out/D` 下面找到 `Electron.app`. + +## 32位支持 + +在 OS X 上,构建 Electron 只支持 64位的,不支持 32位的 . + +## 测试 + +测试你的修改是否符合项目代码风格,使用: + +```bash +$ ./script/cpplint.py +``` + +测试有效性使用: + +```bash +$ ./script/test.py +``` \ No newline at end of file diff --git a/docs-translations/zh-CN/development/build-instructions-windows.md b/docs-translations/zh-CN/development/build-instructions-windows.md new file mode 100644 index 00000000000..7b11dc7f57f --- /dev/null +++ b/docs-translations/zh-CN/development/build-instructions-windows.md @@ -0,0 +1,136 @@ +# Build Instructions (Windows) + +遵循下面的引导,在 Windows 上构建 Electron . + +## 前提 + +* Windows 7 / Server 2008 R2 or higher +* Visual Studio 2013 with Update 4 - [download VS 2013 Community Edition for + free](https://www.visualstudio.com/news/vs2013-community-vs). +* [Python 2.7](http://www.python.org/download/releases/2.7/) +* [Node.js](http://nodejs.org/download/) +* [Git](http://git-scm.com) + +如果你现在还没有安装 Windows , [modern.ie](https://www.modern.ie/en-us/virtualization-tools#downloads) 有一个 timebombed 版本的 Windows ,你可以用它来构建 Electron. + +构建 Electron 完全的依赖于命令行,并且不可通过 Visual Studio. +可以使用任何的编辑器来开发 Electron ,未来会支持 Visual Studio. + +**注意:** 虽然 Visual Studio 不是用来构建的,但是它仍然 +**必须的** ,因为我们需要它提供的构建工具栏. + +**注意:** Visual Studio 2015 不可用. 请确定使用 MSVS +**2013**. + +## 获取代码 + +```powershell +$ git clone https://github.com/atom/electron.git +``` + +## Bootstrapping + +bootstrap 脚本也是必要下载的构建依赖,来创建项目文件.注意我们使用的是 `ninja` 来构建 Electron,所以没有生成 Visual Studio 项目. + +```powershell +$ cd electron +$ python script\bootstrap.py -v +``` + +## 构建 + +创建 `Release` 、 `Debug` target: + +```powershell +$ python script\build.py +``` + +可以只创建 `Debug` target: + +```powershell +$ python script\build.py -c D +``` + +创建完毕, 可以在 `out/D`(debug target) 或 `out\R` (release target) 下面找到 `electron.exe`. + +## 64bit Build + +为了构建64位的 target,在运行 bootstrap 脚本的时候需要使用 `--target_arch=x64` : + +```powershell +$ python script\bootstrap.py -v --target_arch=x64 +``` + +其他构建步骤完全相同. + +## Tests + +测试你的修改是否符合项目代码风格,使用: + +```powershell +$ python script\cpplint.py +``` + +测试有效性使用: + +```powershell +$ python script\test.py +``` +在构建 debug 时为 Tests包含原生模块 (例如 `runas`) 将不会执行(详情 [#2558](https://github.com/atom/electron/issues/2558)), 但是它们在构建 release 会起效. + +运行 release 构建使用 : + +```powershell +$ python script\test.py -R +``` + +## 解决问题 + +### Command xxxx not found + +如果你遇到了一个错误,类似 `Command xxxx not found`, 可以尝试使用 `VS2012 Command Prompt` 控制台来执行构建脚本 . + +### Fatal internal compiler error: C1001 + +确保你已经安装了 Visual Studio 的最新安装包 . + +### Assertion failed: ((handle))->activecnt >= 0 + +如果在 Cygwin 下构建的,你可能会看到 `bootstrap.py` 失败并且附带下面错误 : + +``` +Assertion failed: ((handle))->activecnt >= 0, file src\win\pipe.c, line 1430 + +Traceback (most recent call last): + File "script/bootstrap.py", line 87, in + sys.exit(main()) + File "script/bootstrap.py", line 22, in main + update_node_modules('.') + File "script/bootstrap.py", line 56, in update_node_modules + execute([NPM, 'install']) + File "/home/zcbenz/codes/raven/script/lib/util.py", line 118, in execute + raise e +subprocess.CalledProcessError: Command '['npm.cmd', 'install']' returned non-zero exit status 3 +``` + +这是由同时使用 Cygwin Python 和 Win32 Node 造成的 bug.解决办法就是使用 Win32 Python 执行 bootstrap 脚本 (假定你已经在目录 `C:\Python27` 下安装了 Python): + +```powershell +$ /cygdrive/c/Python27/python.exe script/bootstrap.py +``` + +### LNK1181: cannot open input file 'kernel32.lib' + +重新安装 32位的 Node.js. + +### Error: ENOENT, stat 'C:\Users\USERNAME\AppData\Roaming\npm' + +简单创建目录 [应该可以解决问题](http://stackoverflow.com/a/25095327/102704): + +```powershell +$ mkdir ~\AppData\Roaming\npm +``` + +### node-gyp is not recognized as an internal or external command + +如果你使用 Git Bash 来构建,或许会遇到这个错误,可以使用 PowerShell 或 VS2012 Command Prompt 来代替 . \ No newline at end of file diff --git a/docs-translations/zh-CN/development/build-system-overview.md b/docs-translations/zh-CN/development/build-system-overview.md index 20b0ff185fe..95aea7fb1f5 100644 --- a/docs-translations/zh-CN/development/build-system-overview.md +++ b/docs-translations/zh-CN/development/build-system-overview.md @@ -1,14 +1,14 @@ # Build System Overview -Electron 使用 `gyp` 来生成项目 ,使用 `ninja` 来编译项目. 项目配置可以在 `.gyp` 和 `.gypi` 文件中找到. +Electron 使用 `gyp` 来生成项目 ,使用 `ninja` 来构建项目. 项目配置可以在 `.gyp` 和 `.gypi` 文件中找到. ## Gyp 文件 -下面的 `gyp` 文件包含了编译 Electron 的主要规则 : +下面的 `gyp` 文件包含了构建 Electron 的主要规则 : -* `atom.gyp` 定义了 Electron 它自己是怎样被编译的. -* `common.gypi` 调整 node 的编译配置,来让它结合 Chromium 一起编译. -* `vendor/brightray/brightray.gyp` 定义了 `brightray` 是如何被编译的,并且包含了默认配置来连接到 Chromium. +* `atom.gyp` 定义了 Electron 它自己是怎样被构建的. +* `common.gypi` 调整 node 的构建配置,来让它结合 Chromium 一起构建. +* `vendor/brightray/brightray.gyp` 定义了 `brightray` 是如何被构建的,并且包含了默认配置来连接到 Chromium. * `vendor/brightray/brightray.gypi` 包含了常用的创建配置. ## 创建组件 @@ -31,12 +31,12 @@ $ ./script/build.py -c D ## Two-Phase Project Generation -在 `Release` 和 `Debug` 编译的时候后,Electron 链接了不同配置的库 .然而 `gyp`不支持为不同的配置文件进行不同的链接设置. +在 `Release` 和 `Debug` 构建的时候后,Electron 链接了不同配置的库 .然而 `gyp`不支持为不同的配置文件进行不同的链接设置. 为了规避这个问题,Electron 在运行 `gyp` 的时候,使用了一个 `gyp` 的变量 `libchromiumcontent_component`来控制应该使用哪个链接设置,并且只生成一个目标. ## Target Names -与大多数的项目不同,它们使用 `Release` 和 `Debug` 作为目标名字,而 Electron 使用使用的是 `R` 和 `D`.这是因为如果只定义了一个 `Release` 或 `Debug` 编译配置,`gyp` 会随机崩溃,并且在同一时候,Electron 只生成一个目标,如上所述. +与大多数的项目不同,它们使用 `Release` 和 `Debug` 作为目标名字,而 Electron 使用使用的是 `R` 和 `D`.这是因为如果只定义了一个 `Release` 或 `Debug` 构建配置,`gyp` 会随机崩溃,并且在同一时候,Electron 只生成一个目标,如上所述. -这只对开发者可用,如果想重新编译 Electron ,将不会成功. \ No newline at end of file +这只对开发者可用,如果想重新构建 Electron ,将不会成功. \ No newline at end of file From 7bcb99f8230866325d2980ed91d81e8b9b766b7e Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 16 Mar 2016 15:41:12 +0800 Subject: [PATCH 0212/1265] add last three files first --- .../development/setting-up-symbol-server.md | 38 +++++ .../mac-app-store-submission-guide.md | 147 ++++++++++++++++++ .../tutorial/using-widevine-cdm-plugin.md | 67 ++++++++ 3 files changed, 252 insertions(+) create mode 100644 docs-translations/zh-CN/development/setting-up-symbol-server.md create mode 100644 docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md create mode 100644 docs-translations/zh-CN/tutorial/using-widevine-cdm-plugin.md diff --git a/docs-translations/zh-CN/development/setting-up-symbol-server.md b/docs-translations/zh-CN/development/setting-up-symbol-server.md new file mode 100644 index 00000000000..01098bcc77c --- /dev/null +++ b/docs-translations/zh-CN/development/setting-up-symbol-server.md @@ -0,0 +1,38 @@ +# Setting Up Symbol Server in Debugger + +调试 symbols 让你有更好的调试 sessions. 它们有可执行的动态库的函数信息,并且提供信息来获得洁净的呼叫栈. 一个 Symbol 服务器允许调试器自动加载正确的 symbols, 二进制文件 和 资源文件,不用再去强制用户下载巨大的调试文件. 服务器函数类似 +[Microsoft's symbol server](http://support.microsoft.com/kb/311503) ,所以这里的记录可用. + +注意,因为公众版本的 Electron 构建是最优化的,调试不一定一直简单.调试器将不会给显示出所有变量内容,并且因为内联,尾调用,和其它编译器优化,执行路径会看起来很怪异 . 唯一的解决办法是搭建一个不优化的本地构建. + +Electron 使用的官方 symbol 服务器地址为 +`http://54.249.141.255:8086/atom-shell/symbols` . +你不能直接访问这个路径,必须将其添加到你的调试工具的 symbol 路径上.在下面的例子中,使用了一个本地缓存目录来避免重复从服务器获取 PDB. 在你的电脑上使用一个恰当的缓存目录来代替 `c:\code\symbols` . + +## Using the Symbol Server in Windbg + +Windbg symbol 路径被配制为一个限制带星号字符的字符串. 要只使用 Electron 的 symbol 服务器, 将下列记录添加到你的 symbol 路径 (__注意:__ 如果你愿意使用一个不同的地点来下载 symbols,你可以在你的电脑中使用任何可写的目录来代替 `c:\code\symbols`): + +``` +SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols +``` + +使用 Windbg 菜单或通过输入 `.sympath` 命令,在环境中设置一个 `_NT_SYMBOL_PATH` 字符串.如果你也想从微软的 symbol 服务器获得 symbols ,你应当首先将它们先列出来 : + +``` +SRV*c:\code\symbols\*http://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols +``` + +## 在 Visual Studio 中使用 symbol 服务器 + + + + +## Troubleshooting: Symbols will not load + +在 Windbg 中输入下列命令,打印出未什么 symbols 没有加载 : + +``` +> !sym noisy +> .reload /f chromiumcontent.dll +``` \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md b/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md new file mode 100644 index 00000000000..45cff454a96 --- /dev/null +++ b/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md @@ -0,0 +1,147 @@ +# Mac App Store 应用提交向导 + +自从 v0.34.0, Electron 就允许提交应用包到 Mac App Store +(MAS) . 这个向导提供的信息有 : 如何提交应用和 MAS 构建的限制. + +__注意:__ 从 v0.36.0,当应用成为沙箱之后,会有一个 bug 阻止 GPU 进程开启 , 所以在这个 bug 修复之前,建议使用 v0.35.x .更多查看 [issue #3871][issue-3871] . + +__注意:__ 提交应用到 Mac App Store 需要参加 [Apple Developer +Program][developer-program] , 这需要花钱. + +## 如何提交 + +下面步骤介绍了一个简单的提交应用到商店方法.然而,这些步骤不能保证你的应用被 Apple 接受;你仍然需要阅读 Apple 的 [Submitting Your App][submitting-your-app] 关于如何满足 Mac App Store 要求的向导. + +### 获得证书 + +为了提交应用到商店,首先需要从 Apple 获得一个证书.可以遵循 [existing guides][nwjs-guide]. + +### App 签名 + +获得证书之后,你可以使用 [Application Distribution](application-distribution.md) 打包你的应用, 然后前往提交你的应用.这个步骤基本上和其他程序一样,但是这 key 一个个的标识 Electron 的每个依赖. + +首先,你需要准备2个授权文件 . + +`child.plist`: + +```xml + + + + + com.apple.security.app-sandbox + + com.apple.security.inherit + + + +``` + +`parent.plist`: + +```xml + + + + + com.apple.security.app-sandbox + + + +``` + +然后使用下面的脚本标识你的应用 : + +```bash +#!/bin/bash + +# Name of your app. +APP="YourApp" +# The path of you app to sign. +APP_PATH="/path/to/YouApp.app" +# The path to the location you want to put the signed package. +RESULT_PATH="~/Desktop/$APP.pkg" +# The name of certificates you requested. +APP_KEY="3rd Party Mac Developer Application: Company Name (APPIDENTITY)" +INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)" + +FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks" + +codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A" +codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" +codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" +codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" +if [ -d "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" ]; then + # Signing a non-MAS build. + codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Mantle.framework/Versions/A" + codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/ReactiveCocoa.framework/Versions/A" + codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" +fi +codesign -fs "$APP_KEY" --entitlements parent.plist "$APP_PATH" + +productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH" +``` +如果你是 OS X 下的应用沙箱使用新手,应当仔细阅读 Apple 的 [Enabling App Sandbox][enable-app-sandbox] 来有一点基础,然后向授权文件添加你的应用需要的许可 keys . + +### 上传你的应用并检查提交 + +在签名应用之后,可以使用应用 Loader 来上传到 iTunes 链接处理 , 确保在上传之前你已经 [created a record][create-record]. 然后你能 [submit your app for review][submit-for-review]. + +## MAS构建限制 + +为了让你的应用沙箱满足所有条件,在 MAS 构建的时候,下面的模块被禁用了 : + +* `crashReporter` +* `autoUpdater` + +并且下面的行为也改变了: + +* 一些机子的视频采集功能无效. +* 某些特征不可访问. +* Apps 不可识别 DNS 改变. + +也由于应用沙箱的使用方法,应用可以访问的资源被严格限制了 ; 阅读更多信息 [App Sandboxing][app-sandboxing] . + +## Electron 使用的加密算法 + +取决于你所在地方的国家和地区 , Mac App Store 或许需要记录你应用的加密算法 , 甚至要求你提交一个 U.S 加密注册(ERN) 许可的复印件. + +Electron 使用下列加密算法: + +* AES - [NIST SP 800-38A](http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf), [NIST SP 800-38D](http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf), [RFC 3394](http://www.ietf.org/rfc/rfc3394.txt) +* HMAC - [FIPS 198-1](http://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf) +* ECDSA - ANS X9.62–2005 +* ECDH - ANS X9.63–2001 +* HKDF - [NIST SP 800-56C](http://csrc.nist.gov/publications/nistpubs/800-56C/SP-800-56C.pdf) +* PBKDF2 - [RFC 2898](https://tools.ietf.org/html/rfc2898) +* RSA - [RFC 3447](http://www.ietf.org/rfc/rfc3447) +* SHA - [FIPS 180-4](http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf) +* Blowfish - https://www.schneier.com/cryptography/blowfish/ +* CAST - [RFC 2144](https://tools.ietf.org/html/rfc2144), [RFC 2612](https://tools.ietf.org/html/rfc2612) +* DES - [FIPS 46-3](http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf) +* DH - [RFC 2631](https://tools.ietf.org/html/rfc2631) +* DSA - [ANSI X9.30](http://webstore.ansi.org/RecordDetail.aspx?sku=ANSI+X9.30-1%3A1997) +* EC - [SEC 1](http://www.secg.org/sec1-v2.pdf) +* IDEA - "On the Design and Security of Block Ciphers" book by X. Lai +* MD2 - [RFC 1319](http://tools.ietf.org/html/rfc1319) +* MD4 - [RFC 6150](https://tools.ietf.org/html/rfc6150) +* MD5 - [RFC 1321](https://tools.ietf.org/html/rfc1321) +* MDC2 - [ISO/IEC 10118-2](https://www.openssl.org/docs/manmaster/crypto/mdc2.html) +* RC2 - [RFC 2268](https://tools.ietf.org/html/rfc2268) +* RC4 - [RFC 4345](https://tools.ietf.org/html/rfc4345) +* RC5 - http://people.csail.mit.edu/rivest/Rivest-rc5rev.pdf +* RIPEMD - [ISO/IEC 10118-3](http://webstore.ansi.org/RecordDetail.aspx?sku=ISO%2FIEC%2010118-3:2004) + +如何获取 ERN 许可, 可看这篇文章: [How to legally +submit an app to Apple’s App Store when it uses encryption (or how to obtain an +ERN)][ern-tutorial]. + +[developer-program]: https://developer.apple.com/support/compare-memberships/ +[submitting-your-app]: https://developer.apple.com/library/mac/documentation/IDEs/Conceptual/AppDistributionGuide/SubmittingYourApp/SubmittingYourApp.html +[nwjs-guide]: https://github.com/nwjs/nw.js/wiki/Mac-App-Store-%28MAS%29-Submission-Guideline#first-steps +[enable-app-sandbox]: https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html +[create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html +[submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html +[app-sandboxing]: https://developer.apple.com/app-sandboxing/ +[issue-3871]: https://github.com/atom/electron/issues/3871 +[ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/using-widevine-cdm-plugin.md b/docs-translations/zh-CN/tutorial/using-widevine-cdm-plugin.md new file mode 100644 index 00000000000..d5df1646c48 --- /dev/null +++ b/docs-translations/zh-CN/tutorial/using-widevine-cdm-plugin.md @@ -0,0 +1,67 @@ +# 使用 Widevine CDM 插件 + +在 Electron ,你可以使用 Widevine CDM 插件装载 Chrome 浏览器 . + +## 获取插件 + +Electron 没有为 Widevine CDM 插件 配制许可 reasons, 为了获得它,首先需要安装官方的 chrome 浏览器,这匹配了体系架构和 Electron 构建使用的 chrome 版本 . + +__注意:__ Chrome 浏览器的主要版本必须和 Electron 使用的版本一样,否则插件不会有效,虽然 `navigator.plugins` 会显示你已经安装了它 . + +### Windows & OS X + +在 Chrome 浏览器中打开 `chrome://components/` ,找到 `WidevineCdm` 并且确定它更新到最新版本,然后你可以从 `APP_DATA/Google/Chrome/WidevineCDM/VERSION/_platform_specific/PLATFORM_ARCH/` 路径找到所有的插件二进制文件 . + +`APP_DATA` 是系统存放数据的地方,在 Windows 上它是 +`%LOCALAPPDATA%`, 在 OS X 上它是 `~/Library/Application Support`. `VERSION` 是 +Widevine CDM 插件的版本字符串, 类似 `1.4.8.866`. `PLATFORM` 是 `mac` 或 +`win`. `ARCH` 是 `x86` 或 `x64`. + +在 Windows,必要的二进制文件是 `widevinecdm.dll` and +`widevinecdmadapter.dll`, 在 OS X ,它们是 `libwidevinecdm.dylib` 和 +`widevinecdmadapter.plugin`. 你可以将它们复制到任何你喜欢的地方,但是它们必须要放在一起. + +### Linux + +在 Linux ,Chrome 浏览器将插件的二进制文件装载在一起 , 你可以在 `/opt/google/chrome` 下找到,文件名是 `libwidevinecdm.so` 和 +`libwidevinecdmadapter.so`. + +## 使用插件 + +在获得了插件文件后,你可以使用 `--widevine-cdm-path` 命令行开关来将 `widevinecdmadapter` 的路径传递给 Electron , 插件版本使用 `--widevine-cdm-version` 开关. + +__注意:__ 虽然只有 `widevinecdmadapter` 的二进制文件传递给了 Electron, `widevinecdm` 二进制文件应当放在它的旁边. + +必须在 `app` 模块的 `ready` 事件触发之前使用命令行开关,并且 page 使用的插件必须激活. + +示例代码 : + +```javascript +// You have to pass the filename of `widevinecdmadapter` here, it is +// * `widevinecdmadapter.plugin` on OS X, +// * `libwidevinecdmadapter.so` on Linux, +// * `widevinecdmadapter.dll` on Windows. +app.commandLine.appendSwitch('widevine-cdm-path', '/path/to/widevinecdmadapter.plugin'); +// The version of plugin can be got from `chrome://plugins` page in Chrome. +app.commandLine.appendSwitch('widevine-cdm-version', '1.4.8.866'); + +var mainWindow = null; +app.on('ready', function() { + mainWindow = new BrowserWindow({ + webPreferences: { + // The `plugins` have to be enabled. + plugins: true + } + }) +}); +``` + +## 验证插件 + +为了验证插件是否工作,你可以使用下面的方法 : + +* 打开开发者工具查看是否 `navigator.plugins` 包含了 Widevine +CDM 插件. +* 打开 `https://shaka-player-demo.appspot.com/` 加载一个使用 +`Widevine` 的 manifest. +* 打开 http://www.dash-player.com/demo/drm-test-area/, 检查是否界面输出 `bitdash uses Widevine in your browser`, 然后播放 video. \ No newline at end of file From 25931d16ab424e61e9a678ce040b1753670ddf3c Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 16 Mar 2016 15:56:52 +0800 Subject: [PATCH 0213/1265] modify 2days ago update 2files --- docs-translations/zh-CN/api/web-contents.md | 1 + docs-translations/zh-CN/api/web-view-tag.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs-translations/zh-CN/api/web-contents.md b/docs-translations/zh-CN/api/web-contents.md index 1b7011bb0fa..f168849863a 100644 --- a/docs-translations/zh-CN/api/web-contents.md +++ b/docs-translations/zh-CN/api/web-contents.md @@ -242,6 +242,7 @@ var webContents = win.webContents; * `result` Object * `requestId` Integer * `finalUpdate` Boolean - 标识是否还有更多的值可以查看. + * `activeMatchOrdinal` Integer (可选) - 活动匹配位置 * `matches` Integer (可选) - 匹配数量. * `selectionArea` Object (可选) - 协调首个匹配位置. diff --git a/docs-translations/zh-CN/api/web-view-tag.md b/docs-translations/zh-CN/api/web-view-tag.md index f1f3ef9080c..e1e31f6f5a0 100644 --- a/docs-translations/zh-CN/api/web-view-tag.md +++ b/docs-translations/zh-CN/api/web-view-tag.md @@ -528,6 +528,7 @@ webview.addEventListener('console-message', function(e) { * `result` Object * `requestId` Integer * `finalUpdate` Boolean - 指明下面是否还有更多的回应. + * `activeMatchOrdinal` Integer (可选) - 活动匹配位置 * `matches` Integer (optional) - 匹配数量. * `selectionArea` Object (optional) - 整合第一个匹配域. From 0d8994d81daa908e598fb8baf6d6cf3a558fceb0 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 16 Mar 2016 09:37:04 -0700 Subject: [PATCH 0214/1265] improve wording in the FAQ --- docs/faq/electron-faq.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index a58d31107b6..ef08de5237f 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -5,7 +5,7 @@ The Chrome version of Electron is usually bumped within one or two weeks after a new stable Chrome version gets released. -Also we only use stable channel of Chrome, if an important fix is in beta or dev +Also we only use stable channel of Chrome. If an important fix is in beta or dev channel, we will back-port it. ## When will Electron upgrade to latest Node.js? @@ -25,7 +25,7 @@ use HTML5 APIs which are already available in browsers. Good candidates are [Storage API][storage], [`localStorage`][local-storage], [`sessionStorage`][session-storage], and [IndexedDB][indexed-db]. -Or you can use the IPC system, which are specific to Electron, to store objects +Or you can use the IPC system, which is specific to Electron, to store objects in the main process as a global variable, and then to access them from the renderers through the `remote` module: @@ -51,8 +51,7 @@ console.log(require('remote').getGlobal('sharedObject').someProperty); This happens when the variable which is used to store the window/tray gets garbage collected. -It is recommended to have a reading of following articles you encountered this -problem: +If you encounter this problem, the following articles may prove helpful: * [Memory Management][memory-management] * [Variable Scope][variable-scope] @@ -78,8 +77,8 @@ app.on('ready', function() { ## I can not use jQuery/RequireJS/Meteor/AngularJS in Electron. Due to the Node.js integration of Electron, there are some extra symbols -inserted into DOM, like `module`, `exports`, `require`. This causes troubles for -some libraries since they want to insert the symbols with same names. +inserted into the DOM like `module`, `exports`, `require`. This causes troubles for +some libraries since they want to insert the symbols with the same names. To solve this, you can turn off node integration in Electron: @@ -141,7 +140,7 @@ npm uninstall -g electron ``` However if your are using the built-in module but still getting this error, it -is very likely you are using the module in wrong process. For example +is very likely you are using the module in the wrong process. For example `electron.app` can only be used in the main process, while `electron.webFrame` is only available in renderer processes. From da47b569e8e31a2e19bc7723818a92f8fec23908 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 16 Mar 2016 09:42:33 -0700 Subject: [PATCH 0215/1265] link to the ninja website --- docs/development/build-instructions-osx.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/build-instructions-osx.md b/docs/development/build-instructions-osx.md index ac51bf0dc22..598aa01c440 100644 --- a/docs/development/build-instructions-osx.md +++ b/docs/development/build-instructions-osx.md @@ -22,7 +22,7 @@ $ git clone https://github.com/atom/electron.git ## Bootstrapping The bootstrap script will download all necessary build dependencies and create -the build project files. Notice that we're using `ninja` to build Electron so +the build project files. Notice that we're using [ninja](https://ninja-build.org/) to build Electron so there is no Xcode project generated. ```bash From 6503f32ef9b89fde1798a8ac94bf318c0606e1ed Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 16 Mar 2016 09:47:12 -0700 Subject: [PATCH 0216/1265] add another link to ninja --- docs/development/build-system-overview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/build-system-overview.md b/docs/development/build-system-overview.md index 04067ce8c79..41c65e450a4 100644 --- a/docs/development/build-system-overview.md +++ b/docs/development/build-system-overview.md @@ -1,6 +1,6 @@ # Build System Overview -Electron uses `gyp` for project generation and `ninja` for building. Project +Electron uses `gyp` for project generation and [ninja](https://ninja-build.org/) for building. Project configurations can be found in the `.gyp` and `.gypi` files. ## Gyp Files From fa197ad5832b43044f6731c83e278d4bea3b83cd Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 16 Mar 2016 12:40:28 -0700 Subject: [PATCH 0217/1265] Fix failing test --- spec/api-native-image-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index e411fb11002..fd13ad76db3 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -45,7 +45,7 @@ describe('nativeImage module', () => { assert.equal(nsimage.length, 8); // If all bytes are null, that's Bad - assert.equal(nsimage.reduce((acc,x) => acc || (x != 0)), true); + assert.equal(!!nsimage.reduce((acc,x) => acc || (x != 0)), true); }); }); }); From 148014f99a8a764b795233299cf0e6f4478c15ac Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 16 Mar 2016 12:42:23 -0700 Subject: [PATCH 0218/1265] Fix spec failure --- spec/api-native-image-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index fd13ad76db3..a7ee8be007e 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -45,7 +45,7 @@ describe('nativeImage module', () => { assert.equal(nsimage.length, 8); // If all bytes are null, that's Bad - assert.equal(!!nsimage.reduce((acc,x) => acc || (x != 0)), true); + assert.equal(nsimage.reduce((acc,x) => acc || (x != 0), false), true); }); }); }); From e94da877c2b3a205d196ee5dc5781e5b9524cc26 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 16 Mar 2016 12:49:34 -0700 Subject: [PATCH 0219/1265] Fix compile oopses on non-OS X --- atom/common/api/atom_api_native_image.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index d616b428330..81db35715bc 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -226,10 +226,11 @@ std::string NativeImage::ToDataURL() { v8::Local NativeImage::GetNativeHandle( v8::Isolate* isolate, mate::Arguments* args) { +void* ptr = NULL; #if defined(OS_MACOSX) - void* ptr = reinterpret_cast(image_.AsNSImage()); + ptr = reinterpret_cast(image_.AsNSImage()); #else - args.ThrowError(); + args->ThrowError(); return v8::Undefined(isolate); #endif From 5acfa8611af9fe2878d774ae2cf91d5931cc820b Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 16 Mar 2016 13:15:34 -0700 Subject: [PATCH 0220/1265] link to gyp --- docs/development/build-system-overview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/build-system-overview.md b/docs/development/build-system-overview.md index 41c65e450a4..61b88e14078 100644 --- a/docs/development/build-system-overview.md +++ b/docs/development/build-system-overview.md @@ -1,6 +1,6 @@ # Build System Overview -Electron uses `gyp` for project generation and [ninja](https://ninja-build.org/) for building. Project +Electron uses [gyp](https://gyp.gsrc.io/) for project generation and [ninja](https://ninja-build.org/) for building. Project configurations can be found in the `.gyp` and `.gypi` files. ## Gyp Files From 01980dea11bf66b0275eccf974f5d638438ee438 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 17 Mar 2016 00:03:24 -0700 Subject: [PATCH 0221/1265] s/troubles/problems/ --- docs/faq/electron-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index ef08de5237f..41b301d7198 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -77,7 +77,7 @@ app.on('ready', function() { ## I can not use jQuery/RequireJS/Meteor/AngularJS in Electron. Due to the Node.js integration of Electron, there are some extra symbols -inserted into the DOM like `module`, `exports`, `require`. This causes troubles for +inserted into the DOM like `module`, `exports`, `require`. This causes problems for some libraries since they want to insert the symbols with the same names. To solve this, you can turn off node integration in Electron: From 75ec7a057a67a15816c75299cd5336a5d5553a86 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 17 Mar 2016 21:45:13 +0900 Subject: [PATCH 0222/1265] Update brightray for #4681 --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index c7abfaafc70..242feb1c817 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit c7abfaafc70bdc22604574a8ed2b8c8a7c0e27d3 +Subproject commit 242feb1c817565de6592e9e672c136635bfff453 From f8b9a66ead386034e6cc60e83d4a024f2a749c1e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 17 Mar 2016 21:55:02 +0900 Subject: [PATCH 0223/1265] docs: Make it clear image.getNativeHandle is OS X only --- docs/api/native-image.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/api/native-image.md b/docs/api/native-image.md index c33f35c6fe5..e0c3ae46624 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -133,11 +133,14 @@ Returns a [Buffer][buffer] that contains the image's `JPEG` encoded data. Returns the data URL of the image. -### `image.getNativeHandle()` +### `image.getNativeHandle()` _OS X_ -Returns a pointer to an underlying native type (encoded as a [Buffer][buffer]) which can be used with native APIs. Note that in many cases, this pointer is a weak pointer to the underlying native image not a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. +Returns a [Buffer][buffer] that stores C pointer to underlying native handle of +the image. On OS X, a pointer to `NSImage` instance would be returned. -Returns a [Buffer][buffer] that represents a pointer to a native type - on OS X, this type is an NSImage object. +Notice that the returned pointer is a weak pointer to the underlying native +image instead of a copy, so you _must_ ensure that the associated +`nativeImage` instance is kept around. ### `image.isEmpty()` From 939d69df6e0a97ad67838f4f01888fb0f86e15de Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 17 Mar 2016 22:01:31 +0900 Subject: [PATCH 0224/1265] Throw error with message of "Not implemented". --- atom/common/api/atom_api_native_image.cc | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 81db35715bc..3dda326f59f 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -184,8 +184,7 @@ mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) .SetMethod("toPng", &NativeImage::ToPNG) .SetMethod("toJpeg", &NativeImage::ToJPEG) - .SetMethod("getNativeHandle", - &NativeImage::GetNativeHandle) + .SetMethod("getNativeHandle", &NativeImage::GetNativeHandle) .SetMethod("toDataURL", &NativeImage::ToDataURL) .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. .SetMethod("isEmpty", &NativeImage::IsEmpty) @@ -223,21 +222,18 @@ std::string NativeImage::ToDataURL() { return data_url; } -v8::Local NativeImage::GetNativeHandle( - v8::Isolate* isolate, - mate::Arguments* args) { -void* ptr = NULL; +v8::Local NativeImage::GetNativeHandle(v8::Isolate* isolate, + mate::Arguments* args) { #if defined(OS_MACOSX) - ptr = reinterpret_cast(image_.AsNSImage()); + NSImage* ptr = image_.AsNSImage(); + return node::Buffer::Copy( + isolate, + reinterpret_cast(ptr), + sizeof(void*)).ToLocalChecked(); #else - args->ThrowError(); + args->ThrowError("Not implemented"); return v8::Undefined(isolate); #endif - - return node::Buffer::Copy( - isolate, - reinterpret_cast(ptr), - sizeof(void*)).ToLocalChecked(); } bool NativeImage::IsEmpty() { From cbd37ad3b9f3f565f5e5029df4125486bacbd521 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 17 Mar 2016 22:29:32 +0900 Subject: [PATCH 0225/1265] docs: List breakpad server implementations --- docs/api/crash-reporter.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 5a7ff720bfd..64e5602474a 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -16,6 +16,12 @@ crashReporter.start({ }); ``` +For setting up a server to accept and process crash reports, you can use +following projects: + +* [socorro](https://github.com/mozilla/socorro) +* [mini-breakpad-server](https://github.com/atom/mini-breakpad-server) + ## Methods The `crash-reporter` module has the following methods: @@ -66,6 +72,6 @@ The crash reporter will send the following data to the `submitURL` as a `multipa * `prod` String - Name of the underlying product. In this case Electron. * `_companyName` String - The company name in the `crashReporter` `options` object. -* `upload_file_minidump` File - The crash report as file, a binary. +* `upload_file_minidump` File - The crash report in the format of `minidump`. * All level one properties of the `extra` object in the `crashReporter`. `options` object From 5c9b19b508045df6070f53422b154490be2796d7 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 09:24:57 -0700 Subject: [PATCH 0226/1265] web-preferences -> webPreferences --- spec/static/main.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/static/main.js b/spec/static/main.js index 9a049e3f107..77a3c392722 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -82,8 +82,8 @@ app.on('ready', function() { show: false, width: 800, height: 600, - 'web-preferences': { - javascript: true // Test whether web-preferences crashes. + webPreferences: { + javascript: true // Test whether web preferences crashes. }, }); window.loadURL(url.format({ From 1e8e8f18b42f4a442e5932d20c2c8b3dd295e823 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 09:31:32 -0700 Subject: [PATCH 0227/1265] Add failing specs for deprecated options usage --- spec/api-browser-window-spec.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index c6deb38684c..e0b3c75437e 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -759,4 +759,25 @@ describe('browser-window module', function() { }); }); }); + + describe('deprecated options', function() { + it('throws a deprecation error for option keys using hyphens instead of camel case', function() { + assert.throws(function () { + new BrowserWindow({'min-width': 500}) + }, 'min-width is deprecated. Use minWidth instead.'); + }); + + it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function() { + assert.throws(function () { + new BrowserWindow({webPreferences: {'node-integration': false}}) + }, 'node-integration is deprecated. Use nodeIntegration instead.'); + }); + + it('throws a deprecation error for option keys that should be set on webPreferences', function() { + assert.throws(function () { + new BrowserWindow({zoomFactor: 1}) + }, 'Setting zoomFactor on options is deprecated. Set it on options.webPreferences instead.'); + }); + }) + }); From dfd13cf4ca797afc0027368640a2a65123df9e1d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 09:33:19 -0700 Subject: [PATCH 0228/1265] persistented -> persisted --- lib/browser/chrome-extension.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/browser/chrome-extension.js b/lib/browser/chrome-extension.js index fcbb8c7f15f..054a0cd6c67 100644 --- a/lib/browser/chrome-extension.js +++ b/lib/browser/chrome-extension.js @@ -132,7 +132,7 @@ app.once('ready', function() { return delete extensionInfoMap[name]; }; - // Load persistented extensions when devtools is opened. + // Load persisted extensions when devtools is opened. init = BrowserWindow.prototype._init; return BrowserWindow.prototype._init = function() { init.call(this); From 1b6e01ce6de14f4df6e57d81ceb99b9714bd6159 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 09:35:18 -0700 Subject: [PATCH 0229/1265] Add missing semicolons --- spec/api-browser-window-spec.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index e0b3c75437e..00bc2fb9f18 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -763,21 +763,20 @@ describe('browser-window module', function() { describe('deprecated options', function() { it('throws a deprecation error for option keys using hyphens instead of camel case', function() { assert.throws(function () { - new BrowserWindow({'min-width': 500}) + new BrowserWindow({'min-width': 500}); }, 'min-width is deprecated. Use minWidth instead.'); }); it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function() { assert.throws(function () { - new BrowserWindow({webPreferences: {'node-integration': false}}) + new BrowserWindow({webPreferences: {'node-integration': false}}); }, 'node-integration is deprecated. Use nodeIntegration instead.'); }); it('throws a deprecation error for option keys that should be set on webPreferences', function() { assert.throws(function () { - new BrowserWindow({zoomFactor: 1}) + new BrowserWindow({zoomFactor: 1}); }, 'Setting zoomFactor on options is deprecated. Set it on options.webPreferences instead.'); }); - }) - + }); }); From 15397bf879b26e56df4d28453a30f04ea915b984 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 09:38:03 -0700 Subject: [PATCH 0230/1265] Report deprecated BrowserWindow options --- atom/browser/api/atom_api_window.cc | 19 +++++++++++ lib/browser/api/browser-window.js | 53 ++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 6c0f0f6f762..87f6411e665 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -52,6 +52,11 @@ namespace api { namespace { +// The DeprecatedOptionsCheckCallback funtion which is implemented in JavaScript +using DeprecatedOptionsCheckCallback = + base::Callback)>; +DeprecatedOptionsCheckCallback g_deprecated_options_check; + void OnCapturePageDone( v8::Isolate* isolate, const base::Callback& callback, @@ -291,6 +296,13 @@ mate::Wrappable* Window::New(v8::Isolate* isolate, mate::Arguments* args) { options = mate::Dictionary::CreateEmpty(isolate); } + std::string deprecation_message = g_deprecated_options_check.Run( + options.GetHandle()); + if (deprecation_message.length() > 0) { + args->ThrowError(deprecation_message); + return nullptr; + } + return new Window(isolate, options); } @@ -797,6 +809,10 @@ v8::Local Window::From(v8::Isolate* isolate, return v8::Null(isolate); } +void SetDeprecatedOptionsCheck(const DeprecatedOptionsCheckCallback& callback) { + g_deprecated_options_check = callback; +} + } // namespace api } // namespace atom @@ -816,6 +832,9 @@ void Initialize(v8::Local exports, v8::Local unused, &mate::TrackableObject::FromWeakMapID); browser_window.SetMethod("getAllWindows", &mate::TrackableObject::GetAll); + browser_window.SetMethod("_setDeprecatedOptionsCheck", + &atom::api::SetDeprecatedOptionsCheck); + mate::Dictionary dict(isolate, exports); dict.Set("BrowserWindow", browser_window); diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 7e2a8d38c31..9645f855eed 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -8,7 +8,6 @@ const BrowserWindow = process.atomBinding('window').BrowserWindow; BrowserWindow.prototype.__proto__ = EventEmitter.prototype; BrowserWindow.prototype._init = function() { - // avoid recursive require. var app, menu; app = require('electron').app; @@ -240,4 +239,56 @@ BrowserWindow.prototype.getPageTitle = deprecate('getPageTitle', 'webContents.ge return (ref1 = this.webContents) != null ? ref1.getTitle() : void 0; }); +const isDeprecatedKey = function(key) { + return key.indexOf('-') >= 0; +}; + +// Map deprecated key with hyphens to camel case key +const getNonDeprecatedKey = function(deprecatedKey) { + return deprecatedKey.replace(/-./g, function(match) { + return match[1].toUpperCase(); + }); +}; + +// TODO Remove for 1.0 +const checkForDeprecatedOptions = function(options) { + if (!options) return ''; + + let keysToCheck = Object.keys(options); + if (options.webPreferences) { + keysToCheck = keysToCheck.concat(Object.keys(options.webPreferences)); + } + + // Check options for keys with hypens in them + let deprecatedKey = keysToCheck.filter(isDeprecatedKey)[0]; + if (deprecatedKey) { + try { + deprecate.warn(deprecatedKey, getNonDeprecatedKey(deprecatedKey)); + } catch (error) { + // Return error message so it can be rethrown via C++ + return error.message; + } + } + + let webPreferenceOption; + if (options.hasOwnProperty('nodeIntegration')) { + webPreferenceOption = 'nodeIntegration'; + } else if (options.hasOwnProperty('preload')) { + webPreferenceOption = 'preload'; + } else if (options.hasOwnProperty('zoomFactor')) { + webPreferenceOption = 'zoomFactor'; + } + if (webPreferenceOption) { + try { + deprecate.log(`Setting ${webPreferenceOption} on options is deprecated. Set it on options.webPreferences instead.`); + } catch (error) { + // Return error message so it can be rethrown via C++ + return error.message; + } + } + + return ''; +}; +BrowserWindow._setDeprecatedOptionsCheck(checkForDeprecatedOptions); + module.exports = BrowserWindow; From 2acfb8ad82ee149bec56254c2f61f7fc4b69fcba Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 10:47:55 -0700 Subject: [PATCH 0231/1265] node-integration -> nodeIntegration --- spec/chromium-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 71cef125618..ac9403a7ecd 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -155,7 +155,7 @@ describe('chromium feature', function() { b.close(); }); - it('accepts "node-integration" as feature', function(done) { + it('accepts "nodeIntegration" as feature', function(done) { var b; listener = function(event) { assert.equal(event.data, 'undefined'); From a14380ed01c7bf5d8535bd9515a3964d2a71db63 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 10:59:47 -0700 Subject: [PATCH 0232/1265] Set webPrereferences from features tring --- lib/renderer/override.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 2aceec5353d..d9e00122870 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -101,6 +101,7 @@ window.open = function(url, frameName, features) { } options = {}; ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'zoom-factor']; + const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload']; // Make sure to get rid of excessive whitespace in the property name ref1 = features.split(/,\s*/); @@ -109,7 +110,15 @@ window.open = function(url, frameName, features) { ref2 = feature.split(/\s*=/); name = ref2[0]; value = ref2[1]; - options[name] = value === 'yes' || value === '1' ? true : value === 'no' || value === '0' ? false : value; + value = value === 'yes' || value === '1' ? true : value === 'no' || value === '0' ? false : value; + if (webPreferences.includes(name)) { + if (options.webPreferences == null) { + options.webPreferences = {}; + } + options.webPreferences[name] = value; + } else { + options[name] = value; + } } if (options.left) { if (options.x == null) { From 3e7501579f7644e3e914bacb8ddff4b5291eb302 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 11:00:15 -0700 Subject: [PATCH 0233/1265] Add camel case versions to ints array --- lib/renderer/override.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index d9e00122870..5e9d42adf61 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -100,7 +100,7 @@ window.open = function(url, frameName, features) { features = ''; } options = {}; - ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'zoom-factor']; + ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor']; const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload']; // Make sure to get rid of excessive whitespace in the property name From 90d815ce6ca2d0e28bc29477e5df9ed6798f2b06 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 11:03:50 -0700 Subject: [PATCH 0234/1265] Add todo about removing hyphenated options --- lib/renderer/override.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 5e9d42adf61..69295d1632b 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -100,6 +100,8 @@ window.open = function(url, frameName, features) { features = ''; } options = {}; + + // TODO remove hyphenated options in both of the following arrays for 1.0 ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor']; const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload']; From c31882749d303ef56deadeb8d061641ea1f3f0ee Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 16 Mar 2016 15:03:53 -0700 Subject: [PATCH 0235/1265] Correct typos in comments --- atom/browser/api/atom_api_window.cc | 2 +- lib/browser/api/browser-window.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 87f6411e665..a41b8fae9f2 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -52,7 +52,7 @@ namespace api { namespace { -// The DeprecatedOptionsCheckCallback funtion which is implemented in JavaScript +// This function is implemented in JavaScript using DeprecatedOptionsCheckCallback = base::Callback)>; DeprecatedOptionsCheckCallback g_deprecated_options_check; diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 9645f855eed..fe9d4415d53 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -259,7 +259,7 @@ const checkForDeprecatedOptions = function(options) { keysToCheck = keysToCheck.concat(Object.keys(options.webPreferences)); } - // Check options for keys with hypens in them + // Check options for keys with hyphens in them let deprecatedKey = keysToCheck.filter(isDeprecatedKey)[0]; if (deprecatedKey) { try { From 737ffd8d7c1e7a3a7d67a237b7bde566e071c2f2 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 17 Mar 2016 13:34:30 -0700 Subject: [PATCH 0236/1265] Improve deprecated message on webPreferences options --- lib/browser/api/browser-window.js | 2 +- spec/api-browser-window-spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index fe9d4415d53..87077ffd2d9 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -280,7 +280,7 @@ const checkForDeprecatedOptions = function(options) { } if (webPreferenceOption) { try { - deprecate.log(`Setting ${webPreferenceOption} on options is deprecated. Set it on options.webPreferences instead.`); + deprecate.log(`options.${webPreferenceOption} is deprecated. Use options.webPreferences.${webPreferenceOption} instead.`); } catch (error) { // Return error message so it can be rethrown via C++ return error.message; diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 00bc2fb9f18..beb84a8d748 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -776,7 +776,7 @@ describe('browser-window module', function() { it('throws a deprecation error for option keys that should be set on webPreferences', function() { assert.throws(function () { new BrowserWindow({zoomFactor: 1}); - }, 'Setting zoomFactor on options is deprecated. Set it on options.webPreferences instead.'); + }, 'options.zoomFactor is deprecated. Use options.webPreferences.zoomFactor instead.'); }); }); }); From 87395cdef81a73147dfc75bfb5eeac6337221d16 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 17 Mar 2016 16:09:16 -0700 Subject: [PATCH 0237/1265] add failing spec for undefined accelerator --- spec/api-menu-spec.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/spec/api-menu-spec.js b/spec/api-menu-spec.js index b27840ec4f2..b7bff910f2b 100644 --- a/spec/api-menu-spec.js +++ b/spec/api-menu-spec.js @@ -32,6 +32,17 @@ describe('menu module', function() { ]); }); + it('does not throw exceptions for undefined/null values', function() { + assert.doesNotThrow(function(){ + Menu.buildFromTemplate([ + { + label: 'text', + accelerator: undefined + } + ]); + }); + }); + describe('Menu.buildFromTemplate should reorder based on item position specifiers', function() { it('should position before existing item', function() { var menu = Menu.buildFromTemplate([ From e9ba5abe03762232dd20b940b27298d855b6a3e1 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 17 Mar 2016 16:14:31 -0700 Subject: [PATCH 0238/1265] test for null accelerator too --- spec/api-menu-spec.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spec/api-menu-spec.js b/spec/api-menu-spec.js index b7bff910f2b..cd1e5987008 100644 --- a/spec/api-menu-spec.js +++ b/spec/api-menu-spec.js @@ -38,6 +38,10 @@ describe('menu module', function() { { label: 'text', accelerator: undefined + }, + { + label: 'text again', + accelerator: null } ]); }); From 344dda4029fa475828bf0a27ffb7a58ad08ab398 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 17 Mar 2016 16:20:23 -0700 Subject: [PATCH 0239/1265] ignore set menu item fields --- lib/browser/api/menu.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index cfb00bd4527..4effa10238e 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -269,7 +269,7 @@ Menu.getApplicationMenu = function() { Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder; Menu.buildFromTemplate = function(template) { - var insertIndex, item, j, k, key, len, len1, menu, menuItem, positionedTemplate, value; + var insertIndex, item, j, k, key, len, len1, menu, menuItem, positionedTemplate; if (!Array.isArray(template)) { throw new TypeError('Invalid template for Menu'); } @@ -293,9 +293,9 @@ Menu.buildFromTemplate = function(template) { } menuItem = new MenuItem(item); for (key in item) { - value = item[key]; - if (menuItem[key] == null) { - menuItem[key] = value; + // Preserve extra fields specified by user + if (!menuItem.hasOwnProperty(key)) { + menuItem[key] = item[key]; } } menu.append(menuItem); From 03319a54262a3e936c3d89cb0b2c1b94ca7c7979 Mon Sep 17 00:00:00 2001 From: James Wheare Date: Fri, 18 Mar 2016 15:20:04 +0000 Subject: [PATCH 0240/1265] OSX: Capture 3-finger swipe events in NativeWindow --- atom/browser/api/atom_api_window.cc | 16 ++++++++++++++++ atom/browser/api/atom_api_window.h | 4 ++++ atom/browser/native_window.cc | 20 ++++++++++++++++++++ atom/browser/native_window.h | 4 ++++ atom/browser/native_window_mac.mm | 12 ++++++++++++ atom/browser/native_window_observer.h | 4 ++++ docs/api/browser-window.md | 16 ++++++++++++++++ 7 files changed, 76 insertions(+) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 6c0f0f6f762..c99f80876b8 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -243,6 +243,22 @@ void Window::OnWindowScrollTouchEnd() { Emit("scroll-touch-end"); } +void Window::OnWindowSwipeUp() { + Emit("swipe-up"); +} + +void Window::OnWindowSwipeRight() { + Emit("swipe-right"); +} + +void Window::OnWindowSwipeDown() { + Emit("swipe-down"); +} + +void Window::OnWindowSwipeLeft() { + Emit("swipe-left"); +} + void Window::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index f69f5452994..33bf479b8f9 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -69,6 +69,10 @@ class Window : public mate::TrackableObject, void OnWindowMoved() override; void OnWindowScrollTouchBegin() override; void OnWindowScrollTouchEnd() override; + void OnWindowSwipeUp() override; + void OnWindowSwipeRight() override; + void OnWindowSwipeDown() override; + void OnWindowSwipeLeft() override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 6c64edec5fb..d95c2346642 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -480,6 +480,26 @@ void NativeWindow::NotifyWindowScrollTouchEnd() { OnWindowScrollTouchEnd()); } +void NativeWindow::NotifyWindowSwipeUp() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, + OnWindowSwipeUp()); +} + +void NativeWindow::NotifyWindowSwipeRight() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, + OnWindowSwipeRight()); +} + +void NativeWindow::NotifyWindowSwipeDown() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, + OnWindowSwipeDown()); +} + +void NativeWindow::NotifyWindowSwipeLeft() { + FOR_EACH_OBSERVER(NativeWindowObserver, observers_, + OnWindowSwipeLeft()); +} + void NativeWindow::NotifyWindowLeaveFullScreen() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowLeaveFullScreen()); diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index a215b9eb4c1..27bb4fa5de8 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -221,6 +221,10 @@ class NativeWindow : public base::SupportsUserData, void NotifyWindowMoved(); void NotifyWindowScrollTouchBegin(); void NotifyWindowScrollTouchEnd(); + void NotifyWindowSwipeUp(); + void NotifyWindowSwipeRight(); + void NotifyWindowSwipeDown(); + void NotifyWindowSwipeLeft(); void NotifyWindowEnterFullScreen(); void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index a8f7bc5c168..b0f2df4aaec 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -267,6 +267,18 @@ bool ScopedDisableResize::disable_resize_ = false; // NSWindow overrides. +- (void)swipeWithEvent:(NSEvent *)event { + if (event.deltaY == 1.0) { + shell_->NotifyWindowSwipeUp(); + } else if (event.deltaX == -1.0) { + shell_->NotifyWindowSwipeRight(); + } else if (event.deltaY == -1.0) { + shell_->NotifyWindowSwipeDown(); + } else if (event.deltaX == 1.0) { + shell_->NotifyWindowSwipeLeft(); + } +} + - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (ScopedDisableResize::IsResizeDisabled()) diff --git a/atom/browser/native_window_observer.h b/atom/browser/native_window_observer.h index e9dbff4292e..e88a77af41a 100644 --- a/atom/browser/native_window_observer.h +++ b/atom/browser/native_window_observer.h @@ -58,6 +58,10 @@ class NativeWindowObserver { virtual void OnWindowMoved() {} virtual void OnWindowScrollTouchBegin() {} virtual void OnWindowScrollTouchEnd() {} + virtual void OnWindowSwipeUp() {} + virtual void OnWindowSwipeRight() {} + virtual void OnWindowSwipeDown() {} + virtual void OnWindowSwipeLeft() {} virtual void OnWindowEnterFullScreen() {} virtual void OnWindowLeaveFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {} diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index e2380e4cb18..3ccbb6fe9ad 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -322,6 +322,22 @@ Emitted when scroll wheel event phase has begun. Emitted when scroll wheel event phase has ended. +### Event: 'swipe-up' _OS X_ + +Emitted on 3-finger swipe up. + +### Event: 'swipe-right' _OS X_ + +Emitted on 3-finger swipe right. + +### Event: 'swipe-down' _OS X_ + +Emitted on 3-finger swipe down. + +### Event: 'swipe-left' _OS X_ + +Emitted on 3-finger swipe left. + ## Methods The `BrowserWindow` object has the following methods: From 7668c1ea0b012e4712aa16369ea723a093d7f1d1 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Mar 2016 09:02:58 -0700 Subject: [PATCH 0241/1265] Use deprecate.warn instead of deprecate.log --- lib/browser/api/browser-window.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 87077ffd2d9..ed6cbc4b80a 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -280,7 +280,7 @@ const checkForDeprecatedOptions = function(options) { } if (webPreferenceOption) { try { - deprecate.log(`options.${webPreferenceOption} is deprecated. Use options.webPreferences.${webPreferenceOption} instead.`); + deprecate.warn(`options.${webPreferenceOption}`, `options.webPreferences.${webPreferenceOption}`); } catch (error) { // Return error message so it can be rethrown via C++ return error.message; From 6aa452cda4e3ec6b975bdc9fb3ad043de5bee167 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Mar 2016 09:06:03 -0700 Subject: [PATCH 0242/1265] Set _setDeprecatedOptionsCheck on exports --- atom/browser/api/atom_api_window.cc | 5 ++--- lib/browser/api/browser-window.js | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index a41b8fae9f2..ccc3c8695d5 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -832,12 +832,11 @@ void Initialize(v8::Local exports, v8::Local unused, &mate::TrackableObject::FromWeakMapID); browser_window.SetMethod("getAllWindows", &mate::TrackableObject::GetAll); - browser_window.SetMethod("_setDeprecatedOptionsCheck", - &atom::api::SetDeprecatedOptionsCheck); - mate::Dictionary dict(isolate, exports); dict.Set("BrowserWindow", browser_window); + dict.SetMethod("_setDeprecatedOptionsCheck", + &atom::api::SetDeprecatedOptionsCheck); } } // namespace diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index ed6cbc4b80a..244e87797a5 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -3,7 +3,7 @@ const ipcMain = require('electron').ipcMain; const deprecate = require('electron').deprecate; const EventEmitter = require('events').EventEmitter; -const BrowserWindow = process.atomBinding('window').BrowserWindow; +const {BrowserWindow, _setDeprecatedOptionsCheck} = process.atomBinding('window'); BrowserWindow.prototype.__proto__ = EventEmitter.prototype; @@ -289,6 +289,6 @@ const checkForDeprecatedOptions = function(options) { return ''; }; -BrowserWindow._setDeprecatedOptionsCheck(checkForDeprecatedOptions); +_setDeprecatedOptionsCheck(checkForDeprecatedOptions); module.exports = BrowserWindow; From 827730144b74aa0fc543cc312201cab08a1a0380 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 18 Mar 2016 10:53:49 -0700 Subject: [PATCH 0243/1265] style nit --- spec/api-menu-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/api-menu-spec.js b/spec/api-menu-spec.js index cd1e5987008..bb8736e144f 100644 --- a/spec/api-menu-spec.js +++ b/spec/api-menu-spec.js @@ -33,7 +33,7 @@ describe('menu module', function() { }); it('does not throw exceptions for undefined/null values', function() { - assert.doesNotThrow(function(){ + assert.doesNotThrow(function() { Menu.buildFromTemplate([ { label: 'text', From 99d6afb3a1e65e03c972f43b76f1be905f6aa940 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Mar 2016 11:11:56 -0700 Subject: [PATCH 0244/1265] Add .node-version pinned to 5.1.1 --- .node-version | 1 + 1 file changed, 1 insertion(+) create mode 100644 .node-version diff --git a/.node-version b/.node-version new file mode 100644 index 00000000000..346d9cae72c --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +v5.1.1 From 8889c2986627737e4aadd80fc3f6d6afe2fac27e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Mar 2016 11:51:02 -0700 Subject: [PATCH 0245/1265] Use rest parameters --- lib/browser/api/app.js | 8 ++--- lib/browser/api/dialog.js | 25 ++++++++-------- lib/browser/api/navigation-controller.js | 12 +++----- lib/browser/api/web-contents.js | 27 +++++++---------- lib/browser/guest-view-manager.js | 12 ++++---- lib/browser/guest-window-manager.js | 18 +++++------- lib/browser/init.js | 8 ++--- lib/common/api/callbacks-registry.js | 16 ++++------ lib/common/api/deprecate.js | 12 ++------ lib/renderer/api/ipc-renderer.js | 22 +++++--------- lib/renderer/api/ipc.js | 6 +--- lib/renderer/override.js | 20 ++++--------- lib/renderer/web-view/guest-view-internal.js | 31 +++++++++----------- lib/renderer/web-view/web-view.js | 14 ++++----- 14 files changed, 88 insertions(+), 143 deletions(-) diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index 8d2d203ee98..27b0cb410e4 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -9,8 +9,6 @@ const bindings = process.atomBinding('app'); const downloadItemBindings = process.atomBinding('download_item'); const app = bindings.app; -var slice = [].slice; - app.__proto__ = EventEmitter.prototype; app.setApplicationMenu = function(menu) { @@ -57,10 +55,8 @@ app.getAppPath = function() { // Routes the events to webContents. var ref1 = ['login', 'certificate-error', 'select-client-certificate']; var fn = function(name) { - return app.on(name, function() { - var args, event, webContents; - event = arguments[0], webContents = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : []; - return webContents.emit.apply(webContents, [name, event].concat(slice.call(args))); + return app.on(name, function(event, webContents, ...args) { + return webContents.emit.apply(webContents, [name, event].concat(args)); }); }; var i, len; diff --git a/lib/browser/api/dialog.js b/lib/browser/api/dialog.js index 102aaa3897d..8eb24aa1bbb 100644 --- a/lib/browser/api/dialog.js +++ b/lib/browser/api/dialog.js @@ -1,9 +1,10 @@ +'use strict'; + const app = require('electron').app; const BrowserWindow = require('electron').BrowserWindow; const binding = process.atomBinding('dialog'); const v8Util = process.atomBinding('v8_util'); -var slice = [].slice; var includes = [].includes; var fileDialogProperties = { @@ -41,9 +42,8 @@ var checkAppInitialized = function() { }; module.exports = { - showOpenDialog: function() { - var args, callback, options, prop, properties, ref1, value, window, wrappedCallback; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + showOpenDialog: function(...args) { + var callback, options, prop, properties, ref1, value, window, wrappedCallback; checkAppInitialized(); ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; if (options == null) { @@ -79,9 +79,9 @@ module.exports = { } : null; return binding.showOpenDialog(String(options.title), String(options.defaultPath), options.filters, properties, window, wrappedCallback); }, - showSaveDialog: function() { - var args, callback, options, ref1, window, wrappedCallback; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + + showSaveDialog: function(...args) { + var callback, options, ref1, window, wrappedCallback; checkAppInitialized(); ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; if (options == null) { @@ -103,9 +103,9 @@ module.exports = { } : null; return binding.showSaveDialog(String(options.title), String(options.defaultPath), options.filters, window, wrappedCallback); }, - showMessageBox: function() { - var args, callback, flags, i, j, len, messageBoxType, options, ref1, ref2, ref3, text, window; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + + showMessageBox: function(...args) { + var callback, flags, i, j, len, messageBoxType, options, ref1, ref2, ref3, text, window; checkAppInitialized(); ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; if (options == null) { @@ -154,9 +154,8 @@ module.exports = { flags = options.noLink ? messageBoxOptions.noLink : 0; return binding.showMessageBox(messageBoxType, options.buttons, options.defaultId, options.cancelId, flags, options.title, options.message, options.detail, options.icon, window, callback); }, - showErrorBox: function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + + showErrorBox: function(...args) { return binding.showErrorBox.apply(binding, args); } }; diff --git a/lib/browser/api/navigation-controller.js b/lib/browser/api/navigation-controller.js index 8c3878a51fa..a934ffb3ba5 100644 --- a/lib/browser/api/navigation-controller.js +++ b/lib/browser/api/navigation-controller.js @@ -2,18 +2,14 @@ const ipcMain = require('electron').ipcMain; -var slice = [].slice; - // The history operation in renderer is redirected to browser. -ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function() { - var args, event, method, ref; - event = arguments[0], method = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : []; +ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function(event, method, ...args) { + var ref; return (ref = event.sender)[method].apply(ref, args); }); -ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function() { - var args, event, method, ref; - event = arguments[0], method = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : []; +ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function(event, method, ...args) { + var ref; return event.returnValue = (ref = event.sender)[method].apply(ref, args); }); diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index c7dd3bc7475..d1630ecf348 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -9,7 +9,7 @@ const Menu = require('electron').Menu; const binding = process.atomBinding('web_contents'); const debuggerBinding = process.atomBinding('debugger'); -let slice = [].slice; +let slice = [].slice; let nextId = 0; let getNextId = function() { @@ -74,13 +74,11 @@ let wrapWebContents = function(webContents) { webContents.setMaxListeners(0); // WebContents::send(channel, args..) - webContents.send = function() { - var args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - var channel = arguments[0]; + webContents.send = function(channel, ...args) { if (channel == null) { throw new Error('Missing required channel argument'); } - return this._send(channel, slice.call(args)); + return this._send(channel, args); }; // The navigation controller. @@ -99,8 +97,7 @@ let wrapWebContents = function(webContents) { // Mapping webFrame methods. for (let method of webFrameMethods) { - webContents[method] = function() { - let args = Array.prototype.slice.call(arguments); + webContents[method] = function(...args) { this.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args); }; } @@ -152,30 +149,26 @@ let wrapWebContents = function(webContents) { }); // This error occurs when host could not be found. - webContents.on('did-fail-provisional-load', function() { - var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - + webContents.on('did-fail-provisional-load', function(...args) { // Calling loadURL during this event might cause crash, so delay the event // until next tick. setImmediate(() => { - this.emit.apply(this, ['did-fail-load'].concat(slice.call(args))); + this.emit.apply(this, ['did-fail-load'].concat(args)); }); }); // Delays the page-title-updated event to next tick. - webContents.on('-page-title-updated', function() { - var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + webContents.on('-page-title-updated', function(...args) { setImmediate(() => { - this.emit.apply(this, ['page-title-updated'].concat(slice.call(args))); + this.emit.apply(this, ['page-title-updated'].concat(args)); }); }); // Deprecated. deprecate.rename(webContents, 'loadUrl', 'loadURL'); deprecate.rename(webContents, 'getUrl', 'getURL'); - deprecate.event(webContents, 'page-title-set', 'page-title-updated', function() { - var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return this.emit.apply(this, ['page-title-set'].concat(slice.call(args))); + deprecate.event(webContents, 'page-title-set', 'page-title-updated', function(...args) { + return this.emit.apply(this, ['page-title-set'].concat(args)); }); return webContents.printToPDF = function(options, callback) { var printingSetting; diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index 574207dd5b1..b19fc5cc858 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -1,3 +1,5 @@ +'use strict'; + const ipcMain = require('electron').ipcMain; const webContents = require('electron').webContents; @@ -136,9 +138,8 @@ var createGuest = function(embedder, params) { // Dispatch events to embedder. fn = function(event) { - return guest.on(event, function() { - var args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + guest.viewInstanceId, event].concat(slice.call(args))); + return guest.on(event, function(_, ...args) { + return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + guest.viewInstanceId, event].concat(args)); }); }; for (j = 0, len1 = supportedWebViewEvents.length; j < len1; j++) { @@ -154,9 +155,8 @@ var createGuest = function(embedder, params) { }); // Autosize. - guest.on('size-changed', function() { - var args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + guest.viewInstanceId].concat(slice.call(args))); + guest.on('size-changed', function(_, ...args) { + return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + guest.viewInstanceId].concat(args)); }); return id; }; diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index bdd32af7a61..a8712ea9f80 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -1,8 +1,9 @@ +'use strict'; + const ipcMain = require('electron').ipcMain; const BrowserWindow = require('electron').BrowserWindow; var hasProp = {}.hasOwnProperty; -var slice = [].slice; var frameToGuest = {}; // Copy attribute of |parent| to |child| if it is not defined in |child|. @@ -81,9 +82,8 @@ var createGuest = function(embedder, url, frameName, options) { }; // Routed window.open messages. -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function() { - var args, event, frameName, options, url; - event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; +ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function(event, ...args) { + var frameName, options, url; url = args[0], frameName = args[1], options = args[2]; options = mergeBrowserWindowOptions(event.sender, options); event.sender.emit('new-window', event, url, frameName, 'new-window', options); @@ -99,9 +99,8 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function(event, guest return (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1.destroy() : void 0; }); -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function() { - var args, guestId, method, ref1; - event = arguments[0], guestId = arguments[1], method = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : []; +ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function(event, guestId, method, ...args) { + var ref1; return event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0; }); @@ -117,8 +116,7 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function(event, } }); -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function() { - var args, guestId, method, ref1, ref2; - guestId = arguments[1], method = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : []; +ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function(event, guestId, method, ...args) { + var ref1, ref2; return (ref1 = BrowserWindow.fromId(guestId)) != null ? (ref2 = ref1.webContents) != null ? ref2[method].apply(ref2, args) : void 0 : void 0; }); diff --git a/lib/browser/init.js b/lib/browser/init.js index 471cc3a5a0a..68ca6fff273 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -1,11 +1,11 @@ +'use strict'; + const fs = require('fs'); const path = require('path'); const util = require('util'); const Module = require('module'); const v8 = require('v8'); -var slice = [].slice; - // We modified the original process.argv to let node.js load the atom.js, // we need to restore it here. process.argv.splice(1, 1); @@ -28,9 +28,7 @@ globalPaths.push(path.join(__dirname, 'api', 'exports')); if (process.platform === 'win32') { // Redirect node's console to use our own implementations, since node can not // handle console output when running as GUI program. - var consoleLog = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + var consoleLog = function(...args) { return process.log(util.format.apply(util, args) + "\n"); }; var streamWrite = function(chunk, encoding, callback) { diff --git a/lib/common/api/callbacks-registry.js b/lib/common/api/callbacks-registry.js index 5b528aa3a6c..d5cfd2da839 100644 --- a/lib/common/api/callbacks-registry.js +++ b/lib/common/api/callbacks-registry.js @@ -1,7 +1,5 @@ 'use strict'; -var slice = [].slice; - const v8Util = process.atomBinding('v8_util'); class CallbacksRegistry { @@ -46,16 +44,14 @@ class CallbacksRegistry { return (ref = this.callbacks[id]) != null ? ref : function() {}; } - call() { - var args, id, ref; - id = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - return (ref = this.get(id)).call.apply(ref, [global].concat(slice.call(args))); + call(id, ...args) { + var ref; + return (ref = this.get(id)).call.apply(ref, [global].concat(args)); } - apply() { - var args, id, ref; - id = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - return (ref = this.get(id)).apply.apply(ref, [global].concat(slice.call(args))); + apply(id, ...args) { + var ref; + return (ref = this.get(id)).apply.apply(ref, [global].concat(args)); } remove(id) { diff --git a/lib/common/api/deprecate.js b/lib/common/api/deprecate.js index 852d544deea..16bf71b3f80 100644 --- a/lib/common/api/deprecate.js +++ b/lib/common/api/deprecate.js @@ -1,8 +1,5 @@ // Deprecate a method. -var deprecate, - slice = [].slice; - -deprecate = function(oldName, newName, fn) { +const deprecate = function(oldName, newName, fn) { var warned; warned = false; return function() { @@ -64,10 +61,7 @@ deprecate.property = function(object, property, method) { deprecate.event = function(emitter, oldName, newName, fn) { var warned; warned = false; - return emitter.on(newName, function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - + return emitter.on(newName, function(...args) { // there is listeners for old API. if (this.listenerCount(oldName) > 0) { if (!(warned || process.noDeprecation)) { @@ -77,7 +71,7 @@ deprecate.event = function(emitter, oldName, newName, fn) { if (fn != null) { return fn.apply(this, arguments); } else { - return this.emit.apply(this, [oldName].concat(slice.call(args))); + return this.emit.apply(this, [oldName].concat(args)); } } }); diff --git a/lib/renderer/api/ipc-renderer.js b/lib/renderer/api/ipc-renderer.js index e946dc7a4c0..03fef36bec7 100644 --- a/lib/renderer/api/ipc-renderer.js +++ b/lib/renderer/api/ipc-renderer.js @@ -1,27 +1,21 @@ +'use strict'; + const binding = process.atomBinding('ipc'); const v8Util = process.atomBinding('v8_util'); -var slice = [].slice; - // Created by init.js. const ipcRenderer = v8Util.getHiddenValue(global, 'ipc'); -ipcRenderer.send = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return binding.send('ipc-message', slice.call(args)); +ipcRenderer.send = function(...args) { + return binding.send('ipc-message', args); }; -ipcRenderer.sendSync = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return JSON.parse(binding.sendSync('ipc-message-sync', slice.call(args))); +ipcRenderer.sendSync = function(...args) { + return JSON.parse(binding.sendSync('ipc-message-sync', args)); }; -ipcRenderer.sendToHost = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return binding.send('ipc-message-host', slice.call(args)); +ipcRenderer.sendToHost = function(...args) { + return binding.send('ipc-message-host', args); }; module.exports = ipcRenderer; diff --git a/lib/renderer/api/ipc.js b/lib/renderer/api/ipc.js index a4bab33af81..ee07c791dc8 100644 --- a/lib/renderer/api/ipc.js +++ b/lib/renderer/api/ipc.js @@ -2,17 +2,13 @@ const ipcRenderer = require('electron').ipcRenderer; const deprecate = require('electron').deprecate; const EventEmitter = require('events').EventEmitter; -var slice = [].slice; - // This module is deprecated, we mirror everything from ipcRenderer. deprecate.warn('ipc module', 'require("electron").ipcRenderer'); // Routes events of ipcRenderer. var ipc = new EventEmitter; -ipcRenderer.emit = function() { - var channel = arguments[0]; - var args = 3 <= arguments.length ? slice.call(arguments, 2) : []; +ipcRenderer.emit = function(channel, event, ...args) { ipc.emit.apply(ipc, [channel].concat(slice.call(args))); return EventEmitter.prototype.emit.apply(ipcRenderer, arguments); }; diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 69295d1632b..93a8b76aca3 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -3,8 +3,6 @@ const ipcRenderer = require('electron').ipcRenderer; const remote = require('electron').remote; -var slice = [].slice; - // Cache browser window visibility var _isVisible = true; var _isMinimized = false; @@ -73,10 +71,8 @@ var BrowserWindowProxy = (function() { return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, location.origin); }; - BrowserWindowProxy.prototype["eval"] = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(slice.call(args))); + BrowserWindowProxy.prototype["eval"] = function(...args) { + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(args)); }; return BrowserWindowProxy; @@ -223,16 +219,12 @@ ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, }); // Forward history operations to browser. -var sendHistoryOperation = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_NAVIGATION_CONTROLLER'].concat(slice.call(args))); +var sendHistoryOperation = function(...args) { + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_NAVIGATION_CONTROLLER'].concat(args)); }; -var getHistoryOperation = function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return ipcRenderer.sendSync.apply(ipcRenderer, ['ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER'].concat(slice.call(args))); +var getHistoryOperation = function(...args) { + return ipcRenderer.sendSync.apply(ipcRenderer, ['ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER'].concat(args)); }; window.history.back = function() { diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index c6e46fab954..a4d8930d904 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -1,8 +1,9 @@ +'use strict'; + const ipcRenderer = require('electron').ipcRenderer; const webFrame = require('electron').webFrame; -var slice = [].slice; -var requestId = 0; +var requestId= 0; var WEB_VIEW_EVENTS = { 'load-commit': ['url', 'isMainFrame'], @@ -41,11 +42,10 @@ var DEPRECATED_EVENTS = { 'page-title-updated': 'page-title-set' }; -var dispatchEvent = function() { - var args, domEvent, eventKey, eventName, f, i, j, len, ref1, webView; - webView = arguments[0], eventName = arguments[1], eventKey = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : []; +var dispatchEvent = function(webView, eventName, eventKey, ...args) { + var domEvent, f, i, j, len, ref1; if (DEPRECATED_EVENTS[eventName] != null) { - dispatchEvent.apply(null, [webView, DEPRECATED_EVENTS[eventName], eventKey].concat(slice.call(args))); + dispatchEvent.apply(null, [webView, DEPRECATED_EVENTS[eventName], eventKey].concat(args)); } domEvent = new Event(eventName); ref1 = WEB_VIEW_EVENTS[eventKey]; @@ -61,22 +61,19 @@ var dispatchEvent = function() { module.exports = { registerEvents: function(webView, viewInstanceId) { - ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + viewInstanceId, function() { - var eventName = arguments[1]; - var args = 3 <= arguments.length ? slice.call(arguments, 2) : []; - return dispatchEvent.apply(null, [webView, eventName, eventName].concat(slice.call(args))); + ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + viewInstanceId, function(event, eventName, ...args) { + return dispatchEvent.apply(null, [webView, eventName, eventName].concat(args)); }); - ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + viewInstanceId, function() { - var channel = arguments[1]; - var args = 3 <= arguments.length ? slice.call(arguments, 2) : []; + + ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + viewInstanceId, function(event, channel, ...args) { var domEvent = new Event('ipc-message'); domEvent.channel = channel; - domEvent.args = slice.call(args); + domEvent.args = args; return webView.dispatchEvent(domEvent); }); - return ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + viewInstanceId, function() { - var args, domEvent, f, i, j, len, ref1; - args = 2 <= arguments.length ? slice.call(arguments, 1) : []; + + return ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + viewInstanceId, function(event, ...args) { + var domEvent, f, i, j, len, ref1; domEvent = new Event('size-changed'); ref1 = ['oldWidth', 'oldHeight', 'newWidth', 'newHeight']; for (i = j = 0, len = ref1.length; j < len; i = ++j) { diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 554b2f04cbe..0d85b7549ff 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -10,7 +10,6 @@ const guestViewInternal = require('./guest-view-internal'); const webViewConstants = require('./web-view-constants'); var hasProp = {}.hasOwnProperty; -var slice = [].slice; // ID generator. var nextId = 0; @@ -392,9 +391,8 @@ var registerWebViewElement = function() { // Forward proto.foo* method calls to WebViewImpl.foo*. createBlockHandler = function(m) { - return function() { - var args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - var internal = v8Util.getHiddenValue(this, 'internal'); + return function(...args) { + const internal = v8Util.getHiddenValue(this, 'internal'); if (internal.webContents) { return internal.webContents[m].apply(internal.webContents, args); } else { @@ -407,11 +405,9 @@ var registerWebViewElement = function() { proto[m] = createBlockHandler(m); } createNonBlockHandler = function(m) { - return function() { - var args, internal; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - internal = v8Util.getHiddenValue(this, 'internal'); - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(slice.call(args))); + return function(...args) { + const internal = v8Util.getHiddenValue(this, 'internal'); + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)); }; }; for (j = 0, len1 = nonblockMethods.length; j < len1; j++) { From a53c7529c19a3403defff56d734be8e588560488 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 18 Mar 2016 11:54:34 -0700 Subject: [PATCH 0246/1265] Remove unneeded slice call --- lib/renderer/api/ipc.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/api/ipc.js b/lib/renderer/api/ipc.js index ee07c791dc8..d3e21db2a3a 100644 --- a/lib/renderer/api/ipc.js +++ b/lib/renderer/api/ipc.js @@ -9,7 +9,7 @@ deprecate.warn('ipc module', 'require("electron").ipcRenderer'); var ipc = new EventEmitter; ipcRenderer.emit = function(channel, event, ...args) { - ipc.emit.apply(ipc, [channel].concat(slice.call(args))); + ipc.emit.apply(ipc, [channel].concat(args)); return EventEmitter.prototype.emit.apply(ipcRenderer, arguments); }; From 70baf86ce2d95aaaf683adb91afb6b46229a4b6f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 20 Mar 2016 03:36:27 +0900 Subject: [PATCH 0247/1265] :memo: Correct link anchor --- docs/tutorial/debugging-main-process.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/debugging-main-process.md b/docs/tutorial/debugging-main-process.md index c7a373f0a45..67f349d9f27 100644 --- a/docs/tutorial/debugging-main-process.md +++ b/docs/tutorial/debugging-main-process.md @@ -44,7 +44,7 @@ $ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback- $ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall ``` -See also [How to install native modules](using-native-node-modules.md). +See also [How to install native modules][how-to-install-native-modules]. ### 5. Enable debug mode for Electron From d73dc0958b6a76d3e551c18f519f04c800205510 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 20 Mar 2016 04:04:39 +0900 Subject: [PATCH 0248/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/crash-reporter.md | 20 ++++++++++++------- docs-translations/ko-KR/api/native-image.md | 9 +++++++++ docs-translations/ko-KR/api/web-contents.md | 1 + docs-translations/ko-KR/api/web-view-tag.md | 1 + .../ko-KR/tutorial/debugging-main-process.md | 6 +++--- 5 files changed, 27 insertions(+), 10 deletions(-) diff --git a/docs-translations/ko-KR/api/crash-reporter.md b/docs-translations/ko-KR/api/crash-reporter.md index 81713760a85..c1437571d3f 100644 --- a/docs-translations/ko-KR/api/crash-reporter.md +++ b/docs-translations/ko-KR/api/crash-reporter.md @@ -16,6 +16,12 @@ crashReporter.start({ }); ``` +서버가 크래시 리포트를 받을 수 있도록 설정하기 위해 다음과 같은 프로젝트를 사용할 수도 +있습니다: + +* [socorro](https://github.com/mozilla/socorro) +* [mini-breakpad-server](https://github.com/atom/mini-breakpad-server) + ## Methods `crash-reporter` 모듈은 다음과 같은 메서드를 가지고 있습니다: @@ -50,15 +56,15 @@ crashReporter.start({ ## crash-reporter 업로드 형식 -Crash Reporter는 다음과 같은 데이터를 `submitURL`에 `POST` 방식으로 전송합니다: +Crash Reporter는 다음과 같은 데이터를 `submitURL`에 `multipart/form-data` `POST` 방식으로 전송합니다: -* `ver` String - Electron의 버전 -* `platform` String - 예시 'win32' -* `process_type` String - 예시 'renderer' -* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72' -* `_version` String - `package.json`내의 `version` 필드 +* `ver` String - Electron의 버전. +* `platform` String - e.g. 'win32'. +* `process_type` String - e.g. 'renderer'. +* `guid` String - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72'. +* `_version` String - `package.json`내의 `version` 필드. * `_productName` String - Crash Reporter의 `options` 객체에서 정의한 제품명. * `prod` String - 기본 제품의 이름. 이 경우 Electron으로 표시됩니다. * `_companyName` String - Crash Reporter의 `options` 객체에서 정의한 회사명. -* `upload_file_minidump` File - 크래시 리포트 파일 +* `upload_file_minidump` File - `minidump` 형식의 크래시 리포트 파일. * Crash Reporter의 `options` 객체에서 정의한 `extra` 객체의 속성들. diff --git a/docs-translations/ko-KR/api/native-image.md b/docs-translations/ko-KR/api/native-image.md index 80be2beeafc..2ef35668cae 100644 --- a/docs-translations/ko-KR/api/native-image.md +++ b/docs-translations/ko-KR/api/native-image.md @@ -131,6 +131,15 @@ var image = nativeImage.createFromPath('/Users/somebody/images/icon.png'); 이미지를 data URL로 반환합니다. +### `image.getNativeHandle()` _OS X_ + +이미지의 네이티브 핸들 밑에 있는 C 포인터를 담은 [Buffer][buffer]을 반환합니다. +OS X에선, `NSImage` 인스턴스가 반환됩니다. + +참고로 반환된 포인터는 복사본이 아닌 네이티브 이미지의 밑에 있는 약한 포인터이며, +따라서 반드시 관련된 `nativeImage` 인스턴스가 확실하게 유지되고 있는지를 인지해야 +합니다. + ### `image.isEmpty()` 이미지가 비었는지 확인합니다. diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 96b5eacc544..1cda4a3af5e 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -255,6 +255,7 @@ Returns: * `result` Object * `requestId` Integer * `finalUpdate` Boolean - 더 많은 응답이 따르는 경우를 표시합니다. + * `activeMatchOrdinal` Integer (optional) - 활성화 일치의 위치. * `matches` Integer (optional) - 일치하는 개수. * `selectionArea` Object (optional) - 첫 일치 부위의 좌표. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index bda18b78898..69fa0c5a767 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -563,6 +563,7 @@ Returns: * `result` Object * `requestId` Integer * `finalUpdate` Boolean - 더 많은 응답이 따르는 경우를 표시합니다. + * `activeMatchOrdinal` Integer (optional) - 활성화 일치의 위치. * `matches` Integer (optional) - 일치하는 개수. * `selectionArea` Object (optional) - 첫 일치 부위의 좌표. diff --git a/docs-translations/ko-KR/tutorial/debugging-main-process.md b/docs-translations/ko-KR/tutorial/debugging-main-process.md index 0b69c0a165a..43b24c79b3a 100644 --- a/docs-translations/ko-KR/tutorial/debugging-main-process.md +++ b/docs-translations/ko-KR/tutorial/debugging-main-process.md @@ -40,11 +40,11 @@ $ npm install git+https://git@github.com/enlight/node-pre-gyp.git#detect-electro ### 4. Electron용 `node-inspector` `v8` 모듈을 재 컴파일 (target을 사용하는 Electron의 버전에 맞춰 변경) ```bash -$ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-to-build --directory node_modules/v8-debug/ --dist-url=https://atom.io/download/atom-shell reinstall -$ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall +$ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback-to-build --directory node_modules/v8-debug/ --dist-url=https://atom.io/download/atom-shell reinstall +$ node_modules/.bin/node-pre-gyp --target=0.36.11 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall ``` -또한 [네이티브 모듈을 사용하는 방법](how-to-install-native-modules) 문서도 참고해보세요. +또한 [네이티브 모듈을 사용하는 방법][how-to-install-native-modules] 문서도 참고해보세요. ### 5. Electron 디버그 모드 활성화 From a89e79a7ed92ce267b790e7e0cd757585cb072ea Mon Sep 17 00:00:00 2001 From: chadluo Date: Sun, 20 Mar 2016 14:20:43 +1100 Subject: [PATCH 0249/1265] fix link --- docs-translations/zh-CN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/README.md b/docs-translations/zh-CN/README.md index d7a8442ad4a..58293e38470 100644 --- a/docs-translations/zh-CN/README.md +++ b/docs-translations/zh-CN/README.md @@ -73,7 +73,7 @@ * [源码目录结构](development/source-code-directory-structure.md) * [与 NW.js(原 node-webkit)在技术上的差异](development/atom-shell-vs-node-webkit.md) * [构建系统概览](development/build-system-overview.md) -* [构建步骤(Mac)](development/build-instructions-mac.md) +* [构建步骤(OS X)](development/build-instructions-osx.md) * [构建步骤(Windows)](development/build-instructions-windows.md) * [构建步骤(Linux)](development/build-instructions-linux.md) * [在调试中使用 Symbol Server](development/setting-up-symbol-server.md) From 9f6541228d0dfcee3d5ae0da8322ee87dcc8c24f Mon Sep 17 00:00:00 2001 From: OctoHuman Date: Sun, 20 Mar 2016 02:09:30 -0500 Subject: [PATCH 0250/1265] Fix alert() --- lib/renderer/override.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 69295d1632b..3daea936f45 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -161,11 +161,14 @@ window.open = function(url, frameName, features) { // Use the dialog API to implement alert(). window.alert = function(message, title) { var buttons; + if (message === undefined) { + message = ''; + } if (title == null) { title = ''; } buttons = ['OK']; - message = message.toString(); + message = String(message); remote.dialog.showMessageBox(remote.getCurrentWindow(), { message: message, title: title, From 116d61185a887b50c2a214c0736e07dd6b806868 Mon Sep 17 00:00:00 2001 From: OctoHuman Date: Sun, 20 Mar 2016 03:40:12 -0500 Subject: [PATCH 0251/1265] Refix alert() --- lib/renderer/override.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 3daea936f45..63c7794ea59 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -161,7 +161,7 @@ window.open = function(url, frameName, features) { // Use the dialog API to implement alert(). window.alert = function(message, title) { var buttons; - if (message === undefined) { + if (arguments.length == 0) { message = ''; } if (title == null) { From f84c41f684f0c6c4bfc69d4e4984c8c7b4e8d33e Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sun, 20 Mar 2016 18:58:25 +0100 Subject: [PATCH 0252/1265] Fix Menu documentation --- docs/api/menu.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/api/menu.md b/docs/api/menu.md index 529113509f8..7487f6597a1 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -240,7 +240,11 @@ Generally, the `template` is just an array of `options` for constructing a You can also attach other fields to the element of the `template` and they will become properties of the constructed menu items. -### `Menu.popup([browserWindow, x, y, positioningItem])` +## Instance Methods + +The `menu` object has the following instance methods: + +### `menu.popup([browserWindow, x, y, positioningItem])` * `browserWindow` BrowserWindow (optional) - Default is `null`. * `x` Number (optional) - Default is -1. @@ -253,20 +257,24 @@ Pops up this menu as a context menu in the `browserWindow`. You can optionally provide a `x, y` coordinate to place the menu at, otherwise it will be placed at the current mouse cursor position. -### `Menu.append(menuItem)` +### `menu.append(menuItem)` * `menuItem` MenuItem Appends the `menuItem` to the menu. -### `Menu.insert(pos, menuItem)` +### `menu.insert(pos, menuItem)` * `pos` Integer * `menuItem` MenuItem Inserts the `menuItem` to the `pos` position of the menu. -### `Menu.items()` +## Instance Properties + +`menu` objects also have the following properties: + +### `menu.items` Get an array containing the menu's items. From 52d09e96006e82a598d4806fb13358147ec1df14 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 21 Mar 2016 21:42:12 +0900 Subject: [PATCH 0253/1265] Run callback of setDestructor immediately when GC happens Fix #4733. --- atom/common/api/object_life_monitor.cc | 17 ++++++++--------- atom/common/api/object_life_monitor.h | 1 + 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/common/api/object_life_monitor.cc b/atom/common/api/object_life_monitor.cc index 9b7c7fe6d05..916ad8a5177 100644 --- a/atom/common/api/object_life_monitor.cc +++ b/atom/common/api/object_life_monitor.cc @@ -31,16 +31,16 @@ ObjectLifeMonitor::ObjectLifeMonitor(v8::Isolate* isolate, // static void ObjectLifeMonitor::OnObjectGC( const v8::WeakCallbackInfo& data) { - // Usually FirstWeakCallback should do nothing other than reset |object_| - // and then set a second weak callback to run later. We can sidestep that, - // because posting a task to the current message loop is all but free - but - // DO NOT add any more work to this method. The only acceptable place to add - // code is RunCallback. ObjectLifeMonitor* self = data.GetParameter(); self->target_.Reset(); - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&ObjectLifeMonitor::RunCallback, - self->weak_ptr_factory_.GetWeakPtr())); + self->RunCallback(); + data.SetSecondPassCallback(Free); +} + +// static +void ObjectLifeMonitor::Free( + const v8::WeakCallbackInfo& data) { + delete data.GetParameter(); } void ObjectLifeMonitor::RunCallback() { @@ -50,7 +50,6 @@ void ObjectLifeMonitor::RunCallback() { v8::Context::Scope context_scope(context); v8::Local::New(isolate_, destructor_)->Call( context->Global(), 0, nullptr); - delete this; } } // namespace atom diff --git a/atom/common/api/object_life_monitor.h b/atom/common/api/object_life_monitor.h index 4c932b94c7b..82d923fcedb 100644 --- a/atom/common/api/object_life_monitor.h +++ b/atom/common/api/object_life_monitor.h @@ -23,6 +23,7 @@ class ObjectLifeMonitor { v8::Local destructor); static void OnObjectGC(const v8::WeakCallbackInfo& data); + static void Free(const v8::WeakCallbackInfo& data); void RunCallback(); From cbfe8b922811fcd049a49e4416d9cff4f1c30982 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 21 Mar 2016 09:12:47 -0700 Subject: [PATCH 0254/1265] Add minWidth and maxWidth to ints array --- lib/renderer/override.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 93a8b76aca3..3548df0dc40 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -88,7 +88,7 @@ if (process.guestInstanceId == null) { // Make the browser window or guest view emit "new-window" event. window.open = function(url, frameName, features) { - var feature, guestId, i, ints, j, len, len1, name, options, ref1, ref2, value; + var feature, guestId, i, j, len, len1, name, options, ref1, ref2, value; if (frameName == null) { frameName = ''; } @@ -98,7 +98,7 @@ window.open = function(url, frameName, features) { options = {}; // TODO remove hyphenated options in both of the following arrays for 1.0 - ints = ['x', 'y', 'width', 'height', 'min-width', 'max-width', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor']; + const ints = ['x', 'y', 'width', 'height', 'min-width', 'minWidth', 'max-width', 'maxWidth', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor']; const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload']; // Make sure to get rid of excessive whitespace in the property name From 8cf4574198da33976ffc0e3c6d87d6aac6e6f48c Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Sun, 20 Mar 2016 00:20:32 +0900 Subject: [PATCH 0255/1265] Document `app.setName()` [ci skip] --- docs/api/app.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/api/app.md b/docs/api/app.md index 8935ed894f0..1f139e08e60 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -331,6 +331,12 @@ to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. +### `app.setName(name)` + +* `name` String + +Overrides the current application's name. + ### `app.getLocale()` Returns the current application locale. From 8fac75f4ee2eee76de179a5ae902aa7a9525dbaa Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 22 Mar 2016 13:48:14 +0900 Subject: [PATCH 0256/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/menu.md | 16 ++++++++++++---- .../ko-KR/development/build-instructions-osx.md | 4 ++-- .../ko-KR/development/build-system-overview.md | 5 +++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 1ea8289a9ce..c64aa8c4fab 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -237,7 +237,11 @@ OS X의 네이티브 액션에 대해 자세히 알아보려면 또한 `template`에는 다른 속성도 추가할 수 있으며 메뉴가 만들어질 때 해당 메뉴 아이템의 프로퍼티로 변환됩니다. -### `Menu.popup([browserWindow, x, y, positioningItem])` +## Instance Methods + +`menu` 객체는 다음과 같은 인스턴스 메서드를 가지고 있습니다: + +### `menu.popup([browserWindow, x, y, positioningItem])` * `browserWindow` BrowserWindow (optional) - 기본값은 `null`입니다. * `x` Number (optional) - 기본값은 -1입니다. @@ -250,20 +254,24 @@ OS X의 네이티브 액션에 대해 자세히 알아보려면 `positioningItem` 속성은 메뉴 팝업 시 마우스 커서에 바로 위치시킬 메뉴 아이템의 인덱스입니다. (OS X에서만 지원합니다) -### `Menu.append(menuItem)` +### `menu.append(menuItem)` * `menuItem` MenuItem 메뉴의 리스트 끝에 `menuItem`을 삽입합니다. -### `Menu.insert(pos, menuItem)` +### `menu.insert(pos, menuItem)` * `pos` Integer * `menuItem` MenuItem `pos` 위치에 `menuItem`을 삽입합니다. -### `Menu.items()` +## Instance Properties + +`menu` 객체는 또한 다음과 같은 속성을 가지고 있습니다: + +### `menu.items` 메뉴가 가지고 있는 메뉴 아이템들의 배열입니다. diff --git a/docs-translations/ko-KR/development/build-instructions-osx.md b/docs-translations/ko-KR/development/build-instructions-osx.md index 9e2a76d3104..142cdaca4df 100644 --- a/docs-translations/ko-KR/development/build-instructions-osx.md +++ b/docs-translations/ko-KR/development/build-instructions-osx.md @@ -21,8 +21,8 @@ $ git clone https://github.com/atom/electron.git ## 부트 스트랩 부트스트랩 스크립트는 필수적인 빌드 종속성 라이브러리들을 모두 다운로드하고 프로젝트 -파일을 생성합니다. 참고로 Electron은 `ninja`를 빌드 툴체인으로 사용하므로 Xcode -프로젝트는 생성되지 않습니다. +파일을 생성합니다. 참고로 Electron은 [ninja](https://ninja-build.org/)를 빌드 +툴체인으로 사용하므로 Xcode 프로젝트는 생성되지 않습니다. ```bash $ cd electron diff --git a/docs-translations/ko-KR/development/build-system-overview.md b/docs-translations/ko-KR/development/build-system-overview.md index 79ead32718d..044a2da0ae2 100644 --- a/docs-translations/ko-KR/development/build-system-overview.md +++ b/docs-translations/ko-KR/development/build-system-overview.md @@ -1,7 +1,8 @@ # 빌드 시스템 개요 -Electron은 프로젝트 생성을 위해 `gyp`를 사용하며 `ninja`를 이용하여 빌드합니다. -프로젝트 설정은 `.gyp` 와 `.gypi` 파일에서 볼 수 있습니다. +Electron은 프로젝트 생성을 위해 [gyp](https://gyp.gsrc.io/)를 사용하며 +[ninja](https://ninja-build.org/)를 이용하여 빌드합니다. 프로젝트 설정은 `.gyp` 와 +`.gypi` 파일에서 볼 수 있습니다. ## gyp 파일 From 4f4dc2f4d8a501494920c4d7ef92a83b8c1a791f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 21 Mar 2016 09:39:07 -0700 Subject: [PATCH 0257/1265] Use destructuring assigment --- lib/browser/api/web-contents.js | 11 ++--- lib/browser/guest-view-manager.js | 7 +--- lib/common/asar.js | 70 +++++++++++++++---------------- 3 files changed, 40 insertions(+), 48 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index d1630ecf348..b8e58df379e 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -9,7 +9,6 @@ const Menu = require('electron').Menu; const binding = process.atomBinding('web_contents'); const debuggerBinding = process.atomBinding('debugger'); -let slice = [].slice; let nextId = 0; let getNextId = function() { @@ -126,19 +125,17 @@ let wrapWebContents = function(webContents) { // Dispatch IPC messages to the ipc module. webContents.on('ipc-message', function(event, packed) { - var args, channel; - channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : []; - return ipcMain.emit.apply(ipcMain, [channel, event].concat(slice.call(args))); + const [channel, ...args] = packed; + return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)); }); webContents.on('ipc-message-sync', function(event, packed) { - var args, channel; - channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : []; + const [channel, ...args] = packed; Object.defineProperty(event, 'returnValue', { set: function(value) { return event.sendReply(JSON.stringify(value)); } }); - return ipcMain.emit.apply(ipcMain, [channel, event].concat(slice.call(args))); + return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)); }); // Handle context menu action request from pepper plugin. diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index b19fc5cc858..2fcd3f987f1 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -3,8 +3,6 @@ const ipcMain = require('electron').ipcMain; const webContents = require('electron').webContents; -var slice = [].slice; - // Doesn't exist in early initialization. var webViewManager = null; @@ -149,9 +147,8 @@ var createGuest = function(embedder, params) { // Dispatch guest's IPC messages to embedder. guest.on('ipc-message-host', function(_, packed) { - var args, channel; - channel = packed[0], args = 2 <= packed.length ? slice.call(packed, 1) : []; - return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(slice.call(args))); + const [channel, ...args] = packed; + return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(args)); }); // Autosize. diff --git a/lib/common/asar.js b/lib/common/asar.js index aeff18916a1..e3996a193ac 100644 --- a/lib/common/asar.js +++ b/lib/common/asar.js @@ -150,9 +150,9 @@ } old = module[name]; return module[name] = function() { - var archive, asarPath, filePath, isAsar, newPath, p, ref; + var archive, newPath, p; p = arguments[arg]; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return old.apply(this, arguments); } @@ -176,9 +176,9 @@ } old = module[name]; return module[name] = function() { - var archive, asarPath, callback, filePath, isAsar, newPath, p, ref; + var archive, callback, newPath, p; p = arguments[arg]; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return old.apply(this, arguments); } @@ -221,8 +221,8 @@ lstatSync = fs.lstatSync; fs.lstatSync = function(p) { - var archive, asarPath, filePath, isAsar, ref, stats; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, stats; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return lstatSync(p); } @@ -238,8 +238,8 @@ }; lstat = fs.lstat; fs.lstat = function(p, callback) { - var archive, asarPath, filePath, isAsar, ref, stats; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, stats; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return lstat(p, callback); } @@ -257,7 +257,7 @@ }; statSync = fs.statSync; fs.statSync = function(p) { - var isAsar = splitPath(p)[0]; + const [isAsar] = splitPath(p); if (!isAsar) { return statSync(p); } @@ -267,7 +267,7 @@ }; stat = fs.stat; fs.stat = function(p, callback) { - var isAsar = splitPath(p)[0]; + const [isAsar] = splitPath(p); if (!isAsar) { return stat(p, callback); } @@ -279,8 +279,8 @@ }; statSyncNoException = fs.statSyncNoException; fs.statSyncNoException = function(p) { - var archive, asarPath, filePath, isAsar, ref, stats; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, stats; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return statSyncNoException(p); } @@ -296,8 +296,8 @@ }; realpathSync = fs.realpathSync; fs.realpathSync = function(p) { - var archive, asarPath, filePath, isAsar, real, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, real; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return realpathSync.apply(this, arguments); } @@ -313,8 +313,8 @@ }; realpath = fs.realpath; fs.realpath = function(p, cache, callback) { - var archive, asarPath, filePath, isAsar, real, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, real; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return realpath.apply(this, arguments); } @@ -339,8 +339,8 @@ }; exists = fs.exists; fs.exists = function(p, callback) { - var archive, asarPath, filePath, isAsar, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return exists(p, callback); } @@ -354,8 +354,8 @@ }; existsSync = fs.existsSync; fs.existsSync = function(p) { - var archive, asarPath, filePath, isAsar, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return existsSync(p); } @@ -367,8 +367,8 @@ }; readFile = fs.readFile; fs.readFile = function(p, options, callback) { - var archive, asarPath, buffer, encoding, fd, filePath, info, isAsar, realPath, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, buffer, encoding, fd, info, realPath; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return readFile.apply(this, arguments); } @@ -418,9 +418,9 @@ readFileSync = fs.readFileSync; fs.readFileSync = function(p, opts) { // this allows v8 to optimize this function - var archive, asarPath, buffer, encoding, fd, filePath, info, isAsar, options, realPath, ref; + var archive, buffer, encoding, fd, info, options, realPath; options = opts; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return readFileSync.apply(this, arguments); } @@ -470,8 +470,8 @@ }; readdir = fs.readdir; fs.readdir = function(p, callback) { - var archive, asarPath, filePath, files, isAsar, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, files; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return readdir.apply(this, arguments); } @@ -489,8 +489,8 @@ }; readdirSync = fs.readdirSync; fs.readdirSync = function(p) { - var archive, asarPath, filePath, files, isAsar, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, files; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return readdirSync.apply(this, arguments); } @@ -506,8 +506,8 @@ }; internalModuleReadFile = process.binding('fs').internalModuleReadFile; process.binding('fs').internalModuleReadFile = function(p) { - var archive, asarPath, buffer, fd, filePath, info, isAsar, realPath, ref; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, buffer, fd, info, realPath; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return internalModuleReadFile(p); } @@ -539,8 +539,8 @@ }; internalModuleStat = process.binding('fs').internalModuleStat; process.binding('fs').internalModuleStat = function(p) { - var archive, asarPath, filePath, isAsar, ref, stats; - ref = splitPath(p), isAsar = ref[0], asarPath = ref[1], filePath = ref[2]; + var archive, stats; + const [isAsar, asarPath, filePath] = splitPath(p); if (!isAsar) { return internalModuleStat(p); } @@ -570,11 +570,10 @@ if (process.platform === 'win32') { mkdir = fs.mkdir; fs.mkdir = function(p, mode, callback) { - var filePath, isAsar, ref; if (typeof mode === 'function') { callback = mode; } - ref = splitPath(p), isAsar = ref[0], filePath = ref[2]; + const [isAsar, , filePath] = splitPath(p); if (isAsar && filePath.length) { return notDirError(callback); } @@ -582,8 +581,7 @@ }; mkdirSync = fs.mkdirSync; fs.mkdirSync = function(p, mode) { - var filePath, isAsar, ref; - ref = splitPath(p), isAsar = ref[0], filePath = ref[2]; + const [isAsar, , filePath] = splitPath(p); if (isAsar && filePath.length) { notDirError(); } From 43746727aa4ad020c109a306c10718b096bd0bb6 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 21 Mar 2016 09:50:11 -0700 Subject: [PATCH 0258/1265] Use direct params instead of rest params --- lib/browser/api/dialog.js | 12 ++++++------ lib/browser/api/menu.js | 4 ++-- lib/browser/guest-window-manager.js | 4 +--- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/lib/browser/api/dialog.js b/lib/browser/api/dialog.js index 8eb24aa1bbb..414cd60d223 100644 --- a/lib/browser/api/dialog.js +++ b/lib/browser/api/dialog.js @@ -43,9 +43,9 @@ var checkAppInitialized = function() { module.exports = { showOpenDialog: function(...args) { - var callback, options, prop, properties, ref1, value, window, wrappedCallback; + var prop, properties, value, wrappedCallback; checkAppInitialized(); - ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; + let [window, options, callback] = parseArgs.apply(null, args); if (options == null) { options = { title: 'Open', @@ -81,9 +81,9 @@ module.exports = { }, showSaveDialog: function(...args) { - var callback, options, ref1, window, wrappedCallback; + var wrappedCallback; checkAppInitialized(); - ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; + let [window, options, callback] = parseArgs.apply(null, args); if (options == null) { options = { title: 'Save' @@ -105,9 +105,9 @@ module.exports = { }, showMessageBox: function(...args) { - var callback, flags, i, j, len, messageBoxType, options, ref1, ref2, ref3, text, window; + var flags, i, j, len, messageBoxType, ref2, ref3, text; checkAppInitialized(); - ref1 = parseArgs.apply(null, args), window = ref1[0], options = ref1[1], callback = ref1[2]; + let [window, options, callback] = parseArgs.apply(null, args); if (options == null) { options = { type: 'none' diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 4effa10238e..c0a0e078db6 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -51,11 +51,11 @@ var indexOfItemById = function(items, id) { // Returns the index of where to insert the item according to |position|. var indexToInsertByPosition = function(items, position) { - var id, insertIndex, query, ref1; + var insertIndex; if (!position) { return items.length; } - ref1 = position.split('='), query = ref1[0], id = ref1[1]; + const [query, id] = position.split('='); insertIndex = indexOfItemById(items, id); if (insertIndex === -1 && query !== 'endof') { console.warn("Item with id '" + id + "' is not found"); diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index a8712ea9f80..daeba15457c 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -82,9 +82,7 @@ var createGuest = function(embedder, url, frameName, options) { }; // Routed window.open messages. -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function(event, ...args) { - var frameName, options, url; - url = args[0], frameName = args[1], options = args[2]; +ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function(event, url, frameName, options) { options = mergeBrowserWindowOptions(event.sender, options); event.sender.emit('new-window', event, url, frameName, 'new-window', options); if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { From 4127b524d577059716f9f4b12cd5c8bc6ed60474 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 21 Mar 2016 11:03:18 -0700 Subject: [PATCH 0259/1265] Destructure params directly --- lib/browser/api/web-contents.js | 6 ++---- lib/browser/guest-view-manager.js | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index b8e58df379e..1e0e83f7b05 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -124,12 +124,10 @@ let wrapWebContents = function(webContents) { }; // Dispatch IPC messages to the ipc module. - webContents.on('ipc-message', function(event, packed) { - const [channel, ...args] = packed; + webContents.on('ipc-message', function(event, [channel, ...args]) { return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)); }); - webContents.on('ipc-message-sync', function(event, packed) { - const [channel, ...args] = packed; + webContents.on('ipc-message-sync', function(event, [channel, ...args]) { Object.defineProperty(event, 'returnValue', { set: function(value) { return event.sendReply(JSON.stringify(value)); diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index 2fcd3f987f1..1c1d6f9cfd0 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -146,8 +146,7 @@ var createGuest = function(embedder, params) { } // Dispatch guest's IPC messages to embedder. - guest.on('ipc-message-host', function(_, packed) { - const [channel, ...args] = packed; + guest.on('ipc-message-host', function(_, [channel, ...args]) { return embedder.send.apply(embedder, ["ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + guest.viewInstanceId, channel].concat(args)); }); From 2d32956903fcd610f0d31e4500b5153729665998 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 21 Mar 2016 11:09:29 -0700 Subject: [PATCH 0260/1265] Destructure objects --- lib/browser/desktop-capturer.js | 6 ++++-- lib/renderer/api/remote.js | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/browser/desktop-capturer.js b/lib/browser/desktop-capturer.js index a4154f0c5b1..c13c6d2e2ec 100644 --- a/lib/browser/desktop-capturer.js +++ b/lib/browser/desktop-capturer.js @@ -1,3 +1,5 @@ +'use strict'; + const ipcMain = require('electron').ipcMain; const desktopCapturer = process.atomBinding('desktop_capturer').desktopCapturer; @@ -33,7 +35,7 @@ ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function(event, captureW desktopCapturer.emit = function(event, name, sources) { // Receiving sources result from main process, now send them back to renderer. - var captureScreen, captureWindow, handledRequest, i, len, ref, ref1, ref2, request, result, source, thumbnailSize, unhandledRequestsQueue; + var handledRequest, i, len, ref, ref1, request, result, source, unhandledRequestsQueue; handledRequest = requestsQueue.shift(0); result = (function() { var i, len, results; @@ -69,7 +71,7 @@ desktopCapturer.emit = function(event, name, sources) { // If the requestsQueue is not empty, start a new request handling. if (requestsQueue.length > 0) { - ref2 = requestsQueue[0].options, captureWindow = ref2.captureWindow, captureScreen = ref2.captureScreen, thumbnailSize = ref2.thumbnailSize; + const {captureWindow, captureScreen, thumbnailSize} = requestsQueue[0].options; return desktopCapturer.startHandling(captureWindow, captureScreen, thumbnailSize); } }; diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index d3d490d053c..6bf7b4229ee 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -216,7 +216,7 @@ let metaToValue = function(meta) { // Construct a plain object from the meta. var metaToPlainObject = function(meta) { - var i, len, name, obj, ref1, ref2, value; + var i, len, obj, ref1; obj = (function() { switch (meta.type) { case 'error': @@ -227,7 +227,7 @@ var metaToPlainObject = function(meta) { })(); ref1 = meta.members; for (i = 0, len = ref1.length; i < len; i++) { - ref2 = ref1[i], name = ref2.name, value = ref2.value; + let {name, value} = ref1[i]; obj[name] = value; } return obj; From 951bd745aa2d1bf8ce899603c4728570a9069dac Mon Sep 17 00:00:00 2001 From: Arek Sredzki Date: Tue, 22 Mar 2016 16:35:03 -0700 Subject: [PATCH 0261/1265] Added electron-release-server link to the docs By request from a couple users, I've added a link to the electron-release-server, that makes using the auto-updater much easier. --- docs/api/auto-updater.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 0a5ca2d2d3d..f82520518c8 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -2,6 +2,8 @@ This module provides an interface for the `Squirrel` auto-updater framework. +You can quickly launch a multi-platform release server for distributing your application by forking [electron-release-server](https://github.com/ArekSredzki/electron-release-server). + ## Platform notices Though `autoUpdater` provides a uniform API for different platforms, there are From c0f13103a49abcb23fe3bf1e4fbdfc59c9b39a6c Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 23 Mar 2016 09:39:03 +0900 Subject: [PATCH 0262/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/app.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 7c18f181742..0924e284c31 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -342,6 +342,12 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 반드시 이 필드도 같이 지정해야 합니다. 이 필드는 맨 앞글자가 대문자인 어플리케이션 전체 이름을 지정해야 합니다. +### `app.setName(name)` + +* `name` String + +현재 어플리케이션의 이름을 덮어씌웁니다. + ### `app.getLocale()` 현재 어플리케이션의 [로케일](https://ko.wikipedia.org/wiki/%EB%A1%9C%EC%BC%80%EC%9D%BC)을 From 8939c6ac12a1b43a66b94c60a2ec7790af98a1f6 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 23 Mar 2016 09:42:14 +0900 Subject: [PATCH 0263/1265] :memo: Update Korean readme as upstream [ci skip] --- README-ko.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README-ko.md b/README-ko.md index 28bb02a1637..5bef003966d 100644 --- a/README-ko.md +++ b/README-ko.md @@ -1,6 +1,7 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) [![Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) [![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/) From 7f787818004dfbc6ad8ca7fec47b237bcab61a80 Mon Sep 17 00:00:00 2001 From: Sergey Bekrin Date: Wed, 23 Mar 2016 10:44:11 +0300 Subject: [PATCH 0264/1265] Improve error reporting when using invalid argument types for dialog API methods --- lib/browser/api/dialog.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/browser/api/dialog.js b/lib/browser/api/dialog.js index 414cd60d223..3a9d1200627 100644 --- a/lib/browser/api/dialog.js +++ b/lib/browser/api/dialog.js @@ -67,9 +67,13 @@ module.exports = { } if (options.title == null) { options.title = ''; + } else if (typeof options.title !== 'string') { + throw new TypeError('Title need to be string'); } if (options.defaultPath == null) { options.defaultPath = ''; + } else if (typeof options.defaultPath !== 'string') { + throw new TypeError('Default path need to be string'); } if (options.filters == null) { options.filters = []; @@ -91,9 +95,13 @@ module.exports = { } if (options.title == null) { options.title = ''; + } else if (typeof options.title !== 'string') { + throw new TypeError('Title need to be string'); } if (options.defaultPath == null) { options.defaultPath = ''; + } else if (typeof options.defaultPath !== 'string') { + throw new TypeError('Default path need to be string'); } if (options.filters == null) { options.filters = []; @@ -125,12 +133,18 @@ module.exports = { } if (options.title == null) { options.title = ''; + } else if (typeof options.title !== 'string') { + throw new TypeError('Title need to be string'); } if (options.message == null) { options.message = ''; + } else if (typeof options.message !== 'string') { + throw new TypeError('Message need to be string'); } if (options.detail == null) { options.detail = ''; + } else if (typeof options.detail !== 'string') { + throw new TypeError('Detail need to be string'); } if (options.icon == null) { options.icon = null; From 0bd45c7d757ab394d6f14406582f2d59e7b0e943 Mon Sep 17 00:00:00 2001 From: heyunjiang <598119677@qq.com> Date: Wed, 23 Mar 2016 16:11:23 +0800 Subject: [PATCH 0265/1265] modify 2016.3.23 --- docs-translations/zh-CN/api/app.md | 6 ++++++ docs-translations/zh-CN/api/crash-reporter.md | 9 +++++++-- docs-translations/zh-CN/api/menu.md | 12 ++++++++---- docs-translations/zh-CN/api/native-image.md | 6 ++++++ .../zh-CN/development/build-instructions-osx.md | 2 +- .../zh-CN/development/build-system-overview.md | 2 +- .../zh-CN/tutorial/debugging-main-process.md | 2 ++ 7 files changed, 31 insertions(+), 8 deletions(-) diff --git a/docs-translations/zh-CN/api/app.md b/docs-translations/zh-CN/api/app.md index dd8d6bcfdf6..21c73cf836a 100644 --- a/docs-translations/zh-CN/api/app.md +++ b/docs-translations/zh-CN/api/app.md @@ -295,6 +295,12 @@ app.on('login', function(event, webContents, request, authInfo, callback) { 由于 npm 的命名规则,通常 `name` 字段是一个短的小写字符串。但是应用名的完整名称通常是首字母大写的,你应该单独使用一个 `productName` 字段,用于表示你的应用程序的完整名称。Electron 会优先使用这个字段作为应用名。 +### `app.setName(name)` + +* `name` String + +重写当前应用的名字 + ### `app.getLocale()` 返回当前应用程序的语言。 diff --git a/docs-translations/zh-CN/api/crash-reporter.md b/docs-translations/zh-CN/api/crash-reporter.md index a4646401ad8..6f2de5e8459 100644 --- a/docs-translations/zh-CN/api/crash-reporter.md +++ b/docs-translations/zh-CN/api/crash-reporter.md @@ -15,6 +15,11 @@ crashReporter.start({ }); ``` +可以使用下面的项目来创建一个服务器,用来接收和处理崩溃报告 : + +* [socorro](https://github.com/mozilla/socorro) +* [mini-breakpad-server](https://github.com/atom/mini-breakpad-server) + ## 方法 `crash-reporter` 模块有如下方法: @@ -44,7 +49,7 @@ crashReporter.start({ ## crash-reporter Payload -崩溃报告将发送下面的数据给 `POST` 型的 `提交 URL` : +崩溃报告将发送下面 `multipart/form-data` `POST` 型的数据给 `submitURL` : * `ver` String - Electron 版本. * `platform` String - 例如 'win32'. @@ -56,6 +61,6 @@ crashReporter.start({ * `prod` String - 基础产品名字. 这种情况为 Electron. * `_companyName` String - `crashReporter` `options` 对象中的公司名字. -* `upload_file_minidump` File - 崩溃报告为文件. +* `upload_file_minidump` File - 崩溃报告按照 `minidump` 的格式. * `crashReporter` 中的 `extra` 对象的所有等级和一个属性. `options` object \ No newline at end of file diff --git a/docs-translations/zh-CN/api/menu.md b/docs-translations/zh-CN/api/menu.md index 3a4e7e5c24e..d0cfeeb33eb 100644 --- a/docs-translations/zh-CN/api/menu.md +++ b/docs-translations/zh-CN/api/menu.md @@ -230,7 +230,11 @@ Menu.setApplicationMenu(menu); 你也可以向 `template` 元素添加其它东西,并且他们会变成已经有的菜单项的属性. -### `Menu.popup([browserWindow, x, y, positioningItem])` +##实例方法 + +`menu` 对象有如下实例方法 + +### `menu.popup([browserWindow, x, y, positioningItem])` * `browserWindow` BrowserWindow (可选) - 默认为 `null`. * `x` Number (可选) - 默认为 -1. @@ -240,20 +244,20 @@ Menu.setApplicationMenu(menu); 在 `browserWindow` 中弹出 context menu .你可以选择性地提供指定的 `x, y` 来设置菜单应该放在哪里,否则它将默认地放在当前鼠标的位置. -### `Menu.append(menuItem)` +### `menu.append(menuItem)` * `menuItem` MenuItem 添加菜单项. -### `Menu.insert(pos, menuItem)` +### `menu.insert(pos, menuItem)` * `pos` Integer * `menuItem` MenuItem 在制定位置添加菜单项. -### `Menu.items()` +### `menu.items()` 获取一个菜单项数组. diff --git a/docs-translations/zh-CN/api/native-image.md b/docs-translations/zh-CN/api/native-image.md index cb2569922b2..3644ff0b8bc 100644 --- a/docs-translations/zh-CN/api/native-image.md +++ b/docs-translations/zh-CN/api/native-image.md @@ -121,6 +121,12 @@ var image = nativeImage.createFromPath('/Users/somebody/images/icon.png'); 返回图片数据的 URL. +### `image.getNativeHandle()` _OS X_ + +返回一个保存了 c 指针的 [Buffer][buffer] 来潜在处理原始图像.在OS X, 将会返回一个 `NSImage` 指针实例. + +注意那返回的指针是潜在原始图像的弱指针,而不是一个复制,你_必须_ 确保与 `nativeImage` 的关联不间断 . + ### `image.isEmpty()` 返回一个 boolean ,标识图片是否为空. diff --git a/docs-translations/zh-CN/development/build-instructions-osx.md b/docs-translations/zh-CN/development/build-instructions-osx.md index 18074a3085a..15485e57acc 100644 --- a/docs-translations/zh-CN/development/build-instructions-osx.md +++ b/docs-translations/zh-CN/development/build-instructions-osx.md @@ -20,7 +20,7 @@ $ git clone https://github.com/atom/electron.git ## Bootstrapping -bootstrap 脚本也是必要下载的构建依赖,来创建项目文件.注意我们使用的是 `ninja` 来构建 Electron,所以没有生成 Xcode 项目. +bootstrap 脚本也是必要下载的构建依赖,来创建项目文件.注意我们使用的是 [ninja](https://ninja-build.org/) 来构建 Electron,所以没有生成 Xcode 项目. ```bash $ cd electron diff --git a/docs-translations/zh-CN/development/build-system-overview.md b/docs-translations/zh-CN/development/build-system-overview.md index 95aea7fb1f5..6bd1452b816 100644 --- a/docs-translations/zh-CN/development/build-system-overview.md +++ b/docs-translations/zh-CN/development/build-system-overview.md @@ -1,6 +1,6 @@ # Build System Overview -Electron 使用 `gyp` 来生成项目 ,使用 `ninja` 来构建项目. 项目配置可以在 `.gyp` 和 `.gypi` 文件中找到. +Electron 使用 [gyp](https://gyp.gsrc.io/) 来生成项目 ,使用 [ninja](https://ninja-build.org/) 来构建项目. 项目配置可以在 `.gyp` 和 `.gypi` 文件中找到. ## Gyp 文件 diff --git a/docs-translations/zh-CN/tutorial/debugging-main-process.md b/docs-translations/zh-CN/tutorial/debugging-main-process.md index e3eec0c5b39..361d7c2d57e 100644 --- a/docs-translations/zh-CN/tutorial/debugging-main-process.md +++ b/docs-translations/zh-CN/tutorial/debugging-main-process.md @@ -42,6 +42,8 @@ $ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-t $ node_modules/.bin/node-pre-gyp --target=0.36.2 --runtime=electron --fallback-to-build --directory node_modules/v8-profiler/ --dist-url=https://atom.io/download/atom-shell reinstall ``` +[How to install native modules][how-to-install-native-modules]. + ### 5. 打开 Electron 的调试模式 你也可以用调试参数来运行 Electron : From 8482109dea8f0c3f506e435d2e0e0269a16ff83c Mon Sep 17 00:00:00 2001 From: James Wheare Date: Wed, 23 Mar 2016 15:20:11 +0000 Subject: [PATCH 0266/1265] Switch to a single OS X swipe event with a direction argument --- atom/browser/api/atom_api_window.cc | 16 ++-------------- atom/browser/api/atom_api_window.h | 5 +---- atom/browser/native_window.cc | 19 ++----------------- atom/browser/native_window.h | 5 +---- atom/browser/native_window_mac.mm | 18 +++++++++--------- atom/browser/native_window_observer.h | 5 +---- docs/api/browser-window.md | 17 +++++------------ 7 files changed, 21 insertions(+), 64 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index c99f80876b8..9a57c98e626 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -243,20 +243,8 @@ void Window::OnWindowScrollTouchEnd() { Emit("scroll-touch-end"); } -void Window::OnWindowSwipeUp() { - Emit("swipe-up"); -} - -void Window::OnWindowSwipeRight() { - Emit("swipe-right"); -} - -void Window::OnWindowSwipeDown() { - Emit("swipe-down"); -} - -void Window::OnWindowSwipeLeft() { - Emit("swipe-left"); +void Window::OnWindowSwipe(const std::string& direction) { + Emit("swipe", direction); } void Window::OnWindowEnterHtmlFullScreen() { diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 33bf479b8f9..d26ff5b3674 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -69,10 +69,7 @@ class Window : public mate::TrackableObject, void OnWindowMoved() override; void OnWindowScrollTouchBegin() override; void OnWindowScrollTouchEnd() override; - void OnWindowSwipeUp() override; - void OnWindowSwipeRight() override; - void OnWindowSwipeDown() override; - void OnWindowSwipeLeft() override; + void OnWindowSwipe(const std::string& direction) override; void OnWindowEnterFullScreen() override; void OnWindowLeaveFullScreen() override; void OnWindowEnterHtmlFullScreen() override; diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index d95c2346642..2627c704d21 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -480,24 +480,9 @@ void NativeWindow::NotifyWindowScrollTouchEnd() { OnWindowScrollTouchEnd()); } -void NativeWindow::NotifyWindowSwipeUp() { +void NativeWindow::NotifyWindowSwipe(const std::string& direction) { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, - OnWindowSwipeUp()); -} - -void NativeWindow::NotifyWindowSwipeRight() { - FOR_EACH_OBSERVER(NativeWindowObserver, observers_, - OnWindowSwipeRight()); -} - -void NativeWindow::NotifyWindowSwipeDown() { - FOR_EACH_OBSERVER(NativeWindowObserver, observers_, - OnWindowSwipeDown()); -} - -void NativeWindow::NotifyWindowSwipeLeft() { - FOR_EACH_OBSERVER(NativeWindowObserver, observers_, - OnWindowSwipeLeft()); + OnWindowSwipe(direction)); } void NativeWindow::NotifyWindowLeaveFullScreen() { diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 27bb4fa5de8..49e1e71d5df 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -221,10 +221,7 @@ class NativeWindow : public base::SupportsUserData, void NotifyWindowMoved(); void NotifyWindowScrollTouchBegin(); void NotifyWindowScrollTouchEnd(); - void NotifyWindowSwipeUp(); - void NotifyWindowSwipeRight(); - void NotifyWindowSwipeDown(); - void NotifyWindowSwipeLeft(); + void NotifyWindowSwipe(const std::string& direction); void NotifyWindowEnterFullScreen(); void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index b0f2df4aaec..2044ee7d718 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -268,15 +268,15 @@ bool ScopedDisableResize::disable_resize_ = false; // NSWindow overrides. - (void)swipeWithEvent:(NSEvent *)event { - if (event.deltaY == 1.0) { - shell_->NotifyWindowSwipeUp(); - } else if (event.deltaX == -1.0) { - shell_->NotifyWindowSwipeRight(); - } else if (event.deltaY == -1.0) { - shell_->NotifyWindowSwipeDown(); - } else if (event.deltaX == 1.0) { - shell_->NotifyWindowSwipeLeft(); - } + if (event.deltaY == 1.0) { + shell_->NotifyWindowSwipe("up"); + } else if (event.deltaX == -1.0) { + shell_->NotifyWindowSwipe("right"); + } else if (event.deltaY == -1.0) { + shell_->NotifyWindowSwipe("down"); + } else if (event.deltaX == 1.0) { + shell_->NotifyWindowSwipe("left"); + } } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { diff --git a/atom/browser/native_window_observer.h b/atom/browser/native_window_observer.h index e88a77af41a..cfbae95bda1 100644 --- a/atom/browser/native_window_observer.h +++ b/atom/browser/native_window_observer.h @@ -58,10 +58,7 @@ class NativeWindowObserver { virtual void OnWindowMoved() {} virtual void OnWindowScrollTouchBegin() {} virtual void OnWindowScrollTouchEnd() {} - virtual void OnWindowSwipeUp() {} - virtual void OnWindowSwipeRight() {} - virtual void OnWindowSwipeDown() {} - virtual void OnWindowSwipeLeft() {} + virtual void OnWindowSwipe(const std::string& direction) {} virtual void OnWindowEnterFullScreen() {} virtual void OnWindowLeaveFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {} diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 3ccbb6fe9ad..76343f967b1 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -322,21 +322,14 @@ Emitted when scroll wheel event phase has begun. Emitted when scroll wheel event phase has ended. -### Event: 'swipe-up' _OS X_ +### Event: 'swipe' _OS X_ -Emitted on 3-finger swipe up. +Returns: -### Event: 'swipe-right' _OS X_ +* `event` Event +* `direction` String -Emitted on 3-finger swipe right. - -### Event: 'swipe-down' _OS X_ - -Emitted on 3-finger swipe down. - -### Event: 'swipe-left' _OS X_ - -Emitted on 3-finger swipe left. +Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. ## Methods From 5fccbfc7c6ab64447fc6bebedb93a4c34c32bda1 Mon Sep 17 00:00:00 2001 From: Robo Date: Thu, 24 Mar 2016 01:24:01 +0530 Subject: [PATCH 0267/1265] common: use v8::private symbols as identifiers for object properties --- atom/common/api/atom_api_v8_util.cc | 32 ++++++++++++++++++---- atom/renderer/atom_render_view_observer.cc | 6 +++- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/atom/common/api/atom_api_v8_util.cc b/atom/common/api/atom_api_v8_util.cc index f50d3485eba..0ebd939398f 100644 --- a/atom/common/api/atom_api_v8_util.cc +++ b/atom/common/api/atom_api_v8_util.cc @@ -11,20 +11,40 @@ namespace { -v8::Local GetHiddenValue(v8::Local object, +v8::Local GetHiddenValue(v8::Isolate* isolate, + v8::Local object, v8::Local key) { - return object->GetHiddenValue(key); + v8::Local context = isolate->GetCurrentContext(); + v8::Local privateKey = v8::Private::ForApi(isolate, key); + v8::Local value; + v8::Maybe result = object->HasPrivate(context, privateKey); + if (!(result.IsJust() && result.FromJust())) + return v8::Local(); + if (object->GetPrivate(context, privateKey).ToLocal(&value)) + return value; + return v8::Local(); } -void SetHiddenValue(v8::Local object, +void SetHiddenValue(v8::Isolate* isolate, + v8::Local object, v8::Local key, v8::Local value) { - object->SetHiddenValue(key, value); + if (value.IsEmpty()) + return; + v8::Local context = isolate->GetCurrentContext(); + v8::Local privateKey = v8::Private::ForApi(isolate, key); + object->SetPrivate(context, privateKey, value); } -void DeleteHiddenValue(v8::Local object, +void DeleteHiddenValue(v8::Isolate* isolate, + v8::Local object, v8::Local key) { - object->DeleteHiddenValue(key); + v8::Local context = isolate->GetCurrentContext(); + v8::Local privateKey = v8::Private::ForApi(isolate, key); + // Actually deleting the value would make force the object into + // dictionary mode which is unnecessarily slow. Instead, we replace + // the hidden value with "undefined". + object->SetPrivate(context, privateKey, v8::Undefined(isolate)); } int32_t GetObjectHash(v8::Local object) { diff --git a/atom/renderer/atom_render_view_observer.cc b/atom/renderer/atom_render_view_observer.cc index cdbdb3d7c3c..bbaea351378 100644 --- a/atom/renderer/atom_render_view_observer.cc +++ b/atom/renderer/atom_render_view_observer.cc @@ -39,7 +39,11 @@ bool GetIPCObject(v8::Isolate* isolate, v8::Local context, v8::Local* ipc) { v8::Local key = mate::StringToV8(isolate, "ipc"); - v8::Local value = context->Global()->GetHiddenValue(key); + v8::Local privateKey = v8::Private::ForApi(isolate, key); + v8::Local global_object = context->Global(); + v8::Local value; + if (!global_object->GetPrivate(context, privateKey).ToLocal(&value)) + return false; if (value.IsEmpty() || !value->IsObject()) return false; *ipc = value->ToObject(); From d2567b038101c4f5af96bf8d2fa21ea7647c1a5c Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Mon, 21 Mar 2016 11:24:25 -0700 Subject: [PATCH 0268/1265] :zap: Add API: SetASDefaultProtocolHandler This PR adds an API enabling Electron to set itself as the default protocol handler for a custom porotocl on both oS X and Windows. For details, please see `docs/app.md`. Closes #4857 --- atom/browser/api/atom_api_app.cc | 2 ++ atom/browser/browser.h | 3 ++ atom/browser/browser_linux.cc | 4 +++ atom/browser/browser_mac.mm | 16 ++++++++++ atom/browser/browser_win.cc | 54 ++++++++++++++++++++++++++++++++ docs/api/app.md | 20 ++++++++++++ 6 files changed, 99 insertions(+) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index d728d9dd546..00edcf70b23 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -370,6 +370,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( base::Bind(&Browser::ClearRecentDocuments, browser)) .SetMethod("setAppUserModelId", base::Bind(&Browser::SetAppUserModelID, browser)) + .SetMethod("setAsDefaultProtocolClient", + base::Bind(&Browser::SetAsDefaultProtocolClient, browser)) #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) diff --git a/atom/browser/browser.h b/atom/browser/browser.h index d976fae675c..38899c11eae 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -76,6 +76,9 @@ class Browser : public WindowListObserver { // Set the application user model ID. void SetAppUserModelID(const base::string16& name); + // Set as default handler for a protocol. + bool SetAsDefaultProtocolClient(const std::string& protocol); + #if defined(OS_MACOSX) // Hide the application. void Hide(); diff --git a/atom/browser/browser_linux.cc b/atom/browser/browser_linux.cc index 25cb9a0a238..586ec717a03 100644 --- a/atom/browser/browser_linux.cc +++ b/atom/browser/browser_linux.cc @@ -34,6 +34,10 @@ void Browser::ClearRecentDocuments() { void Browser::SetAppUserModelID(const base::string16& name) { } +bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { + return false; +} + std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 5988e662043..c61a9bddf92 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -8,6 +8,7 @@ #include "atom/browser/mac/atom_application_delegate.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" +#include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "brightray/common/application_info.h" @@ -45,6 +46,21 @@ void Browser::ClearRecentDocuments() { [[NSDocumentController sharedDocumentController] clearRecentDocuments:nil]; } +bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { + if (protocol.empty()) + return false; + + NSString* identifier = [base::mac::MainBundle() bundleIdentifier]; + if (!identifier) + return false; + + NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()]; + OSStatus return_code = + LSSetDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns), + base::mac::NSToCFCast(identifier)); + return return_code == noErr; +} + void Browser::SetAppUserModelID(const base::string16& name) { } diff --git a/atom/browser/browser_win.cc b/atom/browser/browser_win.cc index fdf4bd8c3bb..0b9fe545d5d 100644 --- a/atom/browser/browser_win.cc +++ b/atom/browser/browser_win.cc @@ -19,6 +19,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/win/win_util.h" +#include "base/win/registry.h" #include "base/win/windows_version.h" #include "atom/common/atom_version.h" @@ -125,6 +126,59 @@ void Browser::SetUserTasks(const std::vector& tasks) { destinations->CommitList(); } +bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { + // HKEY_CLASSES_ROOT + // $PROTOCOL + // (Default) = "URL:$NAME" + // URL Protocol = "" + // shell + // open + // command + // (Default) = "$COMMAND" "%1" + // + // However, the "HKEY_CLASSES_ROOT" key can only be written by the + // Administrator user. So, we instead write to "HKEY_CURRENT_USER\ + // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT" + // anyway, and can be written by unprivileged users. + + if (protocol.empty()) + return false; + + base::FilePath path; + if (!PathService::Get(base::FILE_EXE, &path)) { + LOG(ERROR) << "Error getting app exe path"; + return false; + } + + // Main Registry Key + HKEY root = HKEY_CURRENT_USER; + std::string keyPathStr = "Software\\Classes\\" + protocol; + std::wstring keyPath = std::wstring(keyPathStr.begin(), keyPathStr.end()); + std::string urlDeclStr = "URL:" + protocol; + std::wstring urlDecl = std::wstring(urlDeclStr.begin(), urlDeclStr.end()); + + // Command Key + std::string cmdPathStr = keyPathStr + "\\shell\\open\\command"; + std::wstring cmdPath = std::wstring(cmdPathStr.begin(), cmdPathStr.end()); + + // Executable Path + std::wstring exePath(path.value()); + std::wstring exe = L"\"" + exePath + L"\" \"%1\""; + + // Write information to registry + base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS); + if (FAILED(key.WriteValue(L"URL Protocol", L"")) || + FAILED(key.WriteValue(L"", urlDecl.c_str()))) + return false; + + base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS); + if (FAILED(commandKey.WriteValue(L"", exe.c_str()))) + return false; + + VLOG(1) << "Chrome registered as default handler for " << protocol << "."; + return true; +} + PCWSTR Browser::GetAppUserModelID() { if (app_user_model_id_.empty()) { SetAppUserModelID(base::ReplaceStringPlaceholders( diff --git a/docs/api/app.md b/docs/api/app.md index 8935ed894f0..e9bd1066a33 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -348,6 +348,25 @@ bar, and on OS X you can visit it from dock menu. Clears the recent documents list. +### `app.setAsDefaultProtocolClient(protocol)` _OS X_ _Windows_ + + * `protocol` String - The name of your protocol, without `://`. If you want your + app to handle `electron://` links, call this method with `electron` as the + parameter. + +This method sets the current executable as the default handler for a protocol +(aka URI scheme). It allows you to integrate your app deeper into the operating +system. Once registered, all links with `your-protocol://` will be openend with +the current executable. The whole link, including protocol, will be passed to +your application as a parameter. + +**Note:** On OS X, you can only register protocols that have been added to +your app's `info.plist`, which can not be modified at runtime. You can however +change the file with a simple text editor or script during build time. +Please refer to [Apple's documentation][CFBundleURLTypes] for details. + +The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally. + ### `app.setUserTasks(tasks)` _Windows_ * `tasks` Array - Array of `Task` objects @@ -541,3 +560,4 @@ Sets the `image` associated with this dock icon. [dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103 [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx +[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 \ No newline at end of file From f7a82987f43fcaf4ba01abb6c409646dfe69b7bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=A5=94=E5=A5=94?= Date: Thu, 24 Mar 2016 15:30:46 +0800 Subject: [PATCH 0269/1265] fix translation --- docs-translations/zh-CN/api/chrome-command-line-switches.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/zh-CN/api/chrome-command-line-switches.md b/docs-translations/zh-CN/api/chrome-command-line-switches.md index e197626302b..78b84b77276 100644 --- a/docs-translations/zh-CN/api/chrome-command-line-switches.md +++ b/docs-translations/zh-CN/api/chrome-command-line-switches.md @@ -22,7 +22,7 @@ app.on('ready', function() { ## --disable-http-cache -禁用 HTTP 请求. +禁止请求 HTTP 时使用磁盘缓存. ## --remote-debugging-port=`port` @@ -137,4 +137,4 @@ app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com [app]: app.md [append-switch]: app.md#appcommandlineappendswitchswitch-value [ready]: app.md#event-ready -[play-silent-audio]: https://github.com/atom/atom/pull/9485/files \ No newline at end of file +[play-silent-audio]: https://github.com/atom/atom/pull/9485/files From 8839cc51c247a3ec739e0f8975acbc1134e9aa0f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 14:47:31 -0700 Subject: [PATCH 0270/1265] Update source tree docs for new layout --- .../source-code-directory-structure.md | 55 ++++++++++--------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/docs/development/source-code-directory-structure.md b/docs/development/source-code-directory-structure.md index 146edae822d..998280a3705 100644 --- a/docs/development/source-code-directory-structure.md +++ b/docs/development/source-code-directory-structure.md @@ -11,35 +11,36 @@ to understand the source code better. ``` Electron -├──atom - Source code of Electron. -| ├── app - System entry code. -| ├── browser - The frontend including the main window, UI, and all of the -| | main process things. This talks to the renderer to manage web pages. -| |   ├── lib - Javascript part of the main process initialization code. -| | ├── ui - Implementation of UI stuff for different platforms. -| | | ├── cocoa - Cocoa specific source code. -| | | ├── gtk - GTK+ specific source code. -| | | └── win - Windows GUI specific source code. -| | ├── default_app - The default page to show when Electron is started -| | | without providing an app. -| | ├── api - The implementation of the main process APIs. -| | | └── lib - Javascript part of the API implementation. -| | ├── net - Network related code. -| | ├── mac - Mac specific Objective-C source code. -| | └── resources - Icons, platform-dependent files, etc. -| ├── renderer - Code that runs in renderer process. -| | ├── lib - Javascript part of renderer initialization code. -| | └── api - The implementation of renderer process APIs. -| | └── lib - Javascript part of the API implementation. -| └── common - Code that used by both the main and renderer processes, -| including some utility functions and code to integrate node's message -| loop into Chromium's message loop. -| ├── lib - Common Javascript initialization code. -| └── api - The implementation of common APIs, and foundations of -| Electron's built-in modules. -| └── lib - Javascript part of the API implementation. +├── atom - C++ source code. +| ├── app - System entry code. +| ├── browser - The frontend including the main window, UI, and all of the +| | main process things. This talks to the renderer to manage web pages. +| | ├── ui - Implementation of UI stuff for different platforms. +| | | ├── cocoa - Cocoa specific source code. +| | | ├── gtk - GTK+ specific source code. +| | | └── win - Windows GUI specific source code. +| | ├── api - The implementation of the main process APIs. +| | ├── net - Network related code. +| | ├── mac - Mac specific Objective-C source code. +| | └── resources - Icons, platform-dependent files, etc. +| ├── renderer - Code that runs in renderer process. +| | └── api - The implementation of renderer process APIs. +| └── common - Code that used by both the main and renderer processes, +| including some utility functions and code to integrate node's message +| loop into Chromium's message loop. +| └── api - The implementation of common APIs, and foundations of +| Electron's built-in modules. ├── chromium_src - Source code that copied from Chromium. +├── default_app - The default page to show when Electron is started without +| providing an app. ├── docs - Documentations. +├── lib - JavaScript source code. +| ├── browser - Javascript main process initialization code. +| | └── api - Javascript API implementation. +| ├── common - JavaScript used by both the main and renderer processes +| | └── api - Javascript API implementation. +| └── renderer - Javascript renderer process initialization code. +| └── api - Javascript API implementation. ├── spec - Automatic tests. ├── atom.gyp - Building rules of Electron. └── common.gypi - Compiler specific settings and building rules for other From 8feb0f044078f22222a849bb618ffb7e42971f9a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 15:15:46 -0700 Subject: [PATCH 0271/1265] Put link on same line as name --- docs/api/menu.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/api/menu.md b/docs/api/menu.md index 7487f6597a1..d7f32c787fd 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -387,5 +387,4 @@ Menu: ``` [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html -[setMenu]: -https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows +[setMenu]: https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows From 0066833887aba619fd2f91e6462a9b001c54fa47 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 22 Mar 2016 13:22:39 -0700 Subject: [PATCH 0272/1265] Add repl CLI option --- default_app/main.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/default_app/main.js b/default_app/main.js index 6ff26e9ea67..e0e41235eaa 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -6,6 +6,7 @@ const Menu = electron.Menu; const fs = require('fs'); const path = require('path'); +const repl = require('repl'); const url = require('url'); // Quit when all windows are closed and no other one is listening to this. @@ -27,6 +28,8 @@ for (var i = 0; i < argv.length; i++) { } else if (argv[i] == '--help' || argv[i] == '-h') { option.help = true; break; + } else if (argv[i] == '--interactive' || argv[i] == '-i') { + option.interactive = true; } else if (argv[i] == '--test-type=webdriver') { option.webdriver = true; } else if (argv[i] == '--require' || argv[i] == '-r') { @@ -307,6 +310,8 @@ if (option.file && !option.webdriver) { helpMessage += " -v, --version Print the version."; console.log(helpMessage); process.exit(0); +} else if (option.interactive) { + repl.start('> '); } else { loadApplicationByUrl('file://' + __dirname + '/index.html'); } From e49eae40473ddaa6531300590875d28d08006d21 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 22 Mar 2016 13:24:41 -0700 Subject: [PATCH 0273/1265] Document -i/--interactive option --- default_app/main.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/default_app/main.js b/default_app/main.js index e0e41235eaa..18e39544ab8 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -305,8 +305,9 @@ if (option.file && !option.webdriver) { helpMessage += " - .html/.htm file.\n"; helpMessage += " - http://, https://, or file:// URL.\n"; helpMessage += "\nOptions:\n"; - helpMessage += " -r, --require Module to preload (option can be repeated)\n"; helpMessage += " -h, --help Print this usage message.\n"; + helpMessage += " -i, --interactive Open a REPL to the main process.\n"; + helpMessage += " -r, --require Module to preload (option can be repeated)\n"; helpMessage += " -v, --version Print the version."; console.log(helpMessage); process.exit(0); From 8685f8e6c8f7f95b2833ee7643afa83d9050aadf Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 22 Mar 2016 13:26:05 -0700 Subject: [PATCH 0274/1265] Add repl run script --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 21ac10cff25..9f097c167df 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "build": "python ./script/build.py -c D", "lint": "python ./script/eslint.py && python ./script/cpplint.py", "preinstall": "node -e 'process.exit(0)'", + "repl": "python ./script/start.py --interactive", "start": "python ./script/start.py", "test": "python ./script/test.py" } From 832ac970885b2ea7bfacf621e1448d25c336b7bf Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 22 Mar 2016 13:34:46 -0700 Subject: [PATCH 0275/1265] Exit process when repl exits --- default_app/main.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/default_app/main.js b/default_app/main.js index 18e39544ab8..683dccaf3e1 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -278,6 +278,12 @@ function loadApplicationByUrl(appUrl) { require('./default_app').load(appUrl); } +function startRepl() { + repl.start('> ').on('exit', function() { + process.exit(0); + }); +} + // Start the specified app if there is one specified in command line, otherwise // start the default app. if (option.file && !option.webdriver) { @@ -312,7 +318,7 @@ if (option.file && !option.webdriver) { console.log(helpMessage); process.exit(0); } else if (option.interactive) { - repl.start('> '); + startRepl(); } else { loadApplicationByUrl('file://' + __dirname + '/index.html'); } From 09710d6c4766415d9030b1b2532f1de153a103e0 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 22 Mar 2016 13:37:57 -0700 Subject: [PATCH 0276/1265] Don't quit on window-all-closed when in repl mode --- default_app/main.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/default_app/main.js b/default_app/main.js index 683dccaf3e1..c46d1fc3bd6 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -9,12 +9,6 @@ const path = require('path'); const repl = require('repl'); const url = require('url'); -// Quit when all windows are closed and no other one is listening to this. -app.on('window-all-closed', function() { - if (app.listeners('window-all-closed').length == 1) - app.quit(); -}); - // Parse command line options. var argv = process.argv.slice(1); var option = { file: null, help: null, version: null, webdriver: null, modules: [] }; @@ -43,6 +37,12 @@ for (var i = 0; i < argv.length; i++) { } } +// Quit when all windows are closed and no other one is listening to this. +app.on('window-all-closed', function() { + if (app.listeners('window-all-closed').length == 1 && !option.interactive) + app.quit(); +}); + // Create default menu. app.once('ready', function() { if (Menu.getApplicationMenu()) From a3f30ca8227f63da8ad527c6a224c2bc83937329 Mon Sep 17 00:00:00 2001 From: Pier Bover Date: Fri, 25 Mar 2016 16:26:14 -0600 Subject: [PATCH 0277/1265] Update desktop-environment-integration.md --- docs/tutorial/desktop-environment-integration.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index c35eea944be..53fdf606d49 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -15,6 +15,8 @@ to the user. Electron conveniently allows developers to send notifications with the [HTML5 Notification API](https://notifications.spec.whatwg.org/), using the currently running operating system's native notification APIs to display it. +Note: since this is an HTML5 API it is only avaialable in the renderer process. + ```javascript var myNotification = new Notification('Title', { body: 'Lorem Ipsum Dolor Sit Amet' From c4128e6b4b64a8abadf2631c8eb141879ef91998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20Ram=C3=ADrez=20Norambuena?= Date: Fri, 25 Mar 2016 23:47:47 -0300 Subject: [PATCH 0278/1265] add curl package into Ubuntu section missing for the build --- docs/development/build-instructions-linux.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 9ddeed9809b..df0943050f7 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -19,7 +19,7 @@ On Ubuntu, install the following libraries: $ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \ libnotify-dev libgnome-keyring-dev libgconf2-dev \ libasound2-dev libcap-dev libcups2-dev libxtst-dev \ - libxss1 libnss3-dev gcc-multilib g++-multilib + libxss1 libnss3-dev gcc-multilib g++-multilib curl ``` On Fedora, install the following libraries: From 75f09420577fde62a5c28a5d8fc6c2419c709f9f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 12:16:12 +0900 Subject: [PATCH 0279/1265] Bump v0.37.3 --- atom.gyp | 2 +- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom.gyp b/atom.gyp index df7ec4ed329..bfcfb39bab1 100644 --- a/atom.gyp +++ b/atom.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.2', + 'version%': '0.37.3', }, 'includes': [ 'filenames.gypi', diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 06405d836b4..f7bd068e8f4 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile atom.icns CFBundleVersion - 0.37.2 + 0.37.3 CFBundleShortVersionString - 0.37.2 + 0.37.3 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index be2e5666bbf..15252346669 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,2,0 - PRODUCTVERSION 0,37,2,0 + FILEVERSION 0,37,3,0 + PRODUCTVERSION 0,37,3,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.2" + VALUE "FileVersion", "0.37.3" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.2" + VALUE "ProductVersion", "0.37.3" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 8821ec4e159..cb470529340 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 2 +#define ATOM_PATCH_VERSION 3 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/package.json b/package.json index 9f097c167df..ce7c44145d3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.2", + "version": "0.37.3", "devDependencies": { "asar": "^0.10.0", "eslint": "^2.1.0", From 2ffe891cc8172ccf2fc205863fe610430b89f61a Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 27 Mar 2016 18:07:58 +0900 Subject: [PATCH 0280/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/menu.md | 2 +- .../source-code-directory-structure.md | 53 ++++++++++--------- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index c64aa8c4fab..44fe461bcc2 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -382,4 +382,4 @@ OS X에선 지정한 어플리케이션 메뉴에 상관없이 메뉴의 첫번 ``` [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html -[setMenu]: https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows +[setMenu]: https://github.com/atom/electron/blob/master/docs-translations/ko-KR/api/browser-window.md#winsetmenumenu-linux-windows diff --git a/docs-translations/ko-KR/development/source-code-directory-structure.md b/docs-translations/ko-KR/development/source-code-directory-structure.md index e0e172d18b4..7450b3b3e9e 100644 --- a/docs-translations/ko-KR/development/source-code-directory-structure.md +++ b/docs-translations/ko-KR/development/source-code-directory-structure.md @@ -10,33 +10,34 @@ Electron의 소스 코드는 몇 개의 파트로 분리되어 있습니다. 그 ``` Electron -├──atom - Electron의 소스코드. -| ├── app - 시스템 엔트리 코드. -| ├── browser - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 것과 -| | 랜더러와 웹 페이지 관리 관련 코드. -| | ├── lib - 메인 프로세스 초기화 코드의 자바스크립트 파트. -| | ├── ui - 크로스 플랫폼에 대응하는 UI 구현. -| | | ├── cocoa - 코코아 특정 소스 코드. -| | | ├── gtk - GTK+ 특정 소스 코드. -| | | └── win - Windows GUI 특정 소스 코드. -| | ├── default_app - 어플리케이션이 제공되지 않으면 기본으로 사용되는 페이지. -| | ├── api - 메인 프로세스 API의 구현. -| | | └── lib - API 구현의 자바스크립트 파트. -| | ├── net - 네트워크 관련 코드. -| | ├── mac - Mac 특정 Objective-C 소스 코드. -| | └── resources - 아이콘들, 플랫폼 종속성 파일들, 기타 등등. -| ├── renderer - 랜더러 프로세스에서 작동하는 코드들. -| | ├── lib - 랜더러 프로세스 초기화 코드의 자바스크립트 파트. -| | └── api - 랜더러 프로세스 API들의 구현. -| | └── lib - API 구현의 자바스크립트 파트. -| └── common - 메인 프로세스와 랜더러 프로세스에서 공유하는 코드. 유틸리티 함수와 -| node 메시지 루프를 Chromium의 메시지 루프에 통합시킨 코드도 포함. -| ├── lib - 공통 자바스크립트 초기화 코드. -| └── api - 공통 API들의 구현, Electron의 빌트인 모듈 기초 코드들. -| └── lib - API 구현의 자바스크립트 파트. -├── chromium_src - 복사된 Chromium 소스 코드. +├── atom - C++ 소스 코드. +| ├── app - 시스템 엔트리 코드. +| ├── browser - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 +| | 코드와 랜더러 및 웹 페이지 관리 관련 코드. +| | ├── ui - 서로 다른 플랫폼에 대한 UI 관련 구현 코드. +| | | ├── cocoa - Cocoa 특정 소스 코드. +| | | ├── gtk - GTK+ 특정 소스 코드. +| | | └── win - Windows GUI 특정 소스 코드. +| | ├── api - 메인 프로세스 API의 구현. +| | ├── net - 네트워킹 관련 코드. +| | ├── mac - Mac 특정 Objective-C 소스 코드. +| | └── resources - 아이콘들, 플랫폼 종속성 파일들, 기타 등등.. +| ├── renderer - 랜더러 프로세스에서 작동하는 코드. +| | └── api - 랜더러 프로세스 API의 구현. +| └── common - 메인과 랜더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 +| 함수들이 포함되어 있고 node의 메시지 루프와 Chromium의 메시지 루프를 통합. +| └── api - 공통 API 구현들, 기초 Electron 빌트-인 모듈들. +├── chromium_src - Chromium에서 복사하여 가져온 소스코드. +├── default_app - Electron에 앱이 제공되지 않았을 때 보여지는 기본 페이지. ├── docs - 참조 문서. -├── spec - 자동화된 테스트. +├── lib - JavaScript 소스 코드. +| ├── browser - Javascript 메인 프로세스 초기화 코드. +| | └── api - Javascript API 구현 코드. +| ├── common - 메인과 랜더러 프로세스에서 모두 사용하는 JavaScript +| | └── api - Javascript API 구현 코드. +| └── renderer - Javascript 랜더러 프로세스 초기화 코드. +| └── api - Javascript API 구현 코드. +├── spec - 자동화 테스트. ├── atom.gyp - Electron의 빌드 규칙. └── common.gypi - 컴파일러 설정 및 `node` 와 `breakpad` 등의 구성요소를 위한 빌드 규칙. From f23729acdb83f16fb6b7ca6b73d1d514124ebba9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 14:47:01 +0900 Subject: [PATCH 0281/1265] Upgrade to node v5.9.1 --- vendor/node | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/node b/vendor/node index a507a3c3816..12524cebe23 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit a507a3c3816d6ac085ed46250c489a3d76ab8b3c +Subproject commit 12524cebe23226df1f621ffc12e44a62582ae352 From d83cb53997e8e3a4fdf856df770a2c2e8fd296b7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 14:54:26 +0900 Subject: [PATCH 0282/1265] Type of native array has changed --- atom/common/api/atom_api_asar.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/atom/common/api/atom_api_asar.cc b/atom/common/api/atom_api_asar.cc index 8f5190fecaa..4bfb0ed4c1b 100644 --- a/atom/common/api/atom_api_asar.cc +++ b/atom/common/api/atom_api_asar.cc @@ -129,9 +129,11 @@ void InitAsarSupport(v8::Isolate* isolate, v8::Local process, v8::Local require) { // Evaluate asar_init.coffee. + const char* asar_init_native = reinterpret_cast( + static_cast(node::asar_init_native)); v8::Local asar_init = v8::Script::Compile(v8::String::NewFromUtf8( isolate, - node::asar_init_native, + asar_init_native, v8::String::kNormalString, sizeof(node::asar_init_native) -1)); v8::Local result = asar_init->Run(); @@ -141,9 +143,11 @@ void InitAsarSupport(v8::Isolate* isolate, v8::Local, std::string)> init; if (mate::ConvertFromV8(isolate, result, &init)) { + const char* asar_native = reinterpret_cast( + static_cast(node::asar_native)); init.Run(process, require, - std::string(node::asar_native, sizeof(node::asar_native) - 1)); + std::string(asar_native, sizeof(node::asar_native) - 1)); } } From 70f9cb098ff24cd6a06b65843471a0231a66206c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 15:03:53 +0900 Subject: [PATCH 0283/1265] Use Environment::KickNextTick --- atom/common/api/atom_bindings.cc | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/atom/common/api/atom_bindings.cc b/atom/common/api/atom_bindings.cc index a000f6fc743..fe53d8793f2 100644 --- a/atom/common/api/atom_bindings.cc +++ b/atom/common/api/atom_bindings.cc @@ -98,24 +98,8 @@ void AtomBindings::OnCallNextTick(uv_async_t* handle) { self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; - node::Environment::TickInfo* tick_info = env->tick_info(); - - v8::Context::Scope context_scope(env->context()); - if (tick_info->in_tick()) - continue; - - if (tick_info->length() == 0) { - env->isolate()->RunMicrotasks(); - } - - if (tick_info->length() == 0) { - tick_info->set_index(0); - continue; - } - - tick_info->set_in_tick(true); - env->tick_callback_function()->Call(env->process_object(), 0, NULL); - tick_info->set_in_tick(false); + node::Environment::AsyncCallbackScope callback_scope(env); + env->KickNextTick(&callback_scope); } self->pending_next_ticks_.clear(); From 896ea7b79dab9e698b8fc916f8f51e79b5e0e6d5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 18:09:21 +0900 Subject: [PATCH 0284/1265] Do not create dummy node environment There is a bug in V8 that using Private in a dummy environment would result in crash. --- atom/renderer/atom_renderer_client.cc | 30 +++++++++++++-------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index 50ff109a2fc..99696cc8282 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -90,18 +90,6 @@ void AtomRendererClient::WebKitInitialized() { blink::WebCustomElement::addEmbedderCustomElementName("browserplugin"); OverrideNodeArrayBuffer(); - - node_bindings_->Initialize(); - node_bindings_->PrepareMessageLoop(); - - DCHECK(!global_env); - - // Create a default empty environment which would be used when we need to - // run V8 code out of a window context (like running a uv callback). - v8::Isolate* isolate = blink::mainThreadIsolate(); - v8::HandleScope handle_scope(isolate); - v8::Local context = v8::Context::New(isolate); - global_env = node::Environment::New(context, uv_default_loop()); } void AtomRendererClient::RenderThreadStarted() { @@ -160,8 +148,14 @@ bool AtomRendererClient::OverrideCreatePlugin( void AtomRendererClient::DidCreateScriptContext( v8::Handle context) { - // Give the node loop a run to make sure everything is ready. - node_bindings_->RunMessageLoop(); + // Whether the node binding has been initialized. + bool first_time = node_bindings_->uv_env() == nullptr; + + // Prepare the node bindings. + if (first_time) { + node_bindings_->Initialize(); + node_bindings_->PrepareMessageLoop(); + } // Setup node environment for each window. node::Environment* env = node_bindings_->CreateEnvironment(context); @@ -169,10 +163,14 @@ void AtomRendererClient::DidCreateScriptContext( // Add atom-shell extended APIs. atom_bindings_->BindTo(env->isolate(), env->process_object()); - // Make uv loop being wrapped by window context. - if (node_bindings_->uv_env() == nullptr) + if (first_time) { + // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); + // Give the node loop a run to make sure everything is ready. + node_bindings_->RunMessageLoop(); + } + // Load everything. node_bindings_->LoadEnvironment(env); } From e5886dda9b3ae8a857a069a9c65737f8e66f2c5c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 19:13:15 +0900 Subject: [PATCH 0285/1265] Avoid re-evaluating internal modules --- lib/common/asar_init.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/common/asar_init.js b/lib/common/asar_init.js index 49b57907c8f..85bb828583b 100644 --- a/lib/common/asar_init.js +++ b/lib/common/asar_init.js @@ -9,6 +9,12 @@ // Make graceful-fs work with asar. var source = process.binding('natives'); source['original-fs'] = source.fs; - return source['fs'] = "var src = '(function (exports, require, module, __filename, __dirname) { ' +\n process.binding('natives')['original-fs'] +\n ' });';\nvar vm = require('vm');\nvar fn = vm.runInThisContext(src, { filename: 'fs.js' });\nfn(exports, require, module);\nvar asar = require('ATOM_SHELL_ASAR');\nasar.wrapFsWithAsar(exports);"; + return source['fs'] = ` +var nativeModule = new process.NativeModule('original-fs'); +nativeModule.cache(); +nativeModule.compile(); +var asar = require('ATOM_SHELL_ASAR'); +asar.wrapFsWithAsar(nativeModule.exports); +module.exports = nativeModule.exports`; }; })(); From e401335ebb2fed1bd224a4be8f305e593f8a2c8c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 19:21:12 +0900 Subject: [PATCH 0286/1265] Get rid of the global_env --- atom/browser/atom_browser_main_parts.cc | 12 ++++++++---- atom/common/node_bindings.cc | 8 ++------ atom/common/node_includes.h | 7 ------- atom/renderer/atom_renderer_client.cc | 6 +++--- 4 files changed, 13 insertions(+), 20 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index a711c1c8d2b..f45f6492a84 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -106,17 +106,21 @@ void AtomBrowserMainParts::PostEarlyInitialization() { node_debugger_.reset(new NodeDebugger(js_env_->isolate())); // Create the global environment. - global_env = node_bindings_->CreateEnvironment(js_env_->context()); + node::Environment* env = + node_bindings_->CreateEnvironment(js_env_->context()); // Make sure node can get correct environment when debugging. if (node_debugger_->IsRunning()) - global_env->AssignToContext(v8::Debug::GetDebugContext()); + env->AssignToContext(v8::Debug::GetDebugContext()); // Add atom-shell extended APIs. - atom_bindings_->BindTo(js_env_->isolate(), global_env->process_object()); + atom_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. - node_bindings_->LoadEnvironment(global_env); + node_bindings_->LoadEnvironment(env); + + // Wrap the uv loop with global env. + node_bindings_->set_uv_env(env); } void AtomBrowserMainParts::PreMainMessageLoopRun() { diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index 950a2cd786a..b0b4148c7ba 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -106,8 +106,6 @@ base::FilePath GetResourcesPath(bool is_browser) { } // namespace -node::Environment* global_env = nullptr; - NodeBindings::NodeBindings(bool is_browser) : is_browser_(is_browser), message_loop_(nullptr), @@ -214,10 +212,8 @@ void NodeBindings::RunMessageLoop() { void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); - // By default the global env would be used unless user specified another one - // (this happens for renderer process, which wraps the uv loop with web page - // context). - node::Environment* env = uv_env() ? uv_env() : global_env; + node::Environment* env = uv_env(); + CHECK(env); // Use Locker in browser process. mate::Locker locker(env->isolate()); diff --git a/atom/common/node_includes.h b/atom/common/node_includes.h index 3876d862291..bb76afb54db 100644 --- a/atom/common/node_includes.h +++ b/atom/common/node_includes.h @@ -28,11 +28,4 @@ #include "vendor/node/src/node_buffer.h" #include "vendor/node/src/node_internals.h" -namespace atom { -// Defined in node_bindings.cc. -// For renderer it's created in atom_renderer_client.cc. -// For browser it's created in atom_browser_main_parts.cc. -extern node::Environment* global_env; -} - #endif // ATOM_COMMON_NODE_INCLUDES_H_ diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index 99696cc8282..7746ce123e4 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -163,6 +163,9 @@ void AtomRendererClient::DidCreateScriptContext( // Add atom-shell extended APIs. atom_bindings_->BindTo(env->isolate(), env->process_object()); + // Load everything. + node_bindings_->LoadEnvironment(env); + if (first_time) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); @@ -170,9 +173,6 @@ void AtomRendererClient::DidCreateScriptContext( // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } - - // Load everything. - node_bindings_->LoadEnvironment(env); } void AtomRendererClient::WillReleaseScriptContext( From a4d2dd9b4d65f923f508f5b1509b3da40dad47c0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 27 Mar 2016 19:50:34 +0900 Subject: [PATCH 0287/1265] Export symbols of node::Environment --- common.gypi | 1 + vendor/node | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/common.gypi b/common.gypi index 6eacdc93a02..a9f067bcc54 100644 --- a/common.gypi +++ b/common.gypi @@ -230,6 +230,7 @@ 'msvs_cygwin_shell': 0, # Strangely setting it to 1 would make building under cygwin fail. 'msvs_disabled_warnings': [ 4005, # (node.h) macro redefinition + 4091, # (node_extern.h) '__declspec(dllimport)' : ignored on left of 'node::Environment' when no variable is declared 4189, # local variable is initialized but not referenced 4201, # (uv.h) nameless struct/union 4267, # conversion from 'size_t' to 'int', possible loss of data diff --git a/vendor/node b/vendor/node index 12524cebe23..d8e7d3e76cb 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit 12524cebe23226df1f621ffc12e44a62582ae352 +Subproject commit d8e7d3e76cb3c6e709449d181ddc2af8c4859303 From 73201e419d9985fb8a4de55d4d33cc922030af84 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 28 Mar 2016 02:09:56 +0530 Subject: [PATCH 0288/1265] protocol: return status of ReadRawData instead of relying on SetStatus --- atom/browser/net/url_request_fetch_job.cc | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index d58ea3fe9fb..2f907314cad 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -167,8 +167,6 @@ void URLRequestFetchJob::HeadersCompleted() { } int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) { - // Clear the IO_PENDING status. - SetStatus(net::URLRequestStatus()); // Do nothing if pending_buffer_ is empty, i.e. there's no ReadRawData() // operation waiting for IO completion. if (!pending_buffer_.get()) @@ -176,7 +174,6 @@ int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) { // pending_buffer_ is set to the IOBuffer instance provided to ReadRawData() // by URLRequestJob. - int bytes_read = std::min(num_bytes, pending_buffer_size_); memcpy(pending_buffer_->data(), buffer->data(), bytes_read); @@ -197,12 +194,11 @@ void URLRequestFetchJob::Kill() { int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); - return 0; + return net::OK; } pending_buffer_ = dest; pending_buffer_size_ = dest_size; - SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); - return dest_size; + return net::ERR_IO_PENDING; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { From ab685ac335a834759239eb2cd245d93ab33ddfcf Mon Sep 17 00:00:00 2001 From: Alejandro Gonzalez Sole Date: Sat, 26 Mar 2016 22:07:24 -0400 Subject: [PATCH 0289/1265] Update power-monitor.md Updated docs in power-monitor to reflect windows only events --- docs/api/power-monitor.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/power-monitor.md b/docs/api/power-monitor.md index 5313aad9c97..49929a78c90 100644 --- a/docs/api/power-monitor.md +++ b/docs/api/power-monitor.md @@ -26,10 +26,10 @@ Emitted when the system is suspending. Emitted when system is resuming. -### Event: 'on-ac' +### Event: 'on-ac' *Windows* Emitted when the system changes to AC power. -### Event: 'on-battery' +### Event: 'on-battery' *Windows* Emitted when system changes to battery power. From 116aa2f48330417c1e0adaef6188c950e849df2c Mon Sep 17 00:00:00 2001 From: Pier Bover Date: Mon, 28 Mar 2016 11:41:16 -0600 Subject: [PATCH 0290/1265] Update desktop-environment-integration.md --- docs/tutorial/desktop-environment-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index 53fdf606d49..bd4839cd6b1 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -15,7 +15,7 @@ to the user. Electron conveniently allows developers to send notifications with the [HTML5 Notification API](https://notifications.spec.whatwg.org/), using the currently running operating system's native notification APIs to display it. -Note: since this is an HTML5 API it is only avaialable in the renderer process. +Note: since this is an HTML5 API it is only available in the renderer process. ```javascript var myNotification = new Notification('Title', { From 1231360b2ff2ae94068c897ad856d1d7b8b6df9f Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Thu, 24 Mar 2016 10:55:09 -0700 Subject: [PATCH 0291/1265] :zap: Add API: RemoveAsDefaultProtocolHandler --- atom/browser/api/atom_api_app.cc | 2 ++ atom/browser/browser.h | 3 ++ atom/browser/browser_linux.cc | 4 +++ atom/browser/browser_mac.mm | 4 +++ atom/browser/browser_win.cc | 48 +++++++++++++++++++++++++++++++- docs/api/app.md | 10 +++++++ 6 files changed, 70 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 00edcf70b23..ad5b7214ccd 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -372,6 +372,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( base::Bind(&Browser::SetAppUserModelID, browser)) .SetMethod("setAsDefaultProtocolClient", base::Bind(&Browser::SetAsDefaultProtocolClient, browser)) + .SetMethod("removeAsDefaultProtocolClient", + base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser)) #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 38899c11eae..634e14e6026 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -76,6 +76,9 @@ class Browser : public WindowListObserver { // Set the application user model ID. void SetAppUserModelID(const base::string16& name); + // Remove the default protocol handler registry key + bool RemoveAsDefaultProtocolClient(const std::string& protocol); + // Set as default handler for a protocol. bool SetAsDefaultProtocolClient(const std::string& protocol); diff --git a/atom/browser/browser_linux.cc b/atom/browser/browser_linux.cc index 586ec717a03..6c7d4abaf64 100644 --- a/atom/browser/browser_linux.cc +++ b/atom/browser/browser_linux.cc @@ -34,6 +34,10 @@ void Browser::ClearRecentDocuments() { void Browser::SetAppUserModelID(const base::string16& name) { } +bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { + return false; +} + bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return false; } diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index c61a9bddf92..0294894fcd6 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -46,6 +46,10 @@ void Browser::ClearRecentDocuments() { [[NSDocumentController sharedDocumentController] clearRecentDocuments:nil]; } +bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { + return false; +} + bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { if (protocol.empty()) return false; diff --git a/atom/browser/browser_win.cc b/atom/browser/browser_win.cc index 0b9fe545d5d..9531406f8cd 100644 --- a/atom/browser/browser_win.cc +++ b/atom/browser/browser_win.cc @@ -126,6 +126,53 @@ void Browser::SetUserTasks(const std::vector& tasks) { destinations->CommitList(); } +bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { + if (protocol.empty()) + return false; + + base::FilePath path; + if (!PathService::Get(base::FILE_EXE, &path)) { + LOG(ERROR) << "Error getting app exe path"; + return false; + } + + // Main Registry Key + HKEY root = HKEY_CURRENT_USER; + std::string keyPathStr = "Software\\Classes\\" + protocol; + std::wstring keyPath = std::wstring(keyPathStr.begin(), keyPathStr.end()); + + // Command Key + std::string cmdPathStr = keyPathStr + "\\shell\\open\\command"; + std::wstring cmdPath = std::wstring(cmdPathStr.begin(), cmdPathStr.end()); + + base::win::RegKey key; + base::win::RegKey commandKey; + if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) + // Key doesn't even exist, we can confirm that it is not set + return true; + + if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) + // Key doesn't even exist, we can confirm that it is not set + return true; + + std::wstring keyVal; + if (FAILED(commandKey.ReadValue(L"", &keyVal))) + // Default value not set, we can confirm that it is not set + return true; + + std::wstring exePath(path.value()); + std::wstring exe = L"\"" + exePath + L"\" \"%1\""; + if (keyVal == exe) { + // Let's kill the key + if (FAILED(key.DeleteKey(L"shell"))) + return false; + + return true; + } else { + return true; + } +} + bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { // HKEY_CLASSES_ROOT // $PROTOCOL @@ -175,7 +222,6 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { if (FAILED(commandKey.WriteValue(L"", exe.c_str()))) return false; - VLOG(1) << "Chrome registered as default handler for " << protocol << "."; return true; } diff --git a/docs/api/app.md b/docs/api/app.md index e9bd1066a33..94fb28304dd 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -367,6 +367,16 @@ Please refer to [Apple's documentation][CFBundleURLTypes] for details. The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally. +### `app.removeAsDefaultProtocolClient(protocol)` _Windows_ + + * `protocol` String - The name of your protocol, without `://`. + +This method checks if the current executable as the default handler for a protocol +(aka URI scheme). If so, it will remove the app as the default handler. + +**Note:** On OS X, removing the app will automatically remove the app as the +default protocol handler. + ### `app.setUserTasks(tasks)` _Windows_ * `tasks` Array - Array of `Task` objects From ff2d0050587c3fb0a81f8b48aebca00725080988 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Tue, 29 Mar 2016 10:47:31 -0700 Subject: [PATCH 0292/1265] Add "black background?" to FAQ Closes #4937 --- docs/faq/electron-faq.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index 41b301d7198..77d1fca66e9 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -144,6 +144,17 @@ is very likely you are using the module in the wrong process. For example `electron.app` can only be used in the main process, while `electron.webFrame` is only available in renderer processes. +## Why is my app's background transparent? +Since Electron `0.37.3`, the default user-agent background color is `transparent`. Simply specify a background color in HTML; + +```html + +``` + [memory-management]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management [variable-scope]: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx [electron-module]: https://www.npmjs.com/package/electron From edbb2b4a26f25ad50c428700ac7dbf7eac01bf11 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 30 Mar 2016 10:42:59 +0900 Subject: [PATCH 0293/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/power-monitor.md | 4 ++-- .../ko-KR/development/build-instructions-linux.md | 2 +- docs-translations/ko-KR/faq/electron-faq.md | 13 +++++++++++++ .../tutorial/desktop-environment-integration.md | 2 ++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/docs-translations/ko-KR/api/power-monitor.md b/docs-translations/ko-KR/api/power-monitor.md index 29a3aabc84a..63d5959fe20 100644 --- a/docs-translations/ko-KR/api/power-monitor.md +++ b/docs-translations/ko-KR/api/power-monitor.md @@ -29,10 +29,10 @@ app.on('ready', function() { 시스템의 절전모드가 해제될 때 발생하는 이벤트입니다. -## Event: `on-ac` +## Event: `on-ac` _Windows_ 시스템이 AC 어뎁터 충전기를 사용하기 시작할 때 발생하는 이벤트입니다. -## Event: `on-battery` +## Event: `on-battery` _Windows_ 시스템이 배터리를 사용하기 시작할 때 발생하는 이벤트입니다. diff --git a/docs-translations/ko-KR/development/build-instructions-linux.md b/docs-translations/ko-KR/development/build-instructions-linux.md index c4f161fa56a..377a7977a85 100644 --- a/docs-translations/ko-KR/development/build-instructions-linux.md +++ b/docs-translations/ko-KR/development/build-instructions-linux.md @@ -21,7 +21,7 @@ Ubuntu를 사용하고 있다면 다음과 같이 라이브러리를 설치해 $ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \ libnotify-dev libgnome-keyring-dev libgconf2-dev \ libasound2-dev libcap-dev libcups2-dev libxtst-dev \ - libxss1 libnss3-dev gcc-multilib g++-multilib + libxss1 libnss3-dev gcc-multilib g++-multilib curl ``` Fedora를 사용하고 있다면 다음과 같이 라이브러리를 설치해야 합니다: diff --git a/docs-translations/ko-KR/faq/electron-faq.md b/docs-translations/ko-KR/faq/electron-faq.md index ea9953fcd4c..40d10f293f4 100644 --- a/docs-translations/ko-KR/faq/electron-faq.md +++ b/docs-translations/ko-KR/faq/electron-faq.md @@ -144,6 +144,19 @@ npm uninstall -g electron 모듈이며, 반면 `electron.webFrame` 모듈은 랜더러 프로세스에서만 사용할 수 있는 모듈입니다. +## 왜 저의 앱 배경이 투명하죠? + +Electron `0.37.3` 부터, 기본 클라이언트 배경색이 `투명색`으로 변경되었습니다. +간단히 HTML에서 배경색을 지정합니다: + +```html + +``` + [memory-management]: https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management [variable-scope]: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx [electron-module]: https://www.npmjs.com/package/electron diff --git a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md index c72af78a278..ddeadc04e91 100644 --- a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md +++ b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md @@ -14,6 +14,8 @@ Windows, Linux, OS X 운영체제 모두 기본적으로 어플리케이션에 통해 개발자가 편리하게 데스크톱 알림을 사용할 수 있는 기능을 제공합니다. 데스크톱 알림은 운영체제의 네이티브 알림 API를 사용하여 표시합니다. +__참고:__ 이 API는 HTML5 API이기 때문에 랜더러 프로세스에서만 사용할 수 있습니다. + ```javascript var myNotification = new Notification('Title', { body: 'Lorem Ipsum Dolor Sit Amet' From c4a2329665e52e27480d309d74cafb425a4988d8 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 30 Mar 2016 10:55:50 +0900 Subject: [PATCH 0294/1265] :memo: Update docs styles * Adjust line length to `80` * Change platform marker `*` to `_` * Enhance a note section [ci skip] --- docs/api/power-monitor.md | 4 ++-- docs/faq/electron-faq.md | 4 +++- docs/tutorial/desktop-environment-integration.md | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/api/power-monitor.md b/docs/api/power-monitor.md index 49929a78c90..4465b253a75 100644 --- a/docs/api/power-monitor.md +++ b/docs/api/power-monitor.md @@ -26,10 +26,10 @@ Emitted when the system is suspending. Emitted when system is resuming. -### Event: 'on-ac' *Windows* +### Event: 'on-ac' _Windows_ Emitted when the system changes to AC power. -### Event: 'on-battery' *Windows* +### Event: 'on-battery' _Windows_ Emitted when system changes to battery power. diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index 77d1fca66e9..1782d387310 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -145,7 +145,9 @@ is very likely you are using the module in the wrong process. For example is only available in renderer processes. ## Why is my app's background transparent? -Since Electron `0.37.3`, the default user-agent background color is `transparent`. Simply specify a background color in HTML; + +Since Electron `0.37.3`, the default user-agent background color is `transparent`. +Simply specify a background color in HTML: ```html '; - this.setupWebViewAttributes(); - this.setupFocusPropagation(); - this.viewInstanceId = getNextId(); - shadowRoot.appendChild(this.browserPluginNode); + this.on = {} + this.browserPluginNode = this.createBrowserPluginNode() + shadowRoot = this.webviewNode.createShadowRoot() + shadowRoot.innerHTML = '' + this.setupWebViewAttributes() + this.setupFocusPropagation() + this.viewInstanceId = getNextId() + shadowRoot.appendChild(this.browserPluginNode) // Subscribe to host's zoom level changes. this.onZoomLevelChanged = (zoomLevel) => { - this.webviewNode.setZoomLevel(zoomLevel); - }; - webFrame.on('zoom-level-changed', this.onZoomLevelChanged); + this.webviewNode.setZoomLevel(zoomLevel) + } + webFrame.on('zoom-level-changed', this.onZoomLevelChanged) } - WebViewImpl.prototype.createBrowserPluginNode = function() { + WebViewImpl.prototype.createBrowserPluginNode = function () { // We create BrowserPlugin as a custom element in order to observe changes // to attributes synchronously. - var browserPluginNode; - browserPluginNode = new WebViewImpl.BrowserPlugin(); - v8Util.setHiddenValue(browserPluginNode, 'internal', this); - return browserPluginNode; - }; + var browserPluginNode + browserPluginNode = new WebViewImpl.BrowserPlugin() + v8Util.setHiddenValue(browserPluginNode, 'internal', this) + return browserPluginNode + } // Resets some state upon reattaching element to the DOM. - WebViewImpl.prototype.reset = function() { + WebViewImpl.prototype.reset = function () { // Unlisten the zoom-level-changed event. - webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged); + webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged) // If guestInstanceId is defined then the has navigated and has // already picked up a partition ID. Thus, we need to reset the initialization @@ -66,174 +66,172 @@ var WebViewImpl = (function() { // heard back from createGuest yet. We will not reset the flag in this case so // that we don't end up allocating a second guest. if (this.guestInstanceId) { - guestViewInternal.destroyGuest(this.guestInstanceId); - this.webContents = null; - this.guestInstanceId = void 0; - this.beforeFirstNavigation = true; - this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true; + guestViewInternal.destroyGuest(this.guestInstanceId) + this.webContents = null + this.guestInstanceId = void 0 + this.beforeFirstNavigation = true + this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true } - return this.internalInstanceId = 0; - }; + return this.internalInstanceId = 0 + } // Sets the .request property. - WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function(request) { + WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function (request) { return Object.defineProperty(this.webviewNode, 'request', { value: request, enumerable: true - }); - }; + }) + } - WebViewImpl.prototype.setupFocusPropagation = function() { + WebViewImpl.prototype.setupFocusPropagation = function () { if (!this.webviewNode.hasAttribute('tabIndex')) { // needs a tabIndex in order to be focusable. // TODO(fsamuel): It would be nice to avoid exposing a tabIndex attribute // to allow to be focusable. // See http://crbug.com/231664. - this.webviewNode.setAttribute('tabIndex', -1); + this.webviewNode.setAttribute('tabIndex', -1) } // Focus the BrowserPlugin when the takes focus. this.webviewNode.addEventListener('focus', () => { - this.browserPluginNode.focus(); - }); + this.browserPluginNode.focus() + }) // Blur the BrowserPlugin when the loses focus. this.webviewNode.addEventListener('blur', () => { - this.browserPluginNode.blur(); - }); - }; - + this.browserPluginNode.blur() + }) + } // This observer monitors mutations to attributes of the and // updates the BrowserPlugin properties accordingly. In turn, updating // a BrowserPlugin property will update the corresponding BrowserPlugin // attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more // details. - WebViewImpl.prototype.handleWebviewAttributeMutation = function(attributeName, oldValue, newValue) { + WebViewImpl.prototype.handleWebviewAttributeMutation = function (attributeName, oldValue, newValue) { if (!this.attributes[attributeName] || this.attributes[attributeName].ignoreMutation) { - return; + return } - // Let the changed attribute handle its own mutation; - return this.attributes[attributeName].handleMutation(oldValue, newValue); - }; + // Let the changed attribute handle its own mutation + return this.attributes[attributeName].handleMutation(oldValue, newValue) + } - WebViewImpl.prototype.handleBrowserPluginAttributeMutation = function(attributeName, oldValue, newValue) { + WebViewImpl.prototype.handleBrowserPluginAttributeMutation = function (attributeName, oldValue, newValue) { if (attributeName === webViewConstants.ATTRIBUTE_INTERNALINSTANCEID && !oldValue && !!newValue) { - this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID); - this.internalInstanceId = parseInt(newValue); + this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID) + this.internalInstanceId = parseInt(newValue) // Track when the element resizes using the element resize callback. - webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this)); + webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this)) if (!this.guestInstanceId) { - return; + return } - return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()); + return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()) } - }; + } - WebViewImpl.prototype.onSizeChanged = function(webViewEvent) { - var maxHeight, maxWidth, minHeight, minWidth, newHeight, newWidth, node, width; - newWidth = webViewEvent.newWidth; - newHeight = webViewEvent.newHeight; - node = this.webviewNode; - width = node.offsetWidth; + WebViewImpl.prototype.onSizeChanged = function (webViewEvent) { + var maxHeight, maxWidth, minHeight, minWidth, newHeight, newWidth, node, width + newWidth = webViewEvent.newWidth + newHeight = webViewEvent.newHeight + node = this.webviewNode + width = node.offsetWidth // Check the current bounds to make sure we do not resize // outside of current constraints. - maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width; - maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width; - minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width; - minHeight = this.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() | width; - minWidth = Math.min(minWidth, maxWidth); - minHeight = Math.min(minHeight, maxHeight); + maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width + maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width + minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width + minHeight = this.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() | width + minWidth = Math.min(minWidth, maxWidth) + minHeight = Math.min(minHeight, maxHeight) if (!this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE].getValue() || (newWidth >= minWidth && newWidth <= maxWidth && newHeight >= minHeight && newHeight <= maxHeight)) { - node.style.width = newWidth + 'px'; - node.style.height = newHeight + 'px'; + node.style.width = newWidth + 'px' + node.style.height = newHeight + 'px' // Only fire the DOM event if the size of the has actually // changed. - return this.dispatchEvent(webViewEvent); + return this.dispatchEvent(webViewEvent) } - }; + } - WebViewImpl.prototype.onElementResize = function(newSize) { + WebViewImpl.prototype.onElementResize = function (newSize) { // Dispatch the 'resize' event. - var resizeEvent; + var resizeEvent resizeEvent = new Event('resize', { bubbles: true - }); - resizeEvent.newWidth = newSize.width; - resizeEvent.newHeight = newSize.height; - this.dispatchEvent(resizeEvent); + }) + resizeEvent.newWidth = newSize.width + resizeEvent.newHeight = newSize.height + this.dispatchEvent(resizeEvent) if (this.guestInstanceId) { return guestViewInternal.setSize(this.guestInstanceId, { normal: newSize - }); + }) } - }; + } - WebViewImpl.prototype.createGuest = function() { + WebViewImpl.prototype.createGuest = function () { return guestViewInternal.createGuest(this.buildParams(), (event, guestInstanceId) => { - this.attachWindow(guestInstanceId); - }); - }; + this.attachWindow(guestInstanceId) + }) + } - WebViewImpl.prototype.dispatchEvent = function(webViewEvent) { - return this.webviewNode.dispatchEvent(webViewEvent); - }; + WebViewImpl.prototype.dispatchEvent = function (webViewEvent) { + return this.webviewNode.dispatchEvent(webViewEvent) + } // Adds an 'on' property on the webview, which can be used to set/unset // an event handler. - WebViewImpl.prototype.setupEventProperty = function(eventName) { - var propertyName; - propertyName = 'on' + eventName.toLowerCase(); + WebViewImpl.prototype.setupEventProperty = function (eventName) { + var propertyName + propertyName = 'on' + eventName.toLowerCase() return Object.defineProperty(this.webviewNode, propertyName, { get: () => { - return this.on[propertyName]; + return this.on[propertyName] }, set: (value) => { if (this.on[propertyName]) { - this.webviewNode.removeEventListener(eventName, this.on[propertyName]); + this.webviewNode.removeEventListener(eventName, this.on[propertyName]) } - this.on[propertyName] = value; + this.on[propertyName] = value if (value) { - return this.webviewNode.addEventListener(eventName, value); + return this.webviewNode.addEventListener(eventName, value) } }, enumerable: true - }); - }; + }) + } // Updates state upon loadcommit. - WebViewImpl.prototype.onLoadCommit = function(webViewEvent) { - var newValue, oldValue; - oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC); - newValue = webViewEvent.url; + WebViewImpl.prototype.onLoadCommit = function (webViewEvent) { + var newValue, oldValue + oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC) + newValue = webViewEvent.url if (webViewEvent.isMainFrame && (oldValue !== newValue)) { - // Touching the src attribute triggers a navigation. To avoid // triggering a page reload on every guest-initiated navigation, // we do not handle this mutation. - return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue); + return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue) } - }; + } - WebViewImpl.prototype.onAttach = function(storagePartitionId) { - return this.attributes[webViewConstants.ATTRIBUTE_PARTITION].setValue(storagePartitionId); - }; + WebViewImpl.prototype.onAttach = function (storagePartitionId) { + return this.attributes[webViewConstants.ATTRIBUTE_PARTITION].setValue(storagePartitionId) + } - WebViewImpl.prototype.buildParams = function() { - var attribute, attributeName, css, elementRect, params, ref1; + WebViewImpl.prototype.buildParams = function () { + var attribute, attributeName, css, elementRect, params, ref1 params = { instanceId: this.viewInstanceId, userAgentOverride: this.userAgentOverride - }; - ref1 = this.attributes; + } + ref1 = this.attributes for (attributeName in ref1) { - if (!hasProp.call(ref1, attributeName)) continue; - attribute = ref1[attributeName]; - params[attributeName] = attribute.getValue(); + if (!hasProp.call(ref1, attributeName)) continue + attribute = ref1[attributeName] + params[attributeName] = attribute.getValue() } // When the WebView is not participating in layout (display:none) @@ -241,96 +239,95 @@ var WebViewImpl = (function() { // However, in the case where the WebView has a fixed size we can // use that value to initially size the guest so as to avoid a relayout of // the on display:block. - css = window.getComputedStyle(this.webviewNode, null); - elementRect = this.webviewNode.getBoundingClientRect(); - params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width')); - params.elementHeight = parseInt(elementRect.height) || parseInt(css.getPropertyValue('height')); - return params; - }; + css = window.getComputedStyle(this.webviewNode, null) + elementRect = this.webviewNode.getBoundingClientRect() + params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width')) + params.elementHeight = parseInt(elementRect.height) || parseInt(css.getPropertyValue('height')) + return params + } - WebViewImpl.prototype.attachWindow = function(guestInstanceId) { - this.guestInstanceId = guestInstanceId; - this.webContents = remote.getGuestWebContents(this.guestInstanceId); + WebViewImpl.prototype.attachWindow = function (guestInstanceId) { + this.guestInstanceId = guestInstanceId + this.webContents = remote.getGuestWebContents(this.guestInstanceId) if (!this.internalInstanceId) { - return true; + return true } - return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()); - }; + return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()) + } - return WebViewImpl; - -})(); + return WebViewImpl +})() // Registers browser plugin custom element. -var registerBrowserPluginElement = function() { - var proto; - proto = Object.create(HTMLObjectElement.prototype); - proto.createdCallback = function() { - this.setAttribute('type', 'application/browser-plugin'); - this.setAttribute('id', 'browser-plugin-' + getNextId()); +var registerBrowserPluginElement = function () { + var proto + proto = Object.create(HTMLObjectElement.prototype) + proto.createdCallback = function () { + this.setAttribute('type', 'application/browser-plugin') + this.setAttribute('id', 'browser-plugin-' + getNextId()) // The node fills in the container. - return this.style.flex = '1 1 auto'; - }; - proto.attributeChangedCallback = function(name, oldValue, newValue) { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + return this.style.flex = '1 1 auto' + } + proto.attributeChangedCallback = function (name, oldValue, newValue) { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue); - }; - proto.attachedCallback = function() { + return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue) + } + proto.attachedCallback = function () { // Load the plugin immediately. - return this.nonExistentAttribute; - }; + return this.nonExistentAttribute + } WebViewImpl.BrowserPlugin = webFrame.registerEmbedderCustomElement('browserplugin', { - "extends": 'object', + 'extends': 'object', prototype: proto - }); - delete proto.createdCallback; - delete proto.attachedCallback; - delete proto.detachedCallback; - return delete proto.attributeChangedCallback; -}; + }) + delete proto.createdCallback + delete proto.attachedCallback + delete proto.detachedCallback + return delete proto.attributeChangedCallback +} // Registers custom element. -var registerWebViewElement = function() { - var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto; - proto = Object.create(HTMLObjectElement.prototype); - proto.createdCallback = function() { - return new WebViewImpl(this); - }; - proto.attributeChangedCallback = function(name, oldValue, newValue) { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); +var registerWebViewElement = function () { + var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto + proto = Object.create(HTMLObjectElement.prototype) + proto.createdCallback = function () { + return new WebViewImpl(this) + } + proto.attributeChangedCallback = function (name, oldValue, newValue) { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - return internal.handleWebviewAttributeMutation(name, oldValue, newValue); - }; - proto.detachedCallback = function() { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + return internal.handleWebviewAttributeMutation(name, oldValue, newValue) + } + proto.detachedCallback = function () { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - guestViewInternal.deregisterEvents(internal.viewInstanceId); - internal.elementAttached = false; - return internal.reset(); - }; - proto.attachedCallback = function() { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + guestViewInternal.deregisterEvents(internal.viewInstanceId) + internal.elementAttached = false + return internal.reset() + } + proto.attachedCallback = function () { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } if (!internal.elementAttached) { - guestViewInternal.registerEvents(internal, internal.viewInstanceId); - internal.elementAttached = true; - return internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse(); + guestViewInternal.registerEvents(internal, internal.viewInstanceId) + internal.elementAttached = true + return internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse() } - }; + } // Public-facing API methods. methods = [ @@ -378,7 +375,7 @@ var registerWebViewElement = function() { 'inspectServiceWorker', 'print', 'printToPDF', - ]; + ] nonblockMethods = [ 'insertCSS', 'insertText', @@ -387,79 +384,79 @@ var registerWebViewElement = function() { 'setZoomFactor', 'setZoomLevel', 'setZoomLevelLimits', - ]; + ] // Forward proto.foo* method calls to WebViewImpl.foo*. - createBlockHandler = function(m) { - return function(...args) { - const internal = v8Util.getHiddenValue(this, 'internal'); + createBlockHandler = function (m) { + return function (...args) { + const internal = v8Util.getHiddenValue(this, 'internal') if (internal.webContents) { - return internal.webContents[m].apply(internal.webContents, args); + return internal.webContents[m].apply(internal.webContents, args) } else { - throw new Error(`Cannot call ${m} because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.`); + throw new Error(`Cannot call ${m} because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.`) } - }; - }; - for (i = 0, len = methods.length; i < len; i++) { - m = methods[i]; - proto[m] = createBlockHandler(m); + } + } + for (i = 0, len = methods.length; i < len; i++) { + m = methods[i] + proto[m] = createBlockHandler(m) + } + createNonBlockHandler = function (m) { + return function (...args) { + const internal = v8Util.getHiddenValue(this, 'internal') + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)) + } } - createNonBlockHandler = function(m) { - return function(...args) { - const internal = v8Util.getHiddenValue(this, 'internal'); - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)); - }; - }; for (j = 0, len1 = nonblockMethods.length; j < len1; j++) { - m = nonblockMethods[j]; - proto[m] = createNonBlockHandler(m); + m = nonblockMethods[j] + proto[m] = createNonBlockHandler(m) } - proto.executeJavaScript = function(code, hasUserGesture, callback) { - var internal = v8Util.getHiddenValue(this, 'internal'); - if (typeof hasUserGesture === "function") { - callback = hasUserGesture; - hasUserGesture = false; + proto.executeJavaScript = function (code, hasUserGesture, callback) { + var internal = v8Util.getHiddenValue(this, 'internal') + if (typeof hasUserGesture === 'function') { + callback = hasUserGesture + hasUserGesture = false } - let requestId = getNextId(); - ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, "executeJavaScript", code, hasUserGesture); - ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function(event, result) { + let requestId = getNextId() + ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, 'executeJavaScript', code, hasUserGesture) + ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function (event, result) { if (callback) - callback(result); - }); - }; + callback(result) + }) + } // WebContents associated with this webview. - proto.getWebContents = function() { - var internal = v8Util.getHiddenValue(this, 'internal'); - return internal.webContents; - }; + proto.getWebContents = function () { + var internal = v8Util.getHiddenValue(this, 'internal') + return internal.webContents + } // Deprecated. - deprecate.rename(proto, 'getUrl', 'getURL'); + deprecate.rename(proto, 'getUrl', 'getURL') window.WebView = webFrame.registerEmbedderCustomElement('webview', { prototype: proto - }); + }) // Delete the callbacks so developers cannot call them and produce unexpected // behavior. - delete proto.createdCallback; - delete proto.attachedCallback; - delete proto.detachedCallback; - return delete proto.attributeChangedCallback; -}; + delete proto.createdCallback + delete proto.attachedCallback + delete proto.detachedCallback + return delete proto.attributeChangedCallback +} -var useCapture = true; +var useCapture = true -var listener = function(event) { +var listener = function (event) { if (document.readyState === 'loading') { - return; + return } - registerBrowserPluginElement(); - registerWebViewElement(); - return window.removeEventListener(event.type, listener, useCapture); -}; + registerBrowserPluginElement() + registerWebViewElement() + return window.removeEventListener(event.type, listener, useCapture) +} -window.addEventListener('readystatechange', listener, true); +window.addEventListener('readystatechange', listener, true) -module.exports = WebViewImpl; +module.exports = WebViewImpl diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 1b12f6f733c..2a5417b9c50 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -1,135 +1,135 @@ -const assert = require('assert'); -const ChildProcess = require('child_process'); -const path = require('path'); -const remote = require('electron').remote; +const assert = require('assert') +const ChildProcess = require('child_process') +const path = require('path') +const remote = require('electron').remote -const app = remote.require('electron').app; -const BrowserWindow = remote.require('electron').BrowserWindow; +const app = remote.require('electron').app +const BrowserWindow = remote.require('electron').BrowserWindow -describe('electron module', function() { - it('allows old style require by default', function() { - require('shell'); - }); +describe('electron module', function () { + it('allows old style require by default', function () { + require('shell') + }) - it('can prevent exposing internal modules to require', function(done) { - const electron = require('electron'); - const clipboard = require('clipboard'); - assert.equal(typeof clipboard, 'object'); - electron.hideInternalModules(); + it('can prevent exposing internal modules to require', function (done) { + const electron = require('electron') + const clipboard = require('clipboard') + assert.equal(typeof clipboard, 'object') + electron.hideInternalModules() try { - require('clipboard'); + require('clipboard') } catch(err) { - assert.equal(err.message, 'Cannot find module \'clipboard\''); - done(); + assert.equal(err.message, "Cannot find module 'clipboard'") + done() } - }); -}); + }) +}) -describe('app module', function() { - describe('app.getVersion()', function() { - it('returns the version field of package.json', function() { - assert.equal(app.getVersion(), '0.1.0'); - }); - }); +describe('app module', function () { + describe('app.getVersion()', function () { + it('returns the version field of package.json', function () { + assert.equal(app.getVersion(), '0.1.0') + }) + }) - describe('app.setVersion(version)', function() { - it('overrides the version', function() { - assert.equal(app.getVersion(), '0.1.0'); - app.setVersion('test-version'); - assert.equal(app.getVersion(), 'test-version'); - app.setVersion('0.1.0'); - }); - }); + describe('app.setVersion(version)', function () { + it('overrides the version', function () { + assert.equal(app.getVersion(), '0.1.0') + app.setVersion('test-version') + assert.equal(app.getVersion(), 'test-version') + app.setVersion('0.1.0') + }) + }) - describe('app.getName()', function() { - it('returns the name field of package.json', function() { - assert.equal(app.getName(), 'Electron Test'); - }); - }); + describe('app.getName()', function () { + it('returns the name field of package.json', function () { + assert.equal(app.getName(), 'Electron Test') + }) + }) - describe('app.setName(name)', function() { - it('overrides the name', function() { - assert.equal(app.getName(), 'Electron Test'); - app.setName('test-name'); - assert.equal(app.getName(), 'test-name'); - app.setName('Electron Test'); - }); - }); + describe('app.setName(name)', function () { + it('overrides the name', function () { + assert.equal(app.getName(), 'Electron Test') + app.setName('test-name') + assert.equal(app.getName(), 'test-name') + app.setName('Electron Test') + }) + }) - describe('app.getLocale()', function() { - it('should not be empty', function() { - assert.notEqual(app.getLocale(), ''); - }); - }); + describe('app.getLocale()', function () { + it('should not be empty', function () { + assert.notEqual(app.getLocale(), '') + }) + }) - describe('app.exit(exitCode)', function() { - var appProcess = null; + describe('app.exit(exitCode)', function () { + var appProcess = null - afterEach(function() { - appProcess != null ? appProcess.kill() : void 0; - }); + afterEach(function () { + appProcess != null ? appProcess.kill() : void 0 + }) - it('emits a process exit event with the code', function(done) { - var appPath = path.join(__dirname, 'fixtures', 'api', 'quit-app'); - var electronPath = remote.getGlobal('process').execPath; - var output = ''; - appProcess = ChildProcess.spawn(electronPath, [appPath]); - appProcess.stdout.on('data', function(data) { - output += data; - }); - appProcess.on('close', function(code) { + it('emits a process exit event with the code', function (done) { + var appPath = path.join(__dirname, 'fixtures', 'api', 'quit-app') + var electronPath = remote.getGlobal('process').execPath + var output = '' + appProcess = ChildProcess.spawn(electronPath, [appPath]) + appProcess.stdout.on('data', function (data) { + output += data + }) + appProcess.on('close', function (code) { if (process.platform !== 'win32') { - assert.notEqual(output.indexOf('Exit event with code: 123'), -1); + assert.notEqual(output.indexOf('Exit event with code: 123'), -1) } - assert.equal(code, 123); - done(); - }); - }); - }); + assert.equal(code, 123) + done() + }) + }) + }) - describe('BrowserWindow events', function() { - var w = null; + describe('BrowserWindow events', function () { + var w = null - afterEach(function() { + afterEach(function () { if (w != null) { - w.destroy(); + w.destroy() } - w = null; - }); + w = null + }) - it('should emit browser-window-focus event when window is focused', function(done) { - app.once('browser-window-focus', function(e, window) { - assert.equal(w.id, window.id); - done(); - }); + it('should emit browser-window-focus event when window is focused', function (done) { + app.once('browser-window-focus', function (e, window) { + assert.equal(w.id, window.id) + done() + }) w = new BrowserWindow({ show: false - }); - w.emit('focus'); - }); + }) + w.emit('focus') + }) - it('should emit browser-window-blur event when window is blured', function(done) { - app.once('browser-window-blur', function(e, window) { - assert.equal(w.id, window.id); - done(); - }); + it('should emit browser-window-blur event when window is blured', function (done) { + app.once('browser-window-blur', function (e, window) { + assert.equal(w.id, window.id) + done() + }) w = new BrowserWindow({ show: false - }); - w.emit('blur'); - }); + }) + w.emit('blur') + }) - it('should emit browser-window-created event when window is created', function(done) { - app.once('browser-window-created', function(e, window) { - setImmediate(function() { - assert.equal(w.id, window.id); - done(); - }); - }); + it('should emit browser-window-created event when window is created', function (done) { + app.once('browser-window-created', function (e, window) { + setImmediate(function () { + assert.equal(w.id, window.id) + done() + }) + }) w = new BrowserWindow({ show: false - }); - w.emit('blur'); - }); - }); -}); + }) + w.emit('blur') + }) + }) +}) From bd9b0b8ed3e9483deb0fee528737d4af189f7201 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 25 Mar 2016 12:57:49 -0700 Subject: [PATCH 0308/1265] wrap conditional, because return can only be used in a function --- spec/api-auto-updater-spec.js | 65 +++++++++++++++++------------------ 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/spec/api-auto-updater-spec.js b/spec/api-auto-updater-spec.js index efd3afe3882..6335f335943 100644 --- a/spec/api-auto-updater-spec.js +++ b/spec/api-auto-updater-spec.js @@ -1,38 +1,37 @@ -const assert = require('assert'); -const autoUpdater = require('electron').remote.autoUpdater; -const ipcRenderer = require('electron').ipcRenderer; +const assert = require('assert') +const autoUpdater = require('electron').remote.autoUpdater +const ipcRenderer = require('electron').ipcRenderer // Skip autoUpdater tests in MAS build. -if (process.mas) - return; +if (!process.mas) { + describe('autoUpdater module', function () { + describe('checkForUpdates', function () { + it('emits an error on Windows when called the feed URL is not set', function (done) { + if (process.platform !== 'win32') { + return done() + } -describe('autoUpdater module', function() { - describe('checkForUpdates', function() { - it('emits an error on Windows when called the feed URL is not set', function (done) { - if (process.platform !== 'win32') { - return done(); - } + ipcRenderer.once('auto-updater-error', function (event, message) { + assert.equal(message, 'Update URL is not set') + done() + }) + autoUpdater.setFeedURL('') + autoUpdater.checkForUpdates() + }) + }) - ipcRenderer.once('auto-updater-error', function(event, message) { - assert.equal(message, 'Update URL is not set'); - done(); - }); - autoUpdater.setFeedURL(''); - autoUpdater.checkForUpdates(); - }); - }); + describe('setFeedURL', function () { + it('emits an error on Mac OS X when the application is unsigned', function (done) { + if (process.platform !== 'darwin') { + return done() + } - describe('setFeedURL', function() { - it('emits an error on Mac OS X when the application is unsigned', function (done) { - if (process.platform !== 'darwin') { - return done(); - } - - ipcRenderer.once('auto-updater-error', function(event, message) { - assert.equal(message, 'Could not get code signature for running application'); - done(); - }); - autoUpdater.setFeedURL(''); - }); - }); -}); + ipcRenderer.once('auto-updater-error', function (event, message) { + assert.equal(message, 'Could not get code signature for running application') + done() + }) + autoUpdater.setFeedURL('') + }) + }) + }) +} From 06b556c34c5d01db15279c1b7a94c82225e8dace Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 25 Mar 2016 12:58:04 -0700 Subject: [PATCH 0309/1265] ignore more files that are confusing standard-format --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index ced3ab8ae99..9f22ef2ae07 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ }, "standard": { "ignore": [ - "/lib/browser/rpc-server.js" + "/lib/browser/rpc-server.js", + "/lib/common/asar.js" ] }, "private": true, From f35f3622721d917716f3de5527bb170fb99b17c4 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 25 Mar 2016 13:03:49 -0700 Subject: [PATCH 0310/1265] autoformat more files --- spec/api-browser-window-spec.js | 1194 +++++++------- spec/api-clipboard-spec.js | 104 +- spec/api-crash-reporter-spec.js | 130 +- spec/api-debugger-spec.js | 180 +-- spec/api-deprecations-spec.js | 40 +- spec/api-desktop-capturer-spec.js | 42 +- spec/api-ipc-spec.js | 336 ++-- spec/api-menu-spec.js | 302 ++-- spec/api-native-image-spec.js | 68 +- spec/api-protocol-spec.js | 1202 +++++++-------- spec/api-screen-spec.js | 38 +- spec/api-session-spec.js | 368 ++--- spec/api-web-frame-spec.js | 36 +- spec/api-web-request-spec.js | 579 ++++--- spec/asar-spec.js | 1368 ++++++++--------- spec/chromium-spec.js | 682 ++++---- spec/fixtures/api/quit-app/main.js | 12 +- spec/fixtures/module/asar.js | 8 +- spec/fixtures/module/call.js | 12 +- spec/fixtures/module/class.js | 20 +- spec/fixtures/module/create_socket.js | 8 +- spec/fixtures/module/fork_ping.js | 24 +- spec/fixtures/module/function.js | 2 +- spec/fixtures/module/id.js | 2 +- spec/fixtures/module/locale-compare.js | 4 +- spec/fixtures/module/original-fs.js | 4 +- spec/fixtures/module/ping.js | 8 +- spec/fixtures/module/preload-ipc.js | 8 +- spec/fixtures/module/preload-node-off.js | 8 +- spec/fixtures/module/preload.js | 2 +- spec/fixtures/module/print_name.js | 12 +- spec/fixtures/module/process_args.js | 8 +- spec/fixtures/module/promise.js | 6 +- spec/fixtures/module/property.js | 2 +- spec/fixtures/module/runas.js | 10 +- spec/fixtures/module/send-later.js | 8 +- spec/fixtures/module/set-global.js | 2 +- spec/fixtures/module/set-immediate.js | 20 +- .../pages/service-worker/service-worker.js | 12 +- spec/fixtures/workers/shared_worker.js | 14 +- spec/fixtures/workers/worker.js | 6 +- spec/modules-spec.js | 76 +- spec/node-spec.js | 374 ++--- spec/static/main.js | 172 +-- spec/webview-spec.js | 1300 ++++++++-------- tools/dump-version-info.js | 84 +- tools/win/register_msdia80_dll.js | 20 +- 47 files changed, 4458 insertions(+), 4459 deletions(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index beb84a8d748..77e8b004bfe 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -1,782 +1,782 @@ -'use strict'; +'use strict' -const assert = require('assert'); -const fs = require('fs'); -const path = require('path'); -const os = require('os'); +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const os = require('os') -const remote = require('electron').remote; -const screen = require('electron').screen; +const remote = require('electron').remote +const screen = require('electron').screen -const app = remote.require('electron').app; -const ipcMain = remote.require('electron').ipcMain; -const ipcRenderer = require('electron').ipcRenderer; -const BrowserWindow = remote.require('electron').BrowserWindow; +const app = remote.require('electron').app +const ipcMain = remote.require('electron').ipcMain +const ipcRenderer = require('electron').ipcRenderer +const BrowserWindow = remote.require('electron').BrowserWindow -const isCI = remote.getGlobal('isCi'); +const isCI = remote.getGlobal('isCi') -describe('browser-window module', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); - var w = null; +describe('browser-window module', function () { + var fixtures = path.resolve(__dirname, 'fixtures') + var w = null - beforeEach(function() { + beforeEach(function () { if (w != null) { - w.destroy(); + w.destroy() } w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - }); + }) + }) - afterEach(function() { + afterEach(function () { if (w != null) { - w.destroy(); + w.destroy() } - w = null; - }); + w = null + }) - describe('BrowserWindow.close()', function() { - it('should emit unload handler', function(done) { - w.webContents.on('did-finish-load', function() { - w.close(); - }); - w.on('closed', function() { - var test = path.join(fixtures, 'api', 'unload'); - var content = fs.readFileSync(test); - fs.unlinkSync(test); - assert.equal(String(content), 'unload'); - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'unload.html')); - }); + describe('BrowserWindow.close()', function () { + it('should emit unload handler', function (done) { + w.webContents.on('did-finish-load', function () { + w.close() + }) + w.on('closed', function () { + var test = path.join(fixtures, 'api', 'unload') + var content = fs.readFileSync(test) + fs.unlinkSync(test) + assert.equal(String(content), 'unload') + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'unload.html')) + }) - it('should emit beforeunload handler', function(done) { - w.on('onbeforeunload', function() { - done(); - }); - w.webContents.on('did-finish-load', function() { - w.close(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false.html')); - }); - }); + it('should emit beforeunload handler', function (done) { + w.on('onbeforeunload', function () { + done() + }) + w.webContents.on('did-finish-load', function () { + w.close() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'beforeunload-false.html')) + }) + }) - describe('window.close()', function() { - it('should emit unload handler', function(done) { - w.on('closed', function() { - var test = path.join(fixtures, 'api', 'close'); - var content = fs.readFileSync(test); - fs.unlinkSync(test); - assert.equal(String(content), 'close'); - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close.html')); - }); + describe('window.close()', function () { + it('should emit unload handler', function (done) { + w.on('closed', function () { + var test = path.join(fixtures, 'api', 'close') + var content = fs.readFileSync(test) + fs.unlinkSync(test) + assert.equal(String(content), 'close') + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close.html')) + }) - it('should emit beforeunload handler', function(done) { - w.on('onbeforeunload', function() { - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html')); - }); - }); + it('should emit beforeunload handler', function (done) { + w.on('onbeforeunload', function () { + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html')) + }) + }) - describe('BrowserWindow.destroy()', function() { - it('prevents users to access methods of webContents', function() { - var webContents = w.webContents; - w.destroy(); - assert.throws((function() { - webContents.getId(); - }), /Object has been destroyed/); - }); - }); + describe('BrowserWindow.destroy()', function () { + it('prevents users to access methods of webContents', function () { + var webContents = w.webContents + w.destroy() + assert.throws((function () { + webContents.getId() + }), /Object has been destroyed/) + }) + }) - describe('BrowserWindow.loadURL(url)', function() { - it('should emit did-start-loading event', function(done) { - w.webContents.on('did-start-loading', function() { - done(); - }); - w.loadURL('about:blank'); - }); + describe('BrowserWindow.loadURL(url)', function () { + it('should emit did-start-loading event', function (done) { + w.webContents.on('did-start-loading', function () { + done() + }) + w.loadURL('about:blank') + }) - it('should emit did-fail-load event for files that do not exist', function(done) { - w.webContents.on('did-fail-load', function(event, code) { - assert.equal(code, -6); - done(); - }); - w.loadURL('file://a.txt'); - }); + it('should emit did-fail-load event for files that do not exist', function (done) { + w.webContents.on('did-fail-load', function (event, code) { + assert.equal(code, -6) + done() + }) + w.loadURL('file://a.txt') + }) - it('should emit did-fail-load event for invalid URL', function(done) { - w.webContents.on('did-fail-load', function(event, code, desc) { - assert.equal(desc, 'ERR_INVALID_URL'); - assert.equal(code, -300); - done(); - }); - w.loadURL('http://example:port'); - }); - }); + it('should emit did-fail-load event for invalid URL', function (done) { + w.webContents.on('did-fail-load', function (event, code, desc) { + assert.equal(desc, 'ERR_INVALID_URL') + assert.equal(code, -300) + done() + }) + w.loadURL('http://example:port') + }) + }) - describe('BrowserWindow.show()', function() { + describe('BrowserWindow.show()', function () { if (isCI) { - return; + return } - it('should focus on window', function() { - w.show(); - assert(w.isFocused()); - }); + it('should focus on window', function () { + w.show() + assert(w.isFocused()) + }) - it('should make the window visible', function() { - w.show(); - assert(w.isVisible()); - }); + it('should make the window visible', function () { + w.show() + assert(w.isVisible()) + }) - it('emits when window is shown', function(done) { - this.timeout(10000); - w.once('show', function() { - assert.equal(w.isVisible(), true); - done(); - }); - w.show(); - }); - }); + it('emits when window is shown', function (done) { + this.timeout(10000) + w.once('show', function () { + assert.equal(w.isVisible(), true) + done() + }) + w.show() + }) + }) - describe('BrowserWindow.hide()', function() { + describe('BrowserWindow.hide()', function () { if (isCI) { - return; + return } - it('should defocus on window', function() { - w.hide(); - assert(!w.isFocused()); - }); + it('should defocus on window', function () { + w.hide() + assert(!w.isFocused()) + }) - it('should make the window not visible', function() { - w.show(); - w.hide(); - assert(!w.isVisible()); - }); + it('should make the window not visible', function () { + w.show() + w.hide() + assert(!w.isVisible()) + }) - it('emits when window is hidden', function(done) { - this.timeout(10000); - w.show(); - w.once('hide', function() { - assert.equal(w.isVisible(), false); - done(); - }); - w.hide(); - }); - }); + it('emits when window is hidden', function (done) { + this.timeout(10000) + w.show() + w.once('hide', function () { + assert.equal(w.isVisible(), false) + done() + }) + w.hide() + }) + }) - describe('BrowserWindow.showInactive()', function() { - it('should not focus on window', function() { - w.showInactive(); - assert(!w.isFocused()); - }); - }); + describe('BrowserWindow.showInactive()', function () { + it('should not focus on window', function () { + w.showInactive() + assert(!w.isFocused()) + }) + }) - describe('BrowserWindow.focus()', function() { - it('does not make the window become visible', function() { - assert.equal(w.isVisible(), false); - w.focus(); - assert.equal(w.isVisible(), false); - }); - }); + describe('BrowserWindow.focus()', function () { + it('does not make the window become visible', function () { + assert.equal(w.isVisible(), false) + w.focus() + assert.equal(w.isVisible(), false) + }) + }) - describe('BrowserWindow.blur()', function() { - it('removes focus from window', function() { - w.blur(); - assert(!w.isFocused()); - }); - }); + describe('BrowserWindow.blur()', function () { + it('removes focus from window', function () { + w.blur() + assert(!w.isFocused()) + }) + }) - describe('BrowserWindow.capturePage(rect, callback)', function() { - it('calls the callback with a Buffer', function(done) { + describe('BrowserWindow.capturePage(rect, callback)', function () { + it('calls the callback with a Buffer', function (done) { w.capturePage({ x: 0, y: 0, width: 100, height: 100 - }, function(image) { - assert.equal(image.isEmpty(), true); - done(); - }); - }); - }); + }, function (image) { + assert.equal(image.isEmpty(), true) + done() + }) + }) + }) - describe('BrowserWindow.setSize(width, height)', function() { - it('sets the window size', function(done) { - var size = [300, 400]; - w.once('resize', function() { - var newSize = w.getSize(); - assert.equal(newSize[0], size[0]); - assert.equal(newSize[1], size[1]); - done(); - }); - w.setSize(size[0], size[1]); - }); - }); + describe('BrowserWindow.setSize(width, height)', function () { + it('sets the window size', function (done) { + var size = [300, 400] + w.once('resize', function () { + var newSize = w.getSize() + assert.equal(newSize[0], size[0]) + assert.equal(newSize[1], size[1]) + done() + }) + w.setSize(size[0], size[1]) + }) + }) - describe('BrowserWindow.setPosition(x, y)', function() { - it('sets the window position', function(done) { - var pos = [10, 10]; - w.once('move', function() { - var newPos = w.getPosition(); - assert.equal(newPos[0], pos[0]); - assert.equal(newPos[1], pos[1]); - done(); - }); - w.setPosition(pos[0], pos[1]); - }); - }); + describe('BrowserWindow.setPosition(x, y)', function () { + it('sets the window position', function (done) { + var pos = [10, 10] + w.once('move', function () { + var newPos = w.getPosition() + assert.equal(newPos[0], pos[0]) + assert.equal(newPos[1], pos[1]) + done() + }) + w.setPosition(pos[0], pos[1]) + }) + }) - describe('BrowserWindow.setContentSize(width, height)', function() { - it('sets the content size', function() { - var size = [400, 400]; - w.setContentSize(size[0], size[1]); - var after = w.getContentSize(); - assert.equal(after[0], size[0]); - assert.equal(after[1], size[1]); - }); + describe('BrowserWindow.setContentSize(width, height)', function () { + it('sets the content size', function () { + var size = [400, 400] + w.setContentSize(size[0], size[1]) + var after = w.getContentSize() + assert.equal(after[0], size[0]) + assert.equal(after[1], size[1]) + }) - it('works for framless window', function() { - w.destroy(); + it('works for framless window', function () { + w.destroy() w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 - }); - var size = [400, 400]; - w.setContentSize(size[0], size[1]); - var after = w.getContentSize(); - assert.equal(after[0], size[0]); - assert.equal(after[1], size[1]); - }); - }); + }) + var size = [400, 400] + w.setContentSize(size[0], size[1]) + var after = w.getContentSize() + assert.equal(after[0], size[0]) + assert.equal(after[1], size[1]) + }) + }) - describe('BrowserWindow.fromId(id)', function() { - it('returns the window with id', function() { - assert.equal(w.id, BrowserWindow.fromId(w.id).id); - }); - }); + describe('BrowserWindow.fromId(id)', function () { + it('returns the window with id', function () { + assert.equal(w.id, BrowserWindow.fromId(w.id).id) + }) + }) - describe('"useContentSize" option', function() { - it('make window created with content size when used', function() { - w.destroy(); + describe('"useContentSize" option', function () { + it('make window created with content size when used', function () { + w.destroy() w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true - }); - var contentSize = w.getContentSize(); - assert.equal(contentSize[0], 400); - assert.equal(contentSize[1], 400); - }); + }) + var contentSize = w.getContentSize() + assert.equal(contentSize[0], 400) + assert.equal(contentSize[1], 400) + }) - it('make window created with window size when not used', function() { - var size = w.getSize(); - assert.equal(size[0], 400); - assert.equal(size[1], 400); - }); + it('make window created with window size when not used', function () { + var size = w.getSize() + assert.equal(size[0], 400) + assert.equal(size[1], 400) + }) - it('works for framless window', function() { - w.destroy(); + it('works for framless window', function () { + w.destroy() w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true - }); - var contentSize = w.getContentSize(); - assert.equal(contentSize[0], 400); - assert.equal(contentSize[1], 400); - var size = w.getSize(); - assert.equal(size[0], 400); - assert.equal(size[1], 400); - }); - }); + }) + var contentSize = w.getContentSize() + assert.equal(contentSize[0], 400) + assert.equal(contentSize[1], 400) + var size = w.getSize() + assert.equal(size[0], 400) + assert.equal(size[1], 400) + }) + }) - describe('"title-bar-style" option', function() { + describe('"title-bar-style" option', function () { if (process.platform !== 'darwin') { - return; + return } if (parseInt(os.release().split('.')[0]) < 14) { - return; + return } - it('creates browser window with hidden title bar', function() { - w.destroy(); + it('creates browser window with hidden title bar', function () { + w.destroy() w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' - }); - var contentSize = w.getContentSize(); - assert.equal(contentSize[1], 400); - }); + }) + var contentSize = w.getContentSize() + assert.equal(contentSize[1], 400) + }) - it('creates browser window with hidden inset title bar', function() { - w.destroy(); + it('creates browser window with hidden inset title bar', function () { + w.destroy() w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden-inset' - }); - var contentSize = w.getContentSize(); - assert.equal(contentSize[1], 400); - }); - }); + }) + var contentSize = w.getContentSize() + assert.equal(contentSize[1], 400) + }) + }) - describe('"enableLargerThanScreen" option', function() { + describe('"enableLargerThanScreen" option', function () { if (process.platform === 'linux') { - return; + return } - beforeEach(function() { - w.destroy(); + beforeEach(function () { + w.destroy() w = new BrowserWindow({ show: true, width: 400, height: 400, enableLargerThanScreen: true - }); - }); + }) + }) - it('can move the window out of screen', function() { - w.setPosition(-10, -10); - var after = w.getPosition(); - assert.equal(after[0], -10); - assert.equal(after[1], -10); - }); + it('can move the window out of screen', function () { + w.setPosition(-10, -10) + var after = w.getPosition() + assert.equal(after[0], -10) + assert.equal(after[1], -10) + }) - it('can set the window larger than screen', function() { - var size = screen.getPrimaryDisplay().size; - size.width += 100; - size.height += 100; - w.setSize(size.width, size.height); - var after = w.getSize(); - assert.equal(after[0], size.width); - assert.equal(after[1], size.height); - }); - }); + it('can set the window larger than screen', function () { + var size = screen.getPrimaryDisplay().size + size.width += 100 + size.height += 100 + w.setSize(size.width, size.height) + var after = w.getSize() + assert.equal(after[0], size.width) + assert.equal(after[1], size.height) + }) + }) - describe('"web-preferences" option', function() { - afterEach(function() { - ipcMain.removeAllListeners('answer'); - }); + describe('"web-preferences" option', function () { + afterEach(function () { + ipcMain.removeAllListeners('answer') + }) - describe('"preload" option', function() { - it('loads the script before other scripts in window', function(done) { - var preload = path.join(fixtures, 'module', 'set-global.js'); - ipcMain.once('answer', function(event, test) { - assert.equal(test, 'preload'); - done(); - }); - w.destroy(); + describe('"preload" option', function () { + it('loads the script before other scripts in window', function (done) { + var preload = path.join(fixtures, 'module', 'set-global.js') + ipcMain.once('answer', function (event, test) { + assert.equal(test, 'preload') + done() + }) + w.destroy() w = new BrowserWindow({ show: false, webPreferences: { preload: preload } - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html')); - }); - }); + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html')) + }) + }) - describe('"node-integration" option', function() { - it('disables node integration when specified to false', function(done) { - var preload = path.join(fixtures, 'module', 'send-later.js'); - ipcMain.once('answer', function(event, test) { - assert.equal(test, 'undefined'); - done(); - }); - w.destroy(); + describe('"node-integration" option', function () { + it('disables node integration when specified to false', function (done) { + var preload = path.join(fixtures, 'module', 'send-later.js') + ipcMain.once('answer', function (event, test) { + assert.equal(test, 'undefined') + done() + }) + w.destroy() w = new BrowserWindow({ show: false, webPreferences: { preload: preload, nodeIntegration: false } - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'blank.html')); - }); - }); - }); + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'blank.html')) + }) + }) + }) - describe('beforeunload handler', function() { - it('returning true would not prevent close', function(done) { - w.on('closed', function() { - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-true.html')); - }); + describe('beforeunload handler', function () { + it('returning true would not prevent close', function (done) { + w.on('closed', function () { + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-true.html')) + }) - it('returning non-empty string would not prevent close', function(done) { - w.on('closed', function() { - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-string.html')); - }); + it('returning non-empty string would not prevent close', function (done) { + w.on('closed', function () { + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-string.html')) + }) - it('returning false would prevent close', function(done) { - w.on('onbeforeunload', function() { - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html')); - }); + it('returning false would prevent close', function (done) { + w.on('onbeforeunload', function () { + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-false.html')) + }) - it('returning empty string would prevent close', function(done) { - w.on('onbeforeunload', function() { - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html')); - }); - }); + it('returning empty string would prevent close', function (done) { + w.on('onbeforeunload', function () { + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-empty-string.html')) + }) + }) - describe('new-window event', function() { + describe('new-window event', function () { if (isCI && process.platform === 'darwin') { - return; + return } - it('emits when window.open is called', function(done) { - w.webContents.once('new-window', function(e, url, frameName) { - e.preventDefault(); - assert.equal(url, 'http://host/'); - assert.equal(frameName, 'host'); - done(); - }); - w.loadURL("file://" + fixtures + "/pages/window-open.html"); - }); + it('emits when window.open is called', function (done) { + w.webContents.once('new-window', function (e, url, frameName) { + e.preventDefault() + assert.equal(url, 'http://host/') + assert.equal(frameName, 'host') + done() + }) + w.loadURL('file://' + fixtures + '/pages/window-open.html') + }) - it('emits when link with target is called', function(done) { - this.timeout(10000); - w.webContents.once('new-window', function(e, url, frameName) { - e.preventDefault(); - assert.equal(url, 'http://host/'); - assert.equal(frameName, 'target'); - done(); - }); - w.loadURL("file://" + fixtures + "/pages/target-name.html"); - }); - }); + it('emits when link with target is called', function (done) { + this.timeout(10000) + w.webContents.once('new-window', function (e, url, frameName) { + e.preventDefault() + assert.equal(url, 'http://host/') + assert.equal(frameName, 'target') + done() + }) + w.loadURL('file://' + fixtures + '/pages/target-name.html') + }) + }) - describe('maximize event', function() { + describe('maximize event', function () { if (isCI) { - return; + return } - it('emits when window is maximized', function(done) { - this.timeout(10000); - w.once('maximize', function() { - done(); - }); - w.show(); - w.maximize(); - }); - }); + it('emits when window is maximized', function (done) { + this.timeout(10000) + w.once('maximize', function () { + done() + }) + w.show() + w.maximize() + }) + }) - describe('unmaximize event', function() { + describe('unmaximize event', function () { if (isCI) { - return; + return } - it('emits when window is unmaximized', function(done) { - this.timeout(10000); - w.once('unmaximize', function() { - done(); - }); - w.show(); - w.maximize(); - w.unmaximize(); - }); - }); + it('emits when window is unmaximized', function (done) { + this.timeout(10000) + w.once('unmaximize', function () { + done() + }) + w.show() + w.maximize() + w.unmaximize() + }) + }) - describe('minimize event', function() { + describe('minimize event', function () { if (isCI) { - return; + return } - it('emits when window is minimized', function(done) { - this.timeout(10000); - w.once('minimize', function() { - done(); - }); - w.show(); - w.minimize(); - }); - }); + it('emits when window is minimized', function (done) { + this.timeout(10000) + w.once('minimize', function () { + done() + }) + w.show() + w.minimize() + }) + }) - describe('beginFrameSubscription method', function() { - this.timeout(20000); + describe('beginFrameSubscription method', function () { + this.timeout(20000) - it('subscribes frame updates', function(done) { - let called = false; - w.loadURL("file://" + fixtures + "/api/blank.html"); - w.webContents.beginFrameSubscription(function(data) { + it('subscribes frame updates', function (done) { + let called = false + w.loadURL('file://' + fixtures + '/api/blank.html') + w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) - return; - called = true; + return + called = true - assert.notEqual(data.length, 0); - w.webContents.endFrameSubscription(); - done(); - }); - }); - }); + assert.notEqual(data.length, 0) + w.webContents.endFrameSubscription() + done() + }) + }) + }) - describe('savePage method', function() { - const savePageDir = path.join(fixtures, 'save_page'); - const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); - const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); - const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); + describe('savePage method', function () { + const savePageDir = path.join(fixtures, 'save_page') + const savePageHtmlPath = path.join(savePageDir, 'save_page.html') + const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js') + const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css') - after(function() { + after(function () { try { - fs.unlinkSync(savePageCssPath); - fs.unlinkSync(savePageJsPath); - fs.unlinkSync(savePageHtmlPath); - fs.rmdirSync(path.join(savePageDir, 'save_page_files')); - fs.rmdirSync(savePageDir); + fs.unlinkSync(savePageCssPath) + fs.unlinkSync(savePageJsPath) + fs.unlinkSync(savePageHtmlPath) + fs.rmdirSync(path.join(savePageDir, 'save_page_files')) + fs.rmdirSync(savePageDir) } catch (e) { // Ignore error } - }); + }) - it('should save page to disk', function(done) { - w.webContents.on('did-finish-load', function() { - w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function(error) { - assert.equal(error, null); - assert(fs.existsSync(savePageHtmlPath)); - assert(fs.existsSync(savePageJsPath)); - assert(fs.existsSync(savePageCssPath)); - done(); - }); - }); - w.loadURL("file://" + fixtures + "/pages/save_page/index.html"); - }); - }); + it('should save page to disk', function (done) { + w.webContents.on('did-finish-load', function () { + w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) { + assert.equal(error, null) + assert(fs.existsSync(savePageHtmlPath)) + assert(fs.existsSync(savePageJsPath)) + assert(fs.existsSync(savePageCssPath)) + done() + }) + }) + w.loadURL('file://' + fixtures + '/pages/save_page/index.html') + }) + }) - describe('BrowserWindow options argument is optional', function() { - it('should create a window with default size (800x600)', function() { - w.destroy(); - w = new BrowserWindow(); - var size = w.getSize(); - assert.equal(size[0], 800); - assert.equal(size[1], 600); - }); - }); + describe('BrowserWindow options argument is optional', function () { + it('should create a window with default size (800x600)', function () { + w.destroy() + w = new BrowserWindow() + var size = w.getSize() + assert.equal(size[0], 800) + assert.equal(size[1], 600) + }) + }) - describe('window states', function() { - describe('resizable state', function() { - it('can be changed with resizable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, resizable: false}); - assert.equal(w.isResizable(), false); - }); + describe('window states', function () { + describe('resizable state', function () { + it('can be changed with resizable option', function () { + w.destroy() + w = new BrowserWindow({show: false, resizable: false}) + assert.equal(w.isResizable(), false) + }) - it('can be changed with setResizable method', function() { - assert.equal(w.isResizable(), true); - w.setResizable(false); - assert.equal(w.isResizable(), false); - w.setResizable(true); - assert.equal(w.isResizable(), true); - }); - }); - }); + it('can be changed with setResizable method', function () { + assert.equal(w.isResizable(), true) + w.setResizable(false) + assert.equal(w.isResizable(), false) + w.setResizable(true) + assert.equal(w.isResizable(), true) + }) + }) + }) - describe('window states (excluding Linux)', function() { + describe('window states (excluding Linux)', function () { // Not implemented on Linux. if (process.platform == 'linux') - return; + return - describe('movable state', function() { - it('can be changed with movable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, movable: false}); - assert.equal(w.isMovable(), false); - }); + describe('movable state', function () { + it('can be changed with movable option', function () { + w.destroy() + w = new BrowserWindow({show: false, movable: false}) + assert.equal(w.isMovable(), false) + }) - it('can be changed with setMovable method', function() { - assert.equal(w.isMovable(), true); - w.setMovable(false); - assert.equal(w.isMovable(), false); - w.setMovable(true); - assert.equal(w.isMovable(), true); - }); - }); + it('can be changed with setMovable method', function () { + assert.equal(w.isMovable(), true) + w.setMovable(false) + assert.equal(w.isMovable(), false) + w.setMovable(true) + assert.equal(w.isMovable(), true) + }) + }) - describe('minimizable state', function() { - it('can be changed with minimizable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, minimizable: false}); - assert.equal(w.isMinimizable(), false); - }); + describe('minimizable state', function () { + it('can be changed with minimizable option', function () { + w.destroy() + w = new BrowserWindow({show: false, minimizable: false}) + assert.equal(w.isMinimizable(), false) + }) - it('can be changed with setMinimizable method', function() { - assert.equal(w.isMinimizable(), true); - w.setMinimizable(false); - assert.equal(w.isMinimizable(), false); - w.setMinimizable(true); - assert.equal(w.isMinimizable(), true); - }); - }); + it('can be changed with setMinimizable method', function () { + assert.equal(w.isMinimizable(), true) + w.setMinimizable(false) + assert.equal(w.isMinimizable(), false) + w.setMinimizable(true) + assert.equal(w.isMinimizable(), true) + }) + }) - describe('maximizable state', function() { - it('can be changed with maximizable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, maximizable: false}); - assert.equal(w.isMaximizable(), false); - }); + describe('maximizable state', function () { + it('can be changed with maximizable option', function () { + w.destroy() + w = new BrowserWindow({show: false, maximizable: false}) + assert.equal(w.isMaximizable(), false) + }) - it('can be changed with setMaximizable method', function() { - assert.equal(w.isMaximizable(), true); - w.setMaximizable(false); - assert.equal(w.isMaximizable(), false); - w.setMaximizable(true); - assert.equal(w.isMaximizable(), true); - }); + it('can be changed with setMaximizable method', function () { + assert.equal(w.isMaximizable(), true) + w.setMaximizable(false) + assert.equal(w.isMaximizable(), false) + w.setMaximizable(true) + assert.equal(w.isMaximizable(), true) + }) - it('is not affected when changing other states', function() { - w.setMaximizable(false); - assert.equal(w.isMaximizable(), false); - w.setMinimizable(false); - assert.equal(w.isMaximizable(), false); - w.setClosable(false); - assert.equal(w.isMaximizable(), false); - }); - }); + it('is not affected when changing other states', function () { + w.setMaximizable(false) + assert.equal(w.isMaximizable(), false) + w.setMinimizable(false) + assert.equal(w.isMaximizable(), false) + w.setClosable(false) + assert.equal(w.isMaximizable(), false) + }) + }) - describe('fullscreenable state', function() { + describe('fullscreenable state', function () { // Only implemented on OS X. if (process.platform != 'darwin') - return; + return - it('can be changed with fullscreenable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, fullscreenable: false}); - assert.equal(w.isFullScreenable(), false); - }); + it('can be changed with fullscreenable option', function () { + w.destroy() + w = new BrowserWindow({show: false, fullscreenable: false}) + assert.equal(w.isFullScreenable(), false) + }) - it('can be changed with setFullScreenable method', function() { - assert.equal(w.isFullScreenable(), true); - w.setFullScreenable(false); - assert.equal(w.isFullScreenable(), false); - w.setFullScreenable(true); - assert.equal(w.isFullScreenable(), true); - }); - }); + it('can be changed with setFullScreenable method', function () { + assert.equal(w.isFullScreenable(), true) + w.setFullScreenable(false) + assert.equal(w.isFullScreenable(), false) + w.setFullScreenable(true) + assert.equal(w.isFullScreenable(), true) + }) + }) - describe('closable state', function() { - it('can be changed with closable option', function() { - w.destroy(); - w = new BrowserWindow({show: false, closable: false}); - assert.equal(w.isClosable(), false); - }); + describe('closable state', function () { + it('can be changed with closable option', function () { + w.destroy() + w = new BrowserWindow({show: false, closable: false}) + assert.equal(w.isClosable(), false) + }) - it('can be changed with setClosable method', function() { - assert.equal(w.isClosable(), true); - w.setClosable(false); - assert.equal(w.isClosable(), false); - w.setClosable(true); - assert.equal(w.isClosable(), true); - }); - }); + it('can be changed with setClosable method', function () { + assert.equal(w.isClosable(), true) + w.setClosable(false) + assert.equal(w.isClosable(), false) + w.setClosable(true) + assert.equal(w.isClosable(), true) + }) + }) - describe('hasShadow state', function() { + describe('hasShadow state', function () { // On Window there is no shadow by default and it can not be changed // dynamically. - it('can be changed with hasShadow option', function() { - w.destroy(); - let hasShadow = process.platform == 'darwin' ? false : true; - w = new BrowserWindow({show: false, hasShadow: hasShadow}); - assert.equal(w.hasShadow(), hasShadow); - }); + it('can be changed with hasShadow option', function () { + w.destroy() + let hasShadow = process.platform == 'darwin' ? false : true + w = new BrowserWindow({show: false, hasShadow: hasShadow}) + assert.equal(w.hasShadow(), hasShadow) + }) - it('can be changed with setHasShadow method', function() { + it('can be changed with setHasShadow method', function () { if (process.platform != 'darwin') - return; + return - assert.equal(w.hasShadow(), true); - w.setHasShadow(false); - assert.equal(w.hasShadow(), false); - w.setHasShadow(true); - assert.equal(w.hasShadow(), true); - }); - }); - }); + assert.equal(w.hasShadow(), true) + w.setHasShadow(false) + assert.equal(w.hasShadow(), false) + w.setHasShadow(true) + assert.equal(w.hasShadow(), true) + }) + }) + }) - describe('window.webContents.send(channel, args...)', function() { - it('throws an error when the channel is missing', function() { - assert.throws(function() { - w.webContents.send(); - }, 'Missing required channel argument'); + describe('window.webContents.send(channel, args...)', function () { + it('throws an error when the channel is missing', function () { + assert.throws(function () { + w.webContents.send() + }, 'Missing required channel argument') - assert.throws(function() { - w.webContents.send(null); - }, 'Missing required channel argument'); - }); - }); + assert.throws(function () { + w.webContents.send(null) + }, 'Missing required channel argument') + }) + }) describe('dev tool extensions', function () { it('serializes the registered extensions on quit', function () { - var extensionName = 'foo'; - var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName); - var serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions'); + var extensionName = 'foo' + var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName) + var serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions') - BrowserWindow.addDevToolsExtension(extensionPath); - app.emit('will-quit'); - assert.deepEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath]); + BrowserWindow.addDevToolsExtension(extensionPath) + app.emit('will-quit') + assert.deepEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath]) - BrowserWindow.removeDevToolsExtension(extensionName); - app.emit('will-quit'); - assert.equal(fs.existsSync(serializedPath), false); - }); - }); + BrowserWindow.removeDevToolsExtension(extensionName) + app.emit('will-quit') + assert.equal(fs.existsSync(serializedPath), false) + }) + }) - describe('window.webContents.executeJavaScript', function() { - var expected = 'hello, world!'; - var code = '(() => \"' + expected + '\")()'; + describe('window.webContents.executeJavaScript', function () { + var expected = 'hello, world!' + var code = '(() => "' + expected + '")()' - it('doesnt throw when no calback is provided', function() { - const result = ipcRenderer.sendSync('executeJavaScript', code, false); - assert.equal(result, 'success'); - }); + it('doesnt throw when no calback is provided', function () { + const result = ipcRenderer.sendSync('executeJavaScript', code, false) + assert.equal(result, 'success') + }) - it('returns result when calback is provided', function(done) { - ipcRenderer.send('executeJavaScript', code, true); - ipcRenderer.once('executeJavaScript-response', function(event, result) { - assert.equal(result, expected); - done(); - }); - }); - }); + it('returns result when calback is provided', function (done) { + ipcRenderer.send('executeJavaScript', code, true) + ipcRenderer.once('executeJavaScript-response', function (event, result) { + assert.equal(result, expected) + done() + }) + }) + }) - describe('deprecated options', function() { - it('throws a deprecation error for option keys using hyphens instead of camel case', function() { + describe('deprecated options', function () { + it('throws a deprecation error for option keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({'min-width': 500}); - }, 'min-width is deprecated. Use minWidth instead.'); - }); + new BrowserWindow({'min-width': 500}) + }, 'min-width is deprecated. Use minWidth instead.') + }) - it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function() { + it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({webPreferences: {'node-integration': false}}); - }, 'node-integration is deprecated. Use nodeIntegration instead.'); - }); + new BrowserWindow({webPreferences: {'node-integration': false}}) + }, 'node-integration is deprecated. Use nodeIntegration instead.') + }) - it('throws a deprecation error for option keys that should be set on webPreferences', function() { + it('throws a deprecation error for option keys that should be set on webPreferences', function () { assert.throws(function () { - new BrowserWindow({zoomFactor: 1}); - }, 'options.zoomFactor is deprecated. Use options.webPreferences.zoomFactor instead.'); - }); - }); -}); + new BrowserWindow({zoomFactor: 1}) + }, 'options.zoomFactor is deprecated. Use options.webPreferences.zoomFactor instead.') + }) + }) +}) diff --git a/spec/api-clipboard-spec.js b/spec/api-clipboard-spec.js index 0b4a9f9521c..63f1d907e8a 100644 --- a/spec/api-clipboard-spec.js +++ b/spec/api-clipboard-spec.js @@ -1,63 +1,63 @@ -const assert = require('assert'); -const path = require('path'); +const assert = require('assert') +const path = require('path') -const clipboard = require('electron').clipboard; -const nativeImage = require('electron').nativeImage; +const clipboard = require('electron').clipboard +const nativeImage = require('electron').nativeImage -describe('clipboard module', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); +describe('clipboard module', function () { + var fixtures = path.resolve(__dirname, 'fixtures') - describe('clipboard.readImage()', function() { - it('returns NativeImage intance', function() { - var p = path.join(fixtures, 'assets', 'logo.png'); - var i = nativeImage.createFromPath(p); - clipboard.writeImage(p); - assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()); - }); - }); + describe('clipboard.readImage()', function () { + it('returns NativeImage intance', function () { + var p = path.join(fixtures, 'assets', 'logo.png') + var i = nativeImage.createFromPath(p) + clipboard.writeImage(p) + assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()) + }) + }) - describe('clipboard.readText()', function() { - it('returns unicode string correctly', function() { - var text = '千江有水千江月,万里无云万里天'; - clipboard.writeText(text); - assert.equal(clipboard.readText(), text); - }); - }); + describe('clipboard.readText()', function () { + it('returns unicode string correctly', function () { + var text = '千江有水千江月,万里无云万里天' + clipboard.writeText(text) + assert.equal(clipboard.readText(), text) + }) + }) - describe('clipboard.readHtml()', function() { - it('returns markup correctly', function() { - var text = 'Hi'; - var markup = process.platform === 'darwin' ? 'Hi' : process.platform === 'linux' ? 'Hi' : 'Hi'; - clipboard.writeHtml(text); - assert.equal(clipboard.readHtml(), markup); - }); - }); + describe('clipboard.readHtml()', function () { + it('returns markup correctly', function () { + var text = 'Hi' + var markup = process.platform === 'darwin' ? "Hi" : process.platform === 'linux' ? 'Hi' : 'Hi' + clipboard.writeHtml(text) + assert.equal(clipboard.readHtml(), markup) + }) + }) - describe('clipboard.readRtf', function() { - it('returns rtf text correctly', function() { - var rtf = "{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}"; - clipboard.writeRtf(rtf); - assert.equal(clipboard.readRtf(), rtf); - }); - }); + describe('clipboard.readRtf', function () { + it('returns rtf text correctly', function () { + var rtf = '{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}' + clipboard.writeRtf(rtf) + assert.equal(clipboard.readRtf(), rtf) + }) + }) - describe('clipboard.write()', function() { - it('returns data correctly', function() { - var text = 'test'; - var rtf = '{\\rtf1\\utf8 text}'; - var p = path.join(fixtures, 'assets', 'logo.png'); - var i = nativeImage.createFromPath(p); - var markup = process.platform === 'darwin' ? 'Hi' : process.platform === 'linux' ? 'Hi' : 'Hi'; + describe('clipboard.write()', function () { + it('returns data correctly', function () { + var text = 'test' + var rtf = '{\\rtf1\\utf8 text}' + var p = path.join(fixtures, 'assets', 'logo.png') + var i = nativeImage.createFromPath(p) + var markup = process.platform === 'darwin' ? "Hi" : process.platform === 'linux' ? 'Hi' : 'Hi' clipboard.write({ - text: "test", + text: 'test', html: 'Hi', rtf: '{\\rtf1\\utf8 text}', image: p - }); - assert.equal(clipboard.readText(), text); - assert.equal(clipboard.readHtml(), markup); - assert.equal(clipboard.readRtf(), rtf); - assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()); - }); - }); -}); + }) + assert.equal(clipboard.readText(), text) + assert.equal(clipboard.readHtml(), markup) + assert.equal(clipboard.readRtf(), rtf) + assert.equal(clipboard.readImage().toDataURL(), i.toDataURL()) + }) + }) +}) diff --git a/spec/api-crash-reporter-spec.js b/spec/api-crash-reporter-spec.js index 68dc1375fc3..708daeab956 100644 --- a/spec/api-crash-reporter-spec.js +++ b/spec/api-crash-reporter-spec.js @@ -1,93 +1,93 @@ -const assert = require('assert'); -const http = require('http'); -const multiparty = require('multiparty'); -const path = require('path'); -const url = require('url'); +const assert = require('assert') +const http = require('http') +const multiparty = require('multiparty') +const path = require('path') +const url = require('url') -const remote = require('electron').remote; -const app = remote.require('electron').app; -const crashReporter = remote.require('electron').crashReporter; -const BrowserWindow = remote.require('electron').BrowserWindow; +const remote = require('electron').remote +const app = remote.require('electron').app +const crashReporter = remote.require('electron').crashReporter +const BrowserWindow = remote.require('electron').BrowserWindow -describe('crash-reporter module', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); - var w = null; +describe('crash-reporter module', function () { + var fixtures = path.resolve(__dirname, 'fixtures') + var w = null - beforeEach(function() { + beforeEach(function () { w = new BrowserWindow({ show: false - }); - }); + }) + }) - afterEach(function() { - w.destroy(); - }); + afterEach(function () { + w.destroy() + }) if (process.mas) { - return; + return } - var isCI = remote.getGlobal('isCi'); + var isCI = remote.getGlobal('isCi') if (isCI) { - return; + return } - it('should send minidump when renderer crashes', function(done) { - this.timeout(120000); + it('should send minidump when renderer crashes', function (done) { + this.timeout(120000) - var called = false; - var server = http.createServer(function(req, res) { - server.close(); - var form = new multiparty.Form(); - form.parse(req, function(error, fields) { + var called = false + var server = http.createServer(function (req, res) { + server.close() + var form = new multiparty.Form() + form.parse(req, function (error, fields) { if (called) { - return; + return } - called = true; - assert.equal(fields['prod'], 'Electron'); - assert.equal(fields['ver'], process.versions['electron']); - assert.equal(fields['process_type'], 'renderer'); - assert.equal(fields['platform'], process.platform); - assert.equal(fields['extra1'], 'extra1'); - assert.equal(fields['extra2'], 'extra2'); - assert.equal(fields['_productName'], 'Zombies'); - assert.equal(fields['_companyName'], 'Umbrella Corporation'); - assert.equal(fields['_version'], app.getVersion()); - res.end('abc-123-def'); - done(); - }); - }); - var port = remote.process.port; - server.listen(port, '127.0.0.1', function() { - port = server.address().port; - remote.process.port = port; + called = true + assert.equal(fields['prod'], 'Electron') + assert.equal(fields['ver'], process.versions['electron']) + assert.equal(fields['process_type'], 'renderer') + assert.equal(fields['platform'], process.platform) + assert.equal(fields['extra1'], 'extra1') + assert.equal(fields['extra2'], 'extra2') + assert.equal(fields['_productName'], 'Zombies') + assert.equal(fields['_companyName'], 'Umbrella Corporation') + assert.equal(fields['_version'], app.getVersion()) + res.end('abc-123-def') + done() + }) + }) + var port = remote.process.port + server.listen(port, '127.0.0.1', function () { + port = server.address().port + remote.process.port = port const crashUrl = url.format({ protocol: 'file', pathname: path.join(fixtures, 'api', 'crash.html'), - search: "?port=" + port - }); + search: '?port=' + port + }) if (process.platform === 'darwin') { crashReporter.start({ companyName: 'Umbrella Corporation', - submitURL: "http://127.0.0.1:" + port - }); + submitURL: 'http://127.0.0.1:' + port + }) } - w.loadURL(crashUrl); - }); - }); + w.loadURL(crashUrl) + }) + }) - describe(".start(options)", function() { - it('requires that the companyName and submitURL options be specified', function() { - assert.throws(function() { + describe('.start(options)', function () { + it('requires that the companyName and submitURL options be specified', function () { + assert.throws(function () { crashReporter.start({ companyName: 'Missing submitURL' - }); - }); - assert.throws(function() { + }) + }) + assert.throws(function () { crashReporter.start({ submitURL: 'Missing companyName' - }); - }); - }); - }); -}); + }) + }) + }) + }) +}) diff --git a/spec/api-debugger-spec.js b/spec/api-debugger-spec.js index 56b642e76e4..1648ac1c3cd 100644 --- a/spec/api-debugger-spec.js +++ b/spec/api-debugger-spec.js @@ -1,133 +1,133 @@ -const assert = require('assert'); -const path = require('path'); -const BrowserWindow = require('electron').remote.BrowserWindow; +const assert = require('assert') +const path = require('path') +const BrowserWindow = require('electron').remote.BrowserWindow -describe('debugger module', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); - var w = null; +describe('debugger module', function () { + var fixtures = path.resolve(__dirname, 'fixtures') + var w = null - beforeEach(function() { + beforeEach(function () { if (w != null) { - w.destroy(); + w.destroy() } w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - }); + }) + }) - afterEach(function() { + afterEach(function () { if (w != null) { - w.destroy(); + w.destroy() } - w = null; - }); + w = null + }) - describe('debugger.attach', function() { - it('fails when devtools is already open', function(done) { - w.webContents.on('did-finish-load', function() { - w.webContents.openDevTools(); + describe('debugger.attach', function () { + it('fails when devtools is already open', function (done) { + w.webContents.on('did-finish-load', function () { + w.webContents.openDevTools() try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - assert(w.webContents.debugger.isAttached()); - done(); + assert(w.webContents.debugger.isAttached()) + done() } - }); - w.webContents.loadURL('file://' + path.join(fixtures, 'pages', 'a.html')); - }); + }) + w.webContents.loadURL('file://' + path.join(fixtures, 'pages', 'a.html')) + }) - it('fails when protocol version is not supported', function(done) { + it('fails when protocol version is not supported', function (done) { try { - w.webContents.debugger.attach("2.0"); + w.webContents.debugger.attach('2.0') } catch(err) { - assert(!w.webContents.debugger.isAttached()); - done(); + assert(!w.webContents.debugger.isAttached()) + done() } - }); + }) - it('attaches when no protocol version is specified', function(done) { + it('attaches when no protocol version is specified', function (done) { try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - done('unexpected error : ' + err); + done('unexpected error : ' + err) } - assert(w.webContents.debugger.isAttached()); - done(); - }); - }); + assert(w.webContents.debugger.isAttached()) + done() + }) + }) - describe('debugger.detach', function() { - it('fires detach event', function(done) { - w.webContents.debugger.on('detach', function(e, reason) { - assert.equal(reason, 'target closed'); - assert(!w.webContents.debugger.isAttached()); - done(); - }); + describe('debugger.detach', function () { + it('fires detach event', function (done) { + w.webContents.debugger.on('detach', function (e, reason) { + assert.equal(reason, 'target closed') + assert(!w.webContents.debugger.isAttached()) + done() + }) try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - done('unexpected error : ' + err); + done('unexpected error : ' + err) } - w.webContents.debugger.detach(); - }); - }); + w.webContents.debugger.detach() + }) + }) - describe('debugger.sendCommand', function() { - it('retuns response', function(done) { - w.webContents.loadURL('about:blank'); + describe('debugger.sendCommand', function () { + it('retuns response', function (done) { + w.webContents.loadURL('about:blank') try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - done('unexpected error : ' + err); + done('unexpected error : ' + err) + } + var callback = function (err, res) { + assert(!res.wasThrown) + assert.equal(res.result.value, 6) + w.webContents.debugger.detach() + done() } - var callback = function(err, res) { - assert(!res.wasThrown); - assert.equal(res.result.value, 6); - w.webContents.debugger.detach(); - done(); - }; const params = { - "expression": "4+2", - }; - w.webContents.debugger.sendCommand("Runtime.evaluate", params, callback); - }); + 'expression': '4+2', + } + w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback) + }) - it('fires message event', function(done) { + it('fires message event', function (done) { var url = process.platform != 'win32' ? 'file://' + path.join(fixtures, 'pages', 'a.html') : - 'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/'); - w.webContents.loadURL(url); + 'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/') + w.webContents.loadURL(url) try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - done('unexpected error : ' + err); + done('unexpected error : ' + err) } - w.webContents.debugger.on('message', function(e, method, params) { - if(method == "Console.messageAdded") { - assert.equal(params.message.type, 'log'); - assert.equal(params.message.url, url); - assert.equal(params.message.text, 'a'); - w.webContents.debugger.detach(); - done(); + w.webContents.debugger.on('message', function (e, method, params) { + if (method == 'Console.messageAdded') { + assert.equal(params.message.type, 'log') + assert.equal(params.message.url, url) + assert.equal(params.message.text, 'a') + w.webContents.debugger.detach() + done() } - }); - w.webContents.debugger.sendCommand("Console.enable"); - }); + }) + w.webContents.debugger.sendCommand('Console.enable') + }) - it('returns error message when command fails', function(done) { - w.webContents.loadURL('about:blank'); + it('returns error message when command fails', function (done) { + w.webContents.loadURL('about:blank') try { - w.webContents.debugger.attach(); + w.webContents.debugger.attach() } catch(err) { - done('unexpected error : ' + err); + done('unexpected error : ' + err) } - w.webContents.debugger.sendCommand("Test", function(err) { - assert.equal(err.message, '\'Test\' wasn\'t found'); - w.webContents.debugger.detach(); - done(); - }); - }); - }); -}); + w.webContents.debugger.sendCommand('Test', function (err) { + assert.equal(err.message, "'Test' wasn't found") + w.webContents.debugger.detach() + done() + }) + }) + }) +}) diff --git a/spec/api-deprecations-spec.js b/spec/api-deprecations-spec.js index 2f010059059..375de5895fe 100644 --- a/spec/api-deprecations-spec.js +++ b/spec/api-deprecations-spec.js @@ -1,27 +1,27 @@ -const assert = require('assert'); -const deprecations = require('electron').deprecations; +const assert = require('assert') +const deprecations = require('electron').deprecations -describe('deprecations', function() { - beforeEach(function() { - deprecations.setHandler(null); - process.throwDeprecation = true; - }); +describe('deprecations', function () { + beforeEach(function () { + deprecations.setHandler(null) + process.throwDeprecation = true + }) - it('allows a deprecation handler function to be specified', function() { - var messages = []; + it('allows a deprecation handler function to be specified', function () { + var messages = [] deprecations.setHandler(function (message) { - messages.push(message); - }); + messages.push(message) + }) - require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme'); + require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme') - assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']); - }); + assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']) + }) - it('throws an exception if no deprecation handler is specified', function() { - assert.throws(function() { - require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme'); - }, "registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead."); - }); -}); + it('throws an exception if no deprecation handler is specified', function () { + assert.throws(function () { + require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') + }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') + }) +}) diff --git a/spec/api-desktop-capturer-spec.js b/spec/api-desktop-capturer-spec.js index 02eda9003b8..9e85a48fbcc 100644 --- a/spec/api-desktop-capturer-spec.js +++ b/spec/api-desktop-capturer-spec.js @@ -1,27 +1,27 @@ -const assert = require('assert'); -const desktopCapturer = require('electron').desktopCapturer; +const assert = require('assert') +const desktopCapturer = require('electron').desktopCapturer -describe('desktopCapturer', function() { - it('should return a non-empty array of sources', function(done) { +describe('desktopCapturer', function () { + it('should return a non-empty array of sources', function (done) { desktopCapturer.getSources({ types: ['window', 'screen'] - }, function(error, sources) { - assert.equal(error, null); - assert.notEqual(sources.length, 0); - done(); - }); - }); + }, function (error, sources) { + assert.equal(error, null) + assert.notEqual(sources.length, 0) + done() + }) + }) - it('does not throw an error when called more than once (regression)', function(done) { - var callCount = 0; + it('does not throw an error when called more than once (regression)', function (done) { + var callCount = 0 var callback = function (error, sources) { - callCount++; - assert.equal(error, null); - assert.notEqual(sources.length, 0); - if (callCount === 2) done(); - }; + callCount++ + assert.equal(error, null) + assert.notEqual(sources.length, 0) + if (callCount === 2) done() + } - desktopCapturer.getSources({types: ['window', 'screen']}, callback); - desktopCapturer.getSources({types: ['window', 'screen']}, callback); - }); -}); + desktopCapturer.getSources({types: ['window', 'screen']}, callback) + desktopCapturer.getSources({types: ['window', 'screen']}, callback) + }) +}) diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 641d89270cb..862a6c99c17 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -1,210 +1,210 @@ -'use strict'; +'use strict' -const assert = require('assert'); -const path = require('path'); +const assert = require('assert') +const path = require('path') -const ipcRenderer = require('electron').ipcRenderer; -const remote = require('electron').remote; +const ipcRenderer = require('electron').ipcRenderer +const remote = require('electron').remote -const ipcMain = remote.require('electron').ipcMain; -const BrowserWindow = remote.require('electron').BrowserWindow; +const ipcMain = remote.require('electron').ipcMain +const BrowserWindow = remote.require('electron').BrowserWindow -const comparePaths = function(path1, path2) { +const comparePaths = function (path1, path2) { if (process.platform === 'win32') { - path1 = path1.toLowerCase(); - path2 = path2.toLowerCase(); + path1 = path1.toLowerCase() + path2 = path2.toLowerCase() } - assert.equal(path1, path2); -}; + assert.equal(path1, path2) +} -describe('ipc module', function() { - var fixtures = path.join(__dirname, 'fixtures'); +describe('ipc module', function () { + var fixtures = path.join(__dirname, 'fixtures') - describe('remote.require', function() { - it('should returns same object for the same module', function() { - var dialog1 = remote.require('electron'); - var dialog2 = remote.require('electron'); - assert.equal(dialog1, dialog2); - }); + describe('remote.require', function () { + it('should returns same object for the same module', function () { + var dialog1 = remote.require('electron') + var dialog2 = remote.require('electron') + assert.equal(dialog1, dialog2) + }) - it('should work when object contains id property', function() { - var a = remote.require(path.join(fixtures, 'module', 'id.js')); - assert.equal(a.id, 1127); - }); + it('should work when object contains id property', function () { + var a = remote.require(path.join(fixtures, 'module', 'id.js')) + assert.equal(a.id, 1127) + }) - it('should search module from the user app', function() { - comparePaths(path.normalize(remote.process.mainModule.filename), path.resolve(__dirname, 'static', 'main.js')); - comparePaths(path.normalize(remote.process.mainModule.paths[0]), path.resolve(__dirname, 'static', 'node_modules')); - }); - }); + it('should search module from the user app', function () { + comparePaths(path.normalize(remote.process.mainModule.filename), path.resolve(__dirname, 'static', 'main.js')) + comparePaths(path.normalize(remote.process.mainModule.paths[0]), path.resolve(__dirname, 'static', 'node_modules')) + }) + }) - describe('remote.createFunctionWithReturnValue', function() { - it('should be called in browser synchronously', function() { - var buf = new Buffer('test'); - var call = remote.require(path.join(fixtures, 'module', 'call.js')); - var result = call.call(remote.createFunctionWithReturnValue(buf)); - assert.equal(result.constructor.name, 'Buffer'); - }); - }); + describe('remote.createFunctionWithReturnValue', function () { + it('should be called in browser synchronously', function () { + var buf = new Buffer('test') + var call = remote.require(path.join(fixtures, 'module', 'call.js')) + var result = call.call(remote.createFunctionWithReturnValue(buf)) + assert.equal(result.constructor.name, 'Buffer') + }) + }) - describe('remote object in renderer', function() { - it('can change its properties', function() { - var property = remote.require(path.join(fixtures, 'module', 'property.js')); - assert.equal(property.property, 1127); - property.property = 1007; - assert.equal(property.property, 1007); - var property2 = remote.require(path.join(fixtures, 'module', 'property.js')); - assert.equal(property2.property, 1007); - property.property = 1127; - }); + describe('remote object in renderer', function () { + it('can change its properties', function () { + var property = remote.require(path.join(fixtures, 'module', 'property.js')) + assert.equal(property.property, 1127) + property.property = 1007 + assert.equal(property.property, 1007) + var property2 = remote.require(path.join(fixtures, 'module', 'property.js')) + assert.equal(property2.property, 1007) + property.property = 1127 + }) - it('can construct an object from its member', function() { - var call = remote.require(path.join(fixtures, 'module', 'call.js')); - var obj = new call.constructor; - assert.equal(obj.test, 'test'); - }); + it('can construct an object from its member', function () { + var call = remote.require(path.join(fixtures, 'module', 'call.js')) + var obj = new call.constructor + assert.equal(obj.test, 'test') + }) - it('can reassign and delete its member functions', function() { - var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')); - assert.equal(remoteFunctions.aFunction(), 1127); + it('can reassign and delete its member functions', function () { + var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')) + assert.equal(remoteFunctions.aFunction(), 1127) - remoteFunctions.aFunction = function () { return 1234; }; - assert.equal(remoteFunctions.aFunction(), 1234); + remoteFunctions.aFunction = function () { return 1234; } + assert.equal(remoteFunctions.aFunction(), 1234) - assert.equal(delete remoteFunctions.aFunction, true); - }); - }); + assert.equal(delete remoteFunctions.aFunction, true) + }) + }) - describe('remote value in browser', function() { - var print = path.join(fixtures, 'module', 'print_name.js'); + describe('remote value in browser', function () { + var print = path.join(fixtures, 'module', 'print_name.js') - it('keeps its constructor name for objects', function() { - var buf = new Buffer('test'); - var print_name = remote.require(print); - assert.equal(print_name.print(buf), 'Buffer'); - }); + it('keeps its constructor name for objects', function () { + var buf = new Buffer('test') + var print_name = remote.require(print) + assert.equal(print_name.print(buf), 'Buffer') + }) - it('supports instanceof Date', function() { - var now = new Date(); - var print_name = remote.require(print); - assert.equal(print_name.print(now), 'Date'); - assert.deepEqual(print_name.echo(now), now); - }); - }); + it('supports instanceof Date', function () { + var now = new Date() + var print_name = remote.require(print) + assert.equal(print_name.print(now), 'Date') + assert.deepEqual(print_name.echo(now), now) + }) + }) - describe('remote promise', function() { - it('can be used as promise in each side', function(done) { - var promise = remote.require(path.join(fixtures, 'module', 'promise.js')); - promise.twicePromise(Promise.resolve(1234)).then(function(value) { - assert.equal(value, 2468); - done(); - }); - }); - }); + describe('remote promise', function () { + it('can be used as promise in each side', function (done) { + var promise = remote.require(path.join(fixtures, 'module', 'promise.js')) + promise.twicePromise(Promise.resolve(1234)).then(function (value) { + assert.equal(value, 2468) + done() + }) + }) + }) - describe('remote webContents', function() { - it('can return same object with different getters', function() { - var contents1 = remote.getCurrentWindow().webContents; - var contents2 = remote.getCurrentWebContents(); - assert(contents1 == contents2); - }); - }); + describe('remote webContents', function () { + it('can return same object with different getters', function () { + var contents1 = remote.getCurrentWindow().webContents + var contents2 = remote.getCurrentWebContents() + assert(contents1 == contents2) + }) + }) - describe('remote class', function() { - let cl = remote.require(path.join(fixtures, 'module', 'class.js')); - let base = cl.base; - let derived = cl.derived; + describe('remote class', function () { + let cl = remote.require(path.join(fixtures, 'module', 'class.js')) + let base = cl.base + let derived = cl.derived - it('can get methods', function() { - assert.equal(base.method(), 'method'); - }); + it('can get methods', function () { + assert.equal(base.method(), 'method') + }) - it('can get properties', function() { - assert.equal(base.readonly, 'readonly'); - }); + it('can get properties', function () { + assert.equal(base.readonly, 'readonly') + }) - it('can change properties', function() { - assert.equal(base.value, 'old'); - base.value = 'new'; - assert.equal(base.value, 'new'); - base.value = 'old'; - }); + it('can change properties', function () { + assert.equal(base.value, 'old') + base.value = 'new' + assert.equal(base.value, 'new') + base.value = 'old' + }) - it('has unenumerable methods', function() { - assert(!base.hasOwnProperty('method')); - assert(Object.getPrototypeOf(base).hasOwnProperty('method')); - }); + it('has unenumerable methods', function () { + assert(!base.hasOwnProperty('method')) + assert(Object.getPrototypeOf(base).hasOwnProperty('method')) + }) - it('keeps prototype chain in derived class', function() { - assert.equal(derived.method(), 'method'); - assert.equal(derived.readonly, 'readonly'); - assert(!derived.hasOwnProperty('method')); - let proto = Object.getPrototypeOf(derived); - assert(!proto.hasOwnProperty('method')); - assert(Object.getPrototypeOf(proto).hasOwnProperty('method')); - }); - }); + it('keeps prototype chain in derived class', function () { + assert.equal(derived.method(), 'method') + assert.equal(derived.readonly, 'readonly') + assert(!derived.hasOwnProperty('method')) + let proto = Object.getPrototypeOf(derived) + assert(!proto.hasOwnProperty('method')) + assert(Object.getPrototypeOf(proto).hasOwnProperty('method')) + }) + }) - describe('ipc.sender.send', function() { - it('should work when sending an object containing id property', function(done) { + describe('ipc.sender.send', function () { + it('should work when sending an object containing id property', function (done) { var obj = { id: 1, name: 'ly' - }; - ipcRenderer.once('message', function(event, message) { - assert.deepEqual(message, obj); - done(); - }); - ipcRenderer.send('message', obj); - }); + } + ipcRenderer.once('message', function (event, message) { + assert.deepEqual(message, obj) + done() + }) + ipcRenderer.send('message', obj) + }) - it('can send instance of Date', function(done) { - const currentDate = new Date(); - ipcRenderer.once('message', function(event, value) { - assert.equal(value, currentDate.toISOString()); - done(); - }); - ipcRenderer.send('message', currentDate); - }); - }); + it('can send instance of Date', function (done) { + const currentDate = new Date() + ipcRenderer.once('message', function (event, value) { + assert.equal(value, currentDate.toISOString()) + done() + }) + ipcRenderer.send('message', currentDate) + }) + }) - describe('ipc.sendSync', function() { - it('can be replied by setting event.returnValue', function() { - var msg = ipcRenderer.sendSync('echo', 'test'); - assert.equal(msg, 'test'); - }); + describe('ipc.sendSync', function () { + it('can be replied by setting event.returnValue', function () { + var msg = ipcRenderer.sendSync('echo', 'test') + assert.equal(msg, 'test') + }) - it('does not crash when reply is not sent and browser is destroyed', function(done) { - this.timeout(10000); + it('does not crash when reply is not sent and browser is destroyed', function (done) { + this.timeout(10000) var w = new BrowserWindow({ show: false - }); - ipcMain.once('send-sync-message', function(event) { - event.returnValue = null; - w.destroy(); - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'send-sync-message.html')); - }); - }); + }) + ipcMain.once('send-sync-message', function (event) { + event.returnValue = null + w.destroy() + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'send-sync-message.html')) + }) + }) - describe('remote listeners', function() { - var w = null; + describe('remote listeners', function () { + var w = null - afterEach(function() { - w.destroy(); - }); + afterEach(function () { + w.destroy() + }) - it('can be added and removed correctly', function() { + it('can be added and removed correctly', function () { w = new BrowserWindow({ show: false - }); - var listener = function() {}; - w.on('test', listener); - assert.equal(w.listenerCount('test'), 1); - w.removeListener('test', listener); - assert.equal(w.listenerCount('test'), 0); - }); - }); -}); + }) + var listener = function () {} + w.on('test', listener) + assert.equal(w.listenerCount('test'), 1) + w.removeListener('test', listener) + assert.equal(w.listenerCount('test'), 0) + }) + }) +}) diff --git a/spec/api-menu-spec.js b/spec/api-menu-spec.js index bb8736e144f..6866448e0fd 100644 --- a/spec/api-menu-spec.js +++ b/spec/api-menu-spec.js @@ -1,25 +1,25 @@ -const assert = require('assert'); +const assert = require('assert') -const remote = require('electron').remote; -const ipcRenderer = require('electron').ipcRenderer; +const remote = require('electron').remote +const ipcRenderer = require('electron').ipcRenderer -const Menu = remote.require('electron').Menu; -const MenuItem = remote.require('electron').MenuItem; +const Menu = remote.require('electron').Menu +const MenuItem = remote.require('electron').MenuItem -describe('menu module', function() { - describe('Menu.buildFromTemplate', function() { - it('should be able to attach extra fields', function() { +describe('menu module', function () { + describe('Menu.buildFromTemplate', function () { + it('should be able to attach extra fields', function () { var menu = Menu.buildFromTemplate([ { label: 'text', extra: 'field' } - ]); - assert.equal(menu.items[0].extra, 'field'); - }); + ]) + assert.equal(menu.items[0].extra, 'field') + }) - it('does not modify the specified template', function() { - var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;"); + it('does not modify the specified template', function () { + var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;") assert.deepStrictEqual(template, [ { label: 'text', @@ -29,11 +29,11 @@ describe('menu module', function() { } ] } - ]); - }); + ]) + }) - it('does not throw exceptions for undefined/null values', function() { - assert.doesNotThrow(function() { + it('does not throw exceptions for undefined/null values', function () { + assert.doesNotThrow(function () { Menu.buildFromTemplate([ { label: 'text', @@ -43,12 +43,12 @@ describe('menu module', function() { label: 'text again', accelerator: null } - ]); - }); - }); + ]) + }) + }) - describe('Menu.buildFromTemplate should reorder based on item position specifiers', function() { - it('should position before existing item', function() { + describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () { + it('should position before existing item', function () { var menu = Menu.buildFromTemplate([ { label: '2', @@ -61,13 +61,13 @@ describe('menu module', function() { id: '1', position: 'before=2' } - ]); - assert.equal(menu.items[0].label, '1'); - assert.equal(menu.items[1].label, '2'); - assert.equal(menu.items[2].label, '3'); - }); + ]) + assert.equal(menu.items[0].label, '1') + assert.equal(menu.items[1].label, '2') + assert.equal(menu.items[2].label, '3') + }) - it('should position after existing item', function() { + it('should position after existing item', function () { var menu = Menu.buildFromTemplate([ { label: '1', @@ -80,13 +80,13 @@ describe('menu module', function() { id: '2', position: 'after=1' } - ]); - assert.equal(menu.items[0].label, '1'); - assert.equal(menu.items[1].label, '2'); - assert.equal(menu.items[2].label, '3'); - }); + ]) + assert.equal(menu.items[0].label, '1') + assert.equal(menu.items[1].label, '2') + assert.equal(menu.items[2].label, '3') + }) - it('should position at endof existing separator groups', function() { + it('should position at endof existing separator groups', function () { var menu = Menu.buildFromTemplate([ { type: 'separator', @@ -119,18 +119,18 @@ describe('menu module', function() { id: '3', position: 'endof=numbers' } - ]); - assert.equal(menu.items[0].id, 'numbers'); - assert.equal(menu.items[1].label, '1'); - assert.equal(menu.items[2].label, '2'); - assert.equal(menu.items[3].label, '3'); - assert.equal(menu.items[4].id, 'letters'); - assert.equal(menu.items[5].label, 'a'); - assert.equal(menu.items[6].label, 'b'); - assert.equal(menu.items[7].label, 'c'); - }); + ]) + assert.equal(menu.items[0].id, 'numbers') + assert.equal(menu.items[1].label, '1') + assert.equal(menu.items[2].label, '2') + assert.equal(menu.items[3].label, '3') + assert.equal(menu.items[4].id, 'letters') + assert.equal(menu.items[5].label, 'a') + assert.equal(menu.items[6].label, 'b') + assert.equal(menu.items[7].label, 'c') + }) - it('should create separator group if endof does not reference existing separator group', function() { + it('should create separator group if endof does not reference existing separator group', function () { var menu = Menu.buildFromTemplate([ { label: 'a', @@ -157,18 +157,18 @@ describe('menu module', function() { id: '3', position: 'endof=numbers' } - ]); - assert.equal(menu.items[0].id, 'letters'); - assert.equal(menu.items[1].label, 'a'); - assert.equal(menu.items[2].label, 'b'); - assert.equal(menu.items[3].label, 'c'); - assert.equal(menu.items[4].id, 'numbers'); - assert.equal(menu.items[5].label, '1'); - assert.equal(menu.items[6].label, '2'); - assert.equal(menu.items[7].label, '3'); - }); + ]) + assert.equal(menu.items[0].id, 'letters') + assert.equal(menu.items[1].label, 'a') + assert.equal(menu.items[2].label, 'b') + assert.equal(menu.items[3].label, 'c') + assert.equal(menu.items[4].id, 'numbers') + assert.equal(menu.items[5].label, '1') + assert.equal(menu.items[6].label, '2') + assert.equal(menu.items[7].label, '3') + }) - it('should continue inserting items at next index when no specifier is present', function() { + it('should continue inserting items at next index when no specifier is present', function () { var menu = Menu.buildFromTemplate([ { label: '4', @@ -187,18 +187,18 @@ describe('menu module', function() { label: '3', id: '3' } - ]); - assert.equal(menu.items[0].label, '1'); - assert.equal(menu.items[1].label, '2'); - assert.equal(menu.items[2].label, '3'); - assert.equal(menu.items[3].label, '4'); - assert.equal(menu.items[4].label, '5'); - }); - }); - }); + ]) + assert.equal(menu.items[0].label, '1') + assert.equal(menu.items[1].label, '2') + assert.equal(menu.items[2].label, '3') + assert.equal(menu.items[3].label, '4') + assert.equal(menu.items[4].label, '5') + }) + }) + }) - describe('Menu.insert', function() { - it('should store item in @items by its index', function() { + describe('Menu.insert', function () { + it('should store item in @items by its index', function () { var menu = Menu.buildFromTemplate([ { label: '1' @@ -207,156 +207,156 @@ describe('menu module', function() { }, { label: '3' } - ]); + ]) var item = new MenuItem({ label: 'inserted' - }); - menu.insert(1, item); - assert.equal(menu.items[0].label, '1'); - assert.equal(menu.items[1].label, 'inserted'); - assert.equal(menu.items[2].label, '2'); - assert.equal(menu.items[3].label, '3'); - }); - }); + }) + menu.insert(1, item) + assert.equal(menu.items[0].label, '1') + assert.equal(menu.items[1].label, 'inserted') + assert.equal(menu.items[2].label, '2') + assert.equal(menu.items[3].label, '3') + }) + }) - describe('MenuItem.click', function() { - it('should be called with the item object passed', function(done) { + describe('MenuItem.click', function () { + it('should be called with the item object passed', function (done) { var menu = Menu.buildFromTemplate([ { label: 'text', - click: function(item) { - assert.equal(item.constructor.name, 'MenuItem'); - assert.equal(item.label, 'text'); - done(); + click: function (item) { + assert.equal(item.constructor.name, 'MenuItem') + assert.equal(item.label, 'text') + done() } } - ]); - menu.delegate.executeCommand(menu.items[0].commandId); - }); - }); + ]) + menu.delegate.executeCommand(menu.items[0].commandId) + }) + }) - describe('MenuItem with checked property', function() { - it('clicking an checkbox item should flip the checked property', function() { + describe('MenuItem with checked property', function () { + it('clicking an checkbox item should flip the checked property', function () { var menu = Menu.buildFromTemplate([ { label: 'text', type: 'checkbox' } - ]); - assert.equal(menu.items[0].checked, false); - menu.delegate.executeCommand(menu.items[0].commandId); - assert.equal(menu.items[0].checked, true); - }); + ]) + assert.equal(menu.items[0].checked, false) + menu.delegate.executeCommand(menu.items[0].commandId) + assert.equal(menu.items[0].checked, true) + }) - it('clicking an radio item should always make checked property true', function() { + it('clicking an radio item should always make checked property true', function () { var menu = Menu.buildFromTemplate([ { label: 'text', type: 'radio' } - ]); - menu.delegate.executeCommand(menu.items[0].commandId); - assert.equal(menu.items[0].checked, true); - menu.delegate.executeCommand(menu.items[0].commandId); - assert.equal(menu.items[0].checked, true); - }); + ]) + menu.delegate.executeCommand(menu.items[0].commandId) + assert.equal(menu.items[0].checked, true) + menu.delegate.executeCommand(menu.items[0].commandId) + assert.equal(menu.items[0].checked, true) + }) - it('at least have one item checked in each group', function() { - var i, j, k, menu, template; - template = []; + it('at least have one item checked in each group', function () { + var i, j, k, menu, template + template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } template.push({ type: 'separator' - }); + }) for (i = k = 12; k <= 20; i = ++k) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } - menu = Menu.buildFromTemplate(template); - menu.delegate.menuWillShow(); - assert.equal(menu.items[0].checked, true); - assert.equal(menu.items[12].checked, true); - }); + menu = Menu.buildFromTemplate(template) + menu.delegate.menuWillShow() + assert.equal(menu.items[0].checked, true) + assert.equal(menu.items[12].checked, true) + }) - it('should assign groupId automatically', function() { - var groupId, i, j, k, l, m, menu, template; - template = []; + it('should assign groupId automatically', function () { + var groupId, i, j, k, l, m, menu, template + template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } template.push({ type: 'separator' - }); + }) for (i = k = 12; k <= 20; i = ++k) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } - menu = Menu.buildFromTemplate(template); - groupId = menu.items[0].groupId; + menu = Menu.buildFromTemplate(template) + groupId = menu.items[0].groupId for (i = l = 0; l <= 10; i = ++l) { - assert.equal(menu.items[i].groupId, groupId); + assert.equal(menu.items[i].groupId, groupId) } for (i = m = 12; m <= 20; i = ++m) { - assert.equal(menu.items[i].groupId, groupId + 1); + assert.equal(menu.items[i].groupId, groupId + 1) } - }); + }) - it("setting 'checked' should flip other items' 'checked' property", function() { - var i, j, k, l, m, menu, n, o, p, q, template; - template = []; + it("setting 'checked' should flip other items' 'checked' property", function () { + var i, j, k, l, m, menu, n, o, p, q, template + template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } template.push({ type: 'separator' - }); + }) for (i = k = 12; k <= 20; i = ++k) { template.push({ - label: "" + i, + label: '' + i, type: 'radio' - }); + }) } - menu = Menu.buildFromTemplate(template); + menu = Menu.buildFromTemplate(template) for (i = l = 0; l <= 10; i = ++l) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } - menu.items[0].checked = true; - assert.equal(menu.items[0].checked, true); + menu.items[0].checked = true + assert.equal(menu.items[0].checked, true) for (i = m = 1; m <= 10; i = ++m) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } - menu.items[10].checked = true; - assert.equal(menu.items[10].checked, true); + menu.items[10].checked = true + assert.equal(menu.items[10].checked, true) for (i = n = 0; n <= 9; i = ++n) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } for (i = o = 12; o <= 20; i = ++o) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } - menu.items[12].checked = true; - assert.equal(menu.items[10].checked, true); + menu.items[12].checked = true + assert.equal(menu.items[10].checked, true) for (i = p = 0; p <= 9; i = ++p) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } - assert.equal(menu.items[12].checked, true); + assert.equal(menu.items[12].checked, true) for (i = q = 13; q <= 20; i = ++q) { - assert.equal(menu.items[i].checked, false); + assert.equal(menu.items[i].checked, false) } - }); - }); -}); + }) + }) +}) diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index a7ee8be007e..6c5092cf7c3 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -1,51 +1,51 @@ -'use strict'; +'use strict' -const assert = require('assert'); -const nativeImage = require('electron').nativeImage; -const path = require('path'); +const assert = require('assert') +const nativeImage = require('electron').nativeImage +const path = require('path') describe('nativeImage module', () => { describe('createFromPath(path)', () => { it('returns an empty image for invalid paths', () => { - assert(nativeImage.createFromPath('').isEmpty()); - assert(nativeImage.createFromPath('does-not-exist.png').isEmpty()); - }); + assert(nativeImage.createFromPath('').isEmpty()) + assert(nativeImage.createFromPath('does-not-exist.png').isEmpty()) + }) it('loads images from paths relative to the current working directory', () => { - const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`; - const image = nativeImage.createFromPath(imagePath); - assert(!image.isEmpty()); - assert.equal(image.getSize().height, 190); - assert.equal(image.getSize().width, 538); - }); + const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}` + const image = nativeImage.createFromPath(imagePath) + assert(!image.isEmpty()) + assert.equal(image.getSize().height, 190) + assert.equal(image.getSize().width, 538) + }) it('loads images from paths with `.` segments', () => { - const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; - const image = nativeImage.createFromPath(imagePath); - assert(!image.isEmpty()); - assert.equal(image.getSize().height, 190); - assert.equal(image.getSize().width, 538); - }); + const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}` + const image = nativeImage.createFromPath(imagePath) + assert(!image.isEmpty()) + assert.equal(image.getSize().height, 190) + assert.equal(image.getSize().width, 538) + }) it('loads images from paths with `..` segments', () => { - const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; - const image = nativeImage.createFromPath(imagePath); - assert(!image.isEmpty()); - assert.equal(image.getSize().height, 190); - assert.equal(image.getSize().width, 538); - }); + const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}` + const image = nativeImage.createFromPath(imagePath) + assert(!image.isEmpty()) + assert.equal(image.getSize().height, 190) + assert.equal(image.getSize().width, 538) + }) it('Gets an NSImage pointer on OS X', () => { - if (process.platform !== 'darwin') return; + if (process.platform !== 'darwin') return - const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; - const image = nativeImage.createFromPath(imagePath); - const nsimage = image.getNativeHandle(); + const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}` + const image = nativeImage.createFromPath(imagePath) + const nsimage = image.getNativeHandle() - assert.equal(nsimage.length, 8); + assert.equal(nsimage.length, 8) // If all bytes are null, that's Bad - assert.equal(nsimage.reduce((acc,x) => acc || (x != 0), false), true); - }); - }); -}); + assert.equal(nsimage.reduce((acc, x) => acc || (x != 0), false), true) + }) + }) +}) diff --git a/spec/api-protocol-spec.js b/spec/api-protocol-spec.js index 215868bfdc8..001359d3850 100644 --- a/spec/api-protocol-spec.js +++ b/spec/api-protocol-spec.js @@ -1,772 +1,772 @@ -const assert = require('assert'); -const http = require('http'); -const path = require('path'); -const qs = require('querystring'); -const remote = require('electron').remote; -const protocol = remote.require('electron').protocol; +const assert = require('assert') +const http = require('http') +const path = require('path') +const qs = require('querystring') +const remote = require('electron').remote +const protocol = remote.require('electron').protocol -describe('protocol module', function() { - var protocolName = 'sp'; - var text = 'valar morghulis'; +describe('protocol module', function () { + var protocolName = 'sp' + var text = 'valar morghulis' var postData = { name: 'post test', type: 'string' - }; + } - afterEach(function(done) { - protocol.unregisterProtocol(protocolName, function() { - protocol.uninterceptProtocol('http', function() { - done(); - }); - }); - }); + afterEach(function (done) { + protocol.unregisterProtocol(protocolName, function () { + protocol.uninterceptProtocol('http', function () { + done() + }) + }) + }) - describe('protocol.register(Any)Protocol', function() { - var emptyHandler = function(request, callback) { - callback(); - }; + describe('protocol.register(Any)Protocol', function () { + var emptyHandler = function (request, callback) { + callback() + } - it('throws error when scheme is already registered', function(done) { - protocol.registerStringProtocol(protocolName, emptyHandler, function(error) { - assert.equal(error, null); - protocol.registerBufferProtocol(protocolName, emptyHandler, function(error) { - assert.notEqual(error, null); - done(); - }); - }); - }); + it('throws error when scheme is already registered', function (done) { + protocol.registerStringProtocol(protocolName, emptyHandler, function (error) { + assert.equal(error, null) + protocol.registerBufferProtocol(protocolName, emptyHandler, function (error) { + assert.notEqual(error, null) + done() + }) + }) + }) - it('does not crash when handler is called twice', function(done) { - var doubleHandler = function(request, callback) { + it('does not crash when handler is called twice', function (done) { + var doubleHandler = function (request, callback) { try { - callback(text); - callback(); + callback(text) + callback() } catch (error) { // Ignore error } - }; - protocol.registerStringProtocol(protocolName, doubleHandler, function(error) { + } + protocol.registerStringProtocol(protocolName, doubleHandler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('sends error when callback is called with nothing', function(done) { - protocol.registerBufferProtocol(protocolName, emptyHandler, function(error) { + it('sends error when callback is called with nothing', function (done) { + protocol.registerBufferProtocol(protocolName, emptyHandler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - return done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + return done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - return done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + return done() } - }); - }); - }); + }) + }) + }) - it('does not crash when callback is called in next tick', function(done) { - var handler = function(request, callback) { - setImmediate(function() { - callback(text); - }); - }; - protocol.registerStringProtocol(protocolName, handler, function(error) { + it('does not crash when callback is called in next tick', function (done) { + var handler = function (request, callback) { + setImmediate(function () { + callback(text) + }) + } + protocol.registerStringProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - }); + }) + }) + }) + }) - describe('protocol.unregisterProtocol', function() { - it('returns error when scheme does not exist', function(done) { - protocol.unregisterProtocol('not-exist', function(error) { - assert.notEqual(error, null); - done(); - }); - }); - }); + describe('protocol.unregisterProtocol', function () { + it('returns error when scheme does not exist', function (done) { + protocol.unregisterProtocol('not-exist', function (error) { + assert.notEqual(error, null) + done() + }) + }) + }) - describe('protocol.registerStringProtocol', function() { - it('sends string as response', function(done) { - var handler = function(request, callback) { - callback(text); - }; - protocol.registerStringProtocol(protocolName, handler, function(error) { + describe('protocol.registerStringProtocol', function () { + it('sends string as response', function (done) { + var handler = function (request, callback) { + callback(text) + } + protocol.registerStringProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('sets Access-Control-Allow-Origin', function(done) { - var handler = function(request, callback) { - callback(text); - }; - protocol.registerStringProtocol(protocolName, handler, function(error) { + it('sets Access-Control-Allow-Origin', function (done) { + var handler = function (request, callback) { + callback(text) + } + protocol.registerStringProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data, status, request) { - assert.equal(data, text); - assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*'); - done(); + url: protocolName + '://fake-host', + success: function (data, status, request) { + assert.equal(data, text) + assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('sends object as response', function(done) { - var handler = function(request, callback) { + it('sends object as response', function (done) { + var handler = function (request, callback) { callback({ data: text, mimeType: 'text/html' - }); - }; - protocol.registerStringProtocol(protocolName, handler, function(error) { + }) + } + protocol.registerStringProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('fails when sending object other than string', function(done) { - var handler = function(request, callback) { - callback(new Date); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + it('fails when sending object other than string', function (done) { + var handler = function (request, callback) { + callback(new Date) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); - }); + }) + }) + }) + }) - describe('protocol.registerBufferProtocol', function() { - var buffer = new Buffer(text); + describe('protocol.registerBufferProtocol', function () { + var buffer = new Buffer(text) - it('sends Buffer as response', function(done) { - var handler = function(request, callback) { - callback(buffer); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + it('sends Buffer as response', function (done) { + var handler = function (request, callback) { + callback(buffer) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('sets Access-Control-Allow-Origin', function(done) { - var handler = function(request, callback) { - callback(buffer); - }; + it('sets Access-Control-Allow-Origin', function (done) { + var handler = function (request, callback) { + callback(buffer) + } - protocol.registerBufferProtocol(protocolName, handler, function(error) { + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data, status, request) { - assert.equal(data, text); - assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*'); - done(); + url: protocolName + '://fake-host', + success: function (data, status, request) { + assert.equal(data, text) + assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('sends object as response', function(done) { - var handler = function(request, callback) { + it('sends object as response', function (done) { + var handler = function (request, callback) { callback({ data: buffer, mimeType: 'text/html' - }); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + }) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('fails when sending string', function(done) { - var handler = function(request, callback) { - callback(text); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + it('fails when sending string', function (done) { + var handler = function (request, callback) { + callback(text) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); - }); + }) + }) + }) + }) - describe('protocol.registerFileProtocol', function() { - var filePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'file1'); - var fileContent = require('fs').readFileSync(filePath); - var normalPath = path.join(__dirname, 'fixtures', 'pages', 'a.html'); - var normalContent = require('fs').readFileSync(normalPath); + describe('protocol.registerFileProtocol', function () { + var filePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'file1') + var fileContent = require('fs').readFileSync(filePath) + var normalPath = path.join(__dirname, 'fixtures', 'pages', 'a.html') + var normalContent = require('fs').readFileSync(normalPath) - it('sends file path as response', function(done) { - var handler = function(request, callback) { - callback(filePath); - }; - protocol.registerFileProtocol(protocolName, handler, function(error) { + it('sends file path as response', function (done) { + var handler = function (request, callback) { + callback(filePath) + } + protocol.registerFileProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, String(fileContent)); - return done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, String(fileContent)) + return done() }, - error: function(xhr, errorType, error) { - return done(error); + error: function (xhr, errorType, error) { + return done(error) } - }); - }); - }); + }) + }) + }) - it('sets Access-Control-Allow-Origin', function(done) { - var handler = function(request, callback) { - callback(filePath); - }; - protocol.registerFileProtocol(protocolName, handler, function(error) { + it('sets Access-Control-Allow-Origin', function (done) { + var handler = function (request, callback) { + callback(filePath) + } + protocol.registerFileProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data, status, request) { - assert.equal(data, String(fileContent)); - assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*'); - done(); + url: protocolName + '://fake-host', + success: function (data, status, request) { + assert.equal(data, String(fileContent)) + assert.equal(request.getResponseHeader('Access-Control-Allow-Origin'), '*') + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - it('sends object as response', function(done) { - var handler = function(request, callback) { + }) + }) + }) + it('sends object as response', function (done) { + var handler = function (request, callback) { callback({ path: filePath - }); - }; - protocol.registerFileProtocol(protocolName, handler, function(error) { + }) + } + protocol.registerFileProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, String(fileContent)); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, String(fileContent)) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('can send normal file', function(done) { - var handler = function(request, callback) { - callback(normalPath); - }; + it('can send normal file', function (done) { + var handler = function (request, callback) { + callback(normalPath) + } - protocol.registerFileProtocol(protocolName, handler, function(error) { + protocol.registerFileProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, String(normalContent)); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, String(normalContent)) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('fails when sending unexist-file', function(done) { - var fakeFilePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'not-exist'); - var handler = function(request, callback) { - callback(fakeFilePath); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + it('fails when sending unexist-file', function (done) { + var fakeFilePath = path.join(__dirname, 'fixtures', 'asar', 'a.asar', 'not-exist') + var handler = function (request, callback) { + callback(fakeFilePath) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); + }) + }) + }) - it('fails when sending unsupported content', function(done) { - var handler = function(request, callback) { - callback(new Date); - }; - protocol.registerBufferProtocol(protocolName, handler, function(error) { + it('fails when sending unsupported content', function (done) { + var handler = function (request, callback) { + callback(new Date) + } + protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); - }); + }) + }) + }) + }) - describe('protocol.registerHttpProtocol', function() { - it('sends url as response', function(done) { - var server = http.createServer(function(req, res) { - assert.notEqual(req.headers.accept, ''); - res.end(text); - server.close(); - }); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - var url = "http://127.0.0.1:" + port; - var handler = function(request, callback) { + describe('protocol.registerHttpProtocol', function () { + it('sends url as response', function (done) { + var server = http.createServer(function (req, res) { + assert.notEqual(req.headers.accept, '') + res.end(text) + server.close() + }) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + var url = 'http://127.0.0.1:' + port + var handler = function (request, callback) { callback({ url: url - }); - }; - protocol.registerHttpProtocol(protocolName, handler, function(error) { + }) + } + protocol.registerHttpProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function(data) { - assert.equal(data, text); - done(); + url: protocolName + '://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - }); + }) + }) + }) + }) - it('fails when sending invalid url', function(done) { - var handler = function(request, callback) { + it('fails when sending invalid url', function (done) { + var handler = function (request, callback) { callback({ url: 'url' - }); - }; - protocol.registerHttpProtocol(protocolName, handler, function(error) { + }) + } + protocol.registerHttpProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); + }) + }) + }) - it('fails when sending unsupported content', function(done) { - var handler = function(request, callback) { - callback(new Date); - }; - protocol.registerHttpProtocol(protocolName, handler, function(error) { + it('fails when sending unsupported content', function (done) { + var handler = function (request, callback) { + callback(new Date) + } + protocol.registerHttpProtocol(protocolName, handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: protocolName + "://fake-host", - success: function() { - done('request succeeded but it should not'); + url: protocolName + '://fake-host', + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); - }); + }) + }) + }) + }) - describe('protocol.isProtocolHandled', function() { - it('returns true for file:', function(done) { - protocol.isProtocolHandled('file', function(result) { - assert.equal(result, true); - done(); - }); - }); + describe('protocol.isProtocolHandled', function () { + it('returns true for file:', function (done) { + protocol.isProtocolHandled('file', function (result) { + assert.equal(result, true) + done() + }) + }) - it('returns true for http:', function(done) { - protocol.isProtocolHandled('http', function(result) { - assert.equal(result, true); - done(); - }); - }); + it('returns true for http:', function (done) { + protocol.isProtocolHandled('http', function (result) { + assert.equal(result, true) + done() + }) + }) - it('returns true for https:', function(done) { - protocol.isProtocolHandled('https', function(result) { - assert.equal(result, true); - done(); - }); - }); + it('returns true for https:', function (done) { + protocol.isProtocolHandled('https', function (result) { + assert.equal(result, true) + done() + }) + }) - it('returns false when scheme is not registred', function(done) { - protocol.isProtocolHandled('no-exist', function(result) { - assert.equal(result, false); - done(); - }); - }); + it('returns false when scheme is not registred', function (done) { + protocol.isProtocolHandled('no-exist', function (result) { + assert.equal(result, false) + done() + }) + }) - it('returns true for custom protocol', function(done) { - var emptyHandler = function(request, callback) { - callback(); - }; - protocol.registerStringProtocol(protocolName, emptyHandler, function(error) { - assert.equal(error, null); - protocol.isProtocolHandled(protocolName, function(result) { - assert.equal(result, true); - done(); - }); - }); - }); + it('returns true for custom protocol', function (done) { + var emptyHandler = function (request, callback) { + callback() + } + protocol.registerStringProtocol(protocolName, emptyHandler, function (error) { + assert.equal(error, null) + protocol.isProtocolHandled(protocolName, function (result) { + assert.equal(result, true) + done() + }) + }) + }) - it('returns true for intercepted protocol', function(done) { - var emptyHandler = function(request, callback) { - callback(); - }; - protocol.interceptStringProtocol('http', emptyHandler, function(error) { - assert.equal(error, null); - protocol.isProtocolHandled('http', function(result) { - assert.equal(result, true); - done(); - }); - }); - }); - }); + it('returns true for intercepted protocol', function (done) { + var emptyHandler = function (request, callback) { + callback() + } + protocol.interceptStringProtocol('http', emptyHandler, function (error) { + assert.equal(error, null) + protocol.isProtocolHandled('http', function (result) { + assert.equal(result, true) + done() + }) + }) + }) + }) - describe('protocol.intercept(Any)Protocol', function() { - var emptyHandler = function(request, callback) { - callback(); - }; + describe('protocol.intercept(Any)Protocol', function () { + var emptyHandler = function (request, callback) { + callback() + } - it('throws error when scheme is already intercepted', function(done) { - protocol.interceptStringProtocol('http', emptyHandler, function(error) { - assert.equal(error, null); - protocol.interceptBufferProtocol('http', emptyHandler, function(error) { - assert.notEqual(error, null); - done(); - }); - }); - }); + it('throws error when scheme is already intercepted', function (done) { + protocol.interceptStringProtocol('http', emptyHandler, function (error) { + assert.equal(error, null) + protocol.interceptBufferProtocol('http', emptyHandler, function (error) { + assert.notEqual(error, null) + done() + }) + }) + }) - it('does not crash when handler is called twice', function(done) { - var doubleHandler = function(request, callback) { + it('does not crash when handler is called twice', function (done) { + var doubleHandler = function (request, callback) { try { - callback(text); - callback(); + callback(text) + callback() } catch (error) { // Ignore error } - }; - protocol.interceptStringProtocol('http', doubleHandler, function(error) { - if (error) { - return done(error); - } - $.ajax({ - url: 'http://fake-host', - success: function(data) { - assert.equal(data, text); - done(); - }, - error: function(xhr, errorType, error) { - done(error); - } - }); - }); - }); - - it('sends error when callback is called with nothing', function(done) { - if (process.env.TRAVIS === 'true') { - return done(); } - protocol.interceptBufferProtocol('http', emptyHandler, function(error) { + protocol.interceptStringProtocol('http', doubleHandler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ url: 'http://fake-host', - success: function() { - done('request succeeded but it should not'); + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType) { - assert.equal(errorType, 'error'); - done(); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - }); + }) + }) + }) - describe('protocol.interceptStringProtocol', function() { - it('can intercept http protocol', function(done) { - var handler = function(request, callback) { - callback(text); - }; - protocol.interceptStringProtocol('http', handler, function(error) { + it('sends error when callback is called with nothing', function (done) { + if (process.env.TRAVIS === 'true') { + return done() + } + protocol.interceptBufferProtocol('http', emptyHandler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ url: 'http://fake-host', - success: function(data) { - assert.equal(data, text); - done(); + success: function () { + done('request succeeded but it should not') }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType) { + assert.equal(errorType, 'error') + done() } - }); - }); - }); + }) + }) + }) + }) - it('can set content-type', function(done) { - var handler = function(request, callback) { + describe('protocol.interceptStringProtocol', function () { + it('can intercept http protocol', function (done) { + var handler = function (request, callback) { + callback(text) + } + protocol.interceptStringProtocol('http', handler, function (error) { + if (error) { + return done(error) + } + $.ajax({ + url: 'http://fake-host', + success: function (data) { + assert.equal(data, text) + done() + }, + error: function (xhr, errorType, error) { + done(error) + } + }) + }) + }) + + it('can set content-type', function (done) { + var handler = function (request, callback) { callback({ mimeType: 'application/json', data: '{"value": 1}' - }); - }; - protocol.interceptStringProtocol('http', handler, function(error) { + }) + } + protocol.interceptStringProtocol('http', handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ url: 'http://fake-host', - success: function(data) { - assert.equal(typeof data, 'object'); - assert.equal(data.value, 1); - done(); + success: function (data) { + assert.equal(typeof data, 'object') + assert.equal(data.value, 1) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) - it('can receive post data', function(done) { - var handler = function(request, callback) { - var uploadData = request.uploadData[0].bytes.toString(); + it('can receive post data', function (done) { + var handler = function (request, callback) { + var uploadData = request.uploadData[0].bytes.toString() callback({ data: uploadData - }); - }; - protocol.interceptStringProtocol('http', handler, function(error) { + }) + } + protocol.interceptStringProtocol('http', handler, function (error) { if (error) { - return done(error); - } - $.ajax({ - url: "http://fake-host", - type: "POST", - data: postData, - success: function(data) { - assert.deepEqual(qs.parse(data), postData); - done(); - }, - error: function(xhr, errorType, error) { - done(error); - } - }); - }); - }); - }); - - describe('protocol.interceptBufferProtocol', function() { - it('can intercept http protocol', function(done) { - var handler = function(request, callback) { - callback(new Buffer(text)); - }; - protocol.interceptBufferProtocol('http', handler, function(error) { - if (error) { - return done(error); + return done(error) } $.ajax({ url: 'http://fake-host', - success: function(data) { - assert.equal(data, text); - done(); + type: 'POST', + data: postData, + success: function (data) { + assert.deepEqual(qs.parse(data), postData) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); + }) + }) + }) + }) - it('can receive post data', function(done) { - var handler = function(request, callback) { - var uploadData = request.uploadData[0].bytes; - callback(uploadData); - }; - protocol.interceptBufferProtocol('http', handler, function(error) { + describe('protocol.interceptBufferProtocol', function () { + it('can intercept http protocol', function (done) { + var handler = function (request, callback) { + callback(new Buffer(text)) + } + protocol.interceptBufferProtocol('http', handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: "http://fake-host", - type: "POST", - data: postData, - success: function(data) { - assert.equal(data, $.param(postData)); - done(); + url: 'http://fake-host', + success: function (data) { + assert.equal(data, text) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - }); + }) + }) + }) - describe('protocol.interceptHttpProtocol', function() { - it('can send POST request', function(done) { - var server = http.createServer(function(req, res) { - var body = ''; - req.on('data', function(chunk) { - body += chunk; - }); - req.on('end', function() { - res.end(body); - }); - server.close(); - }); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - var url = "http://127.0.0.1:" + port; - var handler = function(request, callback) { + it('can receive post data', function (done) { + var handler = function (request, callback) { + var uploadData = request.uploadData[0].bytes + callback(uploadData) + } + protocol.interceptBufferProtocol('http', handler, function (error) { + if (error) { + return done(error) + } + $.ajax({ + url: 'http://fake-host', + type: 'POST', + data: postData, + success: function (data) { + assert.equal(data, $.param(postData)) + done() + }, + error: function (xhr, errorType, error) { + done(error) + } + }) + }) + }) + }) + + describe('protocol.interceptHttpProtocol', function () { + it('can send POST request', function (done) { + var server = http.createServer(function (req, res) { + var body = '' + req.on('data', function (chunk) { + body += chunk + }) + req.on('end', function () { + res.end(body) + }) + server.close() + }) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + var url = 'http://127.0.0.1:' + port + var handler = function (request, callback) { var data = { url: url, method: 'POST', @@ -775,43 +775,43 @@ describe('protocol module', function() { data: request.uploadData[0].bytes.toString() }, session: null - }; - callback(data); - }; - protocol.interceptHttpProtocol('http', handler, function(error) { + } + callback(data) + } + protocol.interceptHttpProtocol('http', handler, function (error) { if (error) { - return done(error); + return done(error) } $.ajax({ - url: "http://fake-host", - type: "POST", + url: 'http://fake-host', + type: 'POST', data: postData, - success: function(data) { - assert.deepEqual(qs.parse(data), postData); - done(); + success: function (data) { + assert.deepEqual(qs.parse(data), postData) + done() }, - error: function(xhr, errorType, error) { - done(error); + error: function (xhr, errorType, error) { + done(error) } - }); - }); - }); - }); - }); + }) + }) + }) + }) + }) - describe('protocol.uninterceptProtocol', function() { - it('returns error when scheme does not exist', function(done) { - protocol.uninterceptProtocol('not-exist', function(error) { - assert.notEqual(error, null); - done(); - }); - }); + describe('protocol.uninterceptProtocol', function () { + it('returns error when scheme does not exist', function (done) { + protocol.uninterceptProtocol('not-exist', function (error) { + assert.notEqual(error, null) + done() + }) + }) - it('returns error when scheme is not intercepted', function(done) { - protocol.uninterceptProtocol('http', function(error) { - assert.notEqual(error, null); - done(); - }); - }); - }); -}); + it('returns error when scheme is not intercepted', function (done) { + protocol.uninterceptProtocol('http', function (error) { + assert.notEqual(error, null) + done() + }) + }) + }) +}) diff --git a/spec/api-screen-spec.js b/spec/api-screen-spec.js index 34828e863e8..8c4f4305baf 100644 --- a/spec/api-screen-spec.js +++ b/spec/api-screen-spec.js @@ -1,21 +1,21 @@ -const assert = require('assert'); -const screen = require('electron').screen; +const assert = require('assert') +const screen = require('electron').screen -describe('screen module', function() { - describe('screen.getCursorScreenPoint()', function() { - it('returns a point object', function() { - var point = screen.getCursorScreenPoint(); - assert.equal(typeof point.x, 'number'); - assert.equal(typeof point.y, 'number'); - }); - }); +describe('screen module', function () { + describe('screen.getCursorScreenPoint()', function () { + it('returns a point object', function () { + var point = screen.getCursorScreenPoint() + assert.equal(typeof point.x, 'number') + assert.equal(typeof point.y, 'number') + }) + }) - describe('screen.getPrimaryDisplay()', function() { - it('returns a display object', function() { - var display = screen.getPrimaryDisplay(); - assert.equal(typeof display.scaleFactor, 'number'); - assert(display.size.width > 0); - assert(display.size.height > 0); - }); - }); -}); + describe('screen.getPrimaryDisplay()', function () { + it('returns a display object', function () { + var display = screen.getPrimaryDisplay() + assert.equal(typeof display.scaleFactor, 'number') + assert(display.size.width > 0) + assert(display.size.height > 0) + }) + }) +}) diff --git a/spec/api-session-spec.js b/spec/api-session-spec.js index 9fedcc29e77..2f4a50f69e5 100644 --- a/spec/api-session-spec.js +++ b/spec/api-session-spec.js @@ -1,265 +1,265 @@ -const assert = require('assert'); -const http = require('http'); -const path = require('path'); -const fs = require('fs'); +const assert = require('assert') +const http = require('http') +const path = require('path') +const fs = require('fs') -const ipcRenderer = require('electron').ipcRenderer; -const remote = require('electron').remote; +const ipcRenderer = require('electron').ipcRenderer +const remote = require('electron').remote -const ipcMain = remote.ipcMain; -const session = remote.session; -const BrowserWindow = remote.BrowserWindow; +const ipcMain = remote.ipcMain +const session = remote.session +const BrowserWindow = remote.BrowserWindow -describe('session module', function() { - this.timeout(10000); +describe('session module', function () { + this.timeout(10000) - var fixtures = path.resolve(__dirname, 'fixtures'); - var w = null; - var url = "http://127.0.0.1"; + var fixtures = path.resolve(__dirname, 'fixtures') + var w = null + var url = 'http://127.0.0.1' - beforeEach(function() { + beforeEach(function () { w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - }); + }) + }) - afterEach(function() { - w.destroy(); - }); + afterEach(function () { + w.destroy() + }) - describe('session.cookies', function() { - it('should get cookies', function(done) { - var server = http.createServer(function(req, res) { - res.setHeader('Set-Cookie', ['0=0']); - res.end('finished'); - server.close(); - }); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - w.loadURL(url + ":" + port); - w.webContents.on('did-finish-load', function() { + describe('session.cookies', function () { + it('should get cookies', function (done) { + var server = http.createServer(function (req, res) { + res.setHeader('Set-Cookie', ['0=0']) + res.end('finished') + server.close() + }) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + w.loadURL(url + ':' + port) + w.webContents.on('did-finish-load', function () { w.webContents.session.cookies.get({ url: url - }, function(error, list) { - var cookie, i, len; + }, function (error, list) { + var cookie, i, len if (error) { - return done(error); + return done(error) } for (i = 0, len = list.length; i < len; i++) { - cookie = list[i]; + cookie = list[i] if (cookie.name === '0') { if (cookie.value === '0') { - return done(); + return done() } else { - return done("cookie value is " + cookie.value + " while expecting 0"); + return done('cookie value is ' + cookie.value + ' while expecting 0') } } } - done('Can not find cookie'); - }); - }); - }); - }); + done('Can not find cookie') + }) + }) + }) + }) - it('should over-write the existent cookie', function(done) { + it('should over-write the existent cookie', function (done) { session.defaultSession.cookies.set({ url: url, name: '1', value: '1' - }, function(error) { + }, function (error) { if (error) { - return done(error); + return done(error) } session.defaultSession.cookies.get({ url: url - }, function(error, list) { - var cookie, i, len; + }, function (error, list) { + var cookie, i, len if (error) { - return done(error); + return done(error) } for (i = 0, len = list.length; i < len; i++) { - cookie = list[i]; + cookie = list[i] if (cookie.name === '1') { if (cookie.value === '1') { - return done(); + return done() } else { - return done("cookie value is " + cookie.value + " while expecting 1"); + return done('cookie value is ' + cookie.value + ' while expecting 1') } } } - done('Can not find cookie'); - }); - }); - }); + done('Can not find cookie') + }) + }) + }) - it('should remove cookies', function(done) { + it('should remove cookies', function (done) { session.defaultSession.cookies.set({ url: url, name: '2', value: '2' - }, function(error) { + }, function (error) { if (error) { - return done(error); + return done(error) } - session.defaultSession.cookies.remove(url, '2', function() { + session.defaultSession.cookies.remove(url, '2', function () { session.defaultSession.cookies.get({ url: url - }, function(error, list) { - var cookie, i, len; + }, function (error, list) { + var cookie, i, len if (error) { - return done(error); + return done(error) } for (i = 0, len = list.length; i < len; i++) { - cookie = list[i]; + cookie = list[i] if (cookie.name === '2') { - return done('Cookie not deleted'); + return done('Cookie not deleted') } } - done(); - }); - }); - }); - }); - }); + done() + }) + }) + }) + }) + }) - describe('session.clearStorageData(options)', function() { - fixtures = path.resolve(__dirname, 'fixtures'); - it('clears localstorage data', function(done) { - ipcMain.on('count', function(event, count) { - ipcMain.removeAllListeners('count'); - assert(!count); - done(); - }); - w.loadURL('file://' + path.join(fixtures, 'api', 'localstorage.html')); - w.webContents.on('did-finish-load', function() { + describe('session.clearStorageData(options)', function () { + fixtures = path.resolve(__dirname, 'fixtures') + it('clears localstorage data', function (done) { + ipcMain.on('count', function (event, count) { + ipcMain.removeAllListeners('count') + assert(!count) + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'localstorage.html')) + w.webContents.on('did-finish-load', function () { var options = { - origin: "file://", + origin: 'file://', storages: ['localstorage'], quotas: ['persistent'] - }; - w.webContents.session.clearStorageData(options, function() { - w.webContents.send('getcount'); - }); - }); - }); - }); + } + w.webContents.session.clearStorageData(options, function () { + w.webContents.send('getcount') + }) + }) + }) + }) - describe('session will-download event', function() { - var w = null; + describe('session will-download event', function () { + var w = null - beforeEach(function() { + beforeEach(function () { w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - }); + }) + }) - afterEach(function() { - w.destroy(); - }); + afterEach(function () { + w.destroy() + }) - it('can cancel default download behavior', function(done) { - const mockFile = new Buffer(1024); - const contentDisposition = 'inline; filename="mockFile.txt"'; - const downloadServer = http.createServer(function(req, res) { + it('can cancel default download behavior', function (done) { + const mockFile = new Buffer(1024) + const contentDisposition = 'inline; filename="mockFile.txt"' + const downloadServer = http.createServer(function (req, res) { res.writeHead(200, { 'Content-Length': mockFile.length, 'Content-Type': 'application/plain', 'Content-Disposition': contentDisposition - }); - res.end(mockFile); - downloadServer.close(); - }); + }) + res.end(mockFile) + downloadServer.close() + }) - downloadServer.listen(0, '127.0.0.1', function() { - const port = downloadServer.address().port; - const url = "http://127.0.0.1:" + port + '/'; + downloadServer.listen(0, '127.0.0.1', function () { + const port = downloadServer.address().port + const url = 'http://127.0.0.1:' + port + '/' - ipcRenderer.sendSync('set-download-option', false, true); - w.loadURL(url); - ipcRenderer.once('download-error', function(event, downloadUrl, filename, error) { - assert.equal(downloadUrl, url); - assert.equal(filename, 'mockFile.txt'); - assert.equal(error, 'Object has been destroyed'); - done(); - }); - }); - }); - }); + ipcRenderer.sendSync('set-download-option', false, true) + w.loadURL(url) + ipcRenderer.once('download-error', function (event, downloadUrl, filename, error) { + assert.equal(downloadUrl, url) + assert.equal(filename, 'mockFile.txt') + assert.equal(error, 'Object has been destroyed') + done() + }) + }) + }) + }) - describe('DownloadItem', function() { - var mockPDF = new Buffer(1024 * 1024 * 5); - var contentDisposition = 'inline; filename="mock.pdf"'; - var downloadFilePath = path.join(fixtures, 'mock.pdf'); - var downloadServer = http.createServer(function(req, res) { + describe('DownloadItem', function () { + var mockPDF = new Buffer(1024 * 1024 * 5) + var contentDisposition = 'inline; filename="mock.pdf"' + var downloadFilePath = path.join(fixtures, 'mock.pdf') + var downloadServer = http.createServer(function (req, res) { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': contentDisposition - }); - res.end(mockPDF); - downloadServer.close(); - }); - var assertDownload = function(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) { - assert.equal(state, 'completed'); - assert.equal(filename, 'mock.pdf'); - assert.equal(url, "http://127.0.0.1:" + port + "/"); - assert.equal(mimeType, 'application/pdf'); - assert.equal(receivedBytes, mockPDF.length); - assert.equal(totalBytes, mockPDF.length); - assert.equal(disposition, contentDisposition); - assert(fs.existsSync(downloadFilePath)); - fs.unlinkSync(downloadFilePath); - }; + }) + res.end(mockPDF) + downloadServer.close() + }) + var assertDownload = function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) { + assert.equal(state, 'completed') + assert.equal(filename, 'mock.pdf') + assert.equal(url, 'http://127.0.0.1:' + port + '/') + assert.equal(mimeType, 'application/pdf') + assert.equal(receivedBytes, mockPDF.length) + assert.equal(totalBytes, mockPDF.length) + assert.equal(disposition, contentDisposition) + assert(fs.existsSync(downloadFilePath)) + fs.unlinkSync(downloadFilePath) + } - it('can download using BrowserWindow.loadURL', function(done) { - downloadServer.listen(0, '127.0.0.1', function() { - var port = downloadServer.address().port; - ipcRenderer.sendSync('set-download-option', false, false); - w.loadURL(url + ":" + port); - ipcRenderer.once('download-done', function(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { - assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port); - done(); - }); - }); - }); + it('can download using BrowserWindow.loadURL', function (done) { + downloadServer.listen(0, '127.0.0.1', function () { + var port = downloadServer.address().port + ipcRenderer.sendSync('set-download-option', false, false) + w.loadURL(url + ':' + port) + ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { + assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) + done() + }) + }) + }) - it('can download using WebView.downloadURL', function(done) { - downloadServer.listen(0, '127.0.0.1', function() { - var port = downloadServer.address().port; - ipcRenderer.sendSync('set-download-option', false, false); - var webview = new WebView; - webview.src = "file://" + fixtures + "/api/blank.html"; - webview.addEventListener('did-finish-load', function() { - webview.downloadURL(url + ":" + port + "/"); - }); - ipcRenderer.once('download-done', function(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { - assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port); - document.body.removeChild(webview); - done(); - }); - document.body.appendChild(webview); - }); - }); + it('can download using WebView.downloadURL', function (done) { + downloadServer.listen(0, '127.0.0.1', function () { + var port = downloadServer.address().port + ipcRenderer.sendSync('set-download-option', false, false) + var webview = new WebView + webview.src = 'file://' + fixtures + '/api/blank.html' + webview.addEventListener('did-finish-load', function () { + webview.downloadURL(url + ':' + port + '/') + }) + ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { + assertDownload(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename, port) + document.body.removeChild(webview) + done() + }) + document.body.appendChild(webview) + }) + }) - it('can cancel download', function(done) { - downloadServer.listen(0, '127.0.0.1', function() { - var port = downloadServer.address().port; - ipcRenderer.sendSync('set-download-option', true, false); - w.loadURL(url + ":" + port + "/"); - ipcRenderer.once('download-done', function(event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { - assert.equal(state, 'cancelled'); - assert.equal(filename, 'mock.pdf'); - assert.equal(mimeType, 'application/pdf'); - assert.equal(receivedBytes, 0); - assert.equal(totalBytes, mockPDF.length); - assert.equal(disposition, contentDisposition); - done(); - }); - }); - }); - }); -}); + it('can cancel download', function (done) { + downloadServer.listen(0, '127.0.0.1', function () { + var port = downloadServer.address().port + ipcRenderer.sendSync('set-download-option', true, false) + w.loadURL(url + ':' + port + '/') + ipcRenderer.once('download-done', function (event, state, url, mimeType, receivedBytes, totalBytes, disposition, filename) { + assert.equal(state, 'cancelled') + assert.equal(filename, 'mock.pdf') + assert.equal(mimeType, 'application/pdf') + assert.equal(receivedBytes, 0) + assert.equal(totalBytes, mockPDF.length) + assert.equal(disposition, contentDisposition) + done() + }) + }) + }) + }) +}) diff --git a/spec/api-web-frame-spec.js b/spec/api-web-frame-spec.js index 15f31aa8f09..519966c8cea 100644 --- a/spec/api-web-frame-spec.js +++ b/spec/api-web-frame-spec.js @@ -1,19 +1,19 @@ -const assert = require('assert'); -const path = require('path'); -const webFrame = require('electron').webFrame; +const assert = require('assert') +const path = require('path') +const webFrame = require('electron').webFrame -describe('webFrame module', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); - describe('webFrame.registerURLSchemeAsPrivileged', function() { - it('supports fetch api', function(done) { - webFrame.registerURLSchemeAsPrivileged('file'); - var url = "file://" + fixtures + "/assets/logo.png"; - fetch(url).then(function(response) { - assert(response.ok); - done(); - }).catch(function(err) { - done('unexpected error : ' + err); - }); - }); - }); -}); +describe('webFrame module', function () { + var fixtures = path.resolve(__dirname, 'fixtures') + describe('webFrame.registerURLSchemeAsPrivileged', function () { + it('supports fetch api', function (done) { + webFrame.registerURLSchemeAsPrivileged('file') + var url = 'file://' + fixtures + '/assets/logo.png' + fetch(url).then(function (response) { + assert(response.ok) + done() + }).catch(function (err) { + done('unexpected error : ' + err) + }) + }) + }) +}) diff --git a/spec/api-web-request-spec.js b/spec/api-web-request-spec.js index 77f160a2004..abc4f9568cd 100644 --- a/spec/api-web-request-spec.js +++ b/spec/api-web-request-spec.js @@ -1,413 +1,412 @@ -const assert = require('assert'); -const http = require('http'); -const qs = require('querystring'); -const remote = require('electron').remote; -const session = remote.session; +const assert = require('assert') +const http = require('http') +const qs = require('querystring') +const remote = require('electron').remote +const session = remote.session -describe('webRequest module', function() { - var ses = session.defaultSession; - var server = http.createServer(function(req, res) { - res.setHeader('Custom', ['Header']); - var content = req.url; +describe('webRequest module', function () { + var ses = session.defaultSession + var server = http.createServer(function (req, res) { + res.setHeader('Custom', ['Header']) + var content = req.url if (req.headers.accept === '*/*;test/header') { - content += 'header/received'; + content += 'header/received' } - res.end(content); - }); - var defaultURL = null; + res.end(content) + }) + var defaultURL = null - before(function(done) { - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - defaultURL = "http://127.0.0.1:" + port + "/"; - done(); - }); - }); + before(function (done) { + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + defaultURL = 'http://127.0.0.1:' + port + '/' + done() + }) + }) - after(function() { - server.close(); - }); + after(function () { + server.close() + }) - describe('webRequest.onBeforeRequest', function() { - afterEach(function() { - ses.webRequest.onBeforeRequest(null); - }); + describe('webRequest.onBeforeRequest', function () { + afterEach(function () { + ses.webRequest.onBeforeRequest(null) + }) - it('can cancel the request', function(done) { - ses.webRequest.onBeforeRequest(function(details, callback) { + it('can cancel the request', function (done) { + ses.webRequest.onBeforeRequest(function (details, callback) { callback({ cancel: true - }); - }); + }) + }) $.ajax({ url: defaultURL, - success: function() { - done('unexpected success'); + success: function () { + done('unexpected success') }, - error: function() { - done(); + error: function () { + done() } - }); - }); + }) + }) - it('can filter URLs', function(done) { + it('can filter URLs', function (done) { var filter = { - urls: [defaultURL + "filter/*"] - }; - ses.webRequest.onBeforeRequest(filter, function(details, callback) { + urls: [defaultURL + 'filter/*'] + } + ses.webRequest.onBeforeRequest(filter, function (details, callback) { callback({ cancel: true - }); - }); + }) + }) $.ajax({ - url: defaultURL + "nofilter/test", - success: function(data) { - assert.equal(data, '/nofilter/test'); + url: defaultURL + 'nofilter/test', + success: function (data) { + assert.equal(data, '/nofilter/test') $.ajax({ - url: defaultURL + "filter/test", - success: function() { - done('unexpected success'); + url: defaultURL + 'filter/test', + success: function () { + done('unexpected success') }, - error: function() { - done(); + error: function () { + done() } - }); + }) }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('receives details object', function(done) { - ses.webRequest.onBeforeRequest(function(details, callback) { - assert.equal(typeof details.id, 'number'); - assert.equal(typeof details.timestamp, 'number'); - assert.equal(details.url, defaultURL); - assert.equal(details.method, 'GET'); - assert.equal(details.resourceType, 'xhr'); - assert(!details.uploadData); - callback({}); - }); + it('receives details object', function (done) { + ses.webRequest.onBeforeRequest(function (details, callback) { + assert.equal(typeof details.id, 'number') + assert.equal(typeof details.timestamp, 'number') + assert.equal(details.url, defaultURL) + assert.equal(details.method, 'GET') + assert.equal(details.resourceType, 'xhr') + assert(!details.uploadData) + callback({}) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/'); - done(); + success: function (data) { + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('receives post data in details object', function(done) { + it('receives post data in details object', function (done) { var postData = { name: 'post test', type: 'string' - }; - ses.webRequest.onBeforeRequest(function(details, callback) { - assert.equal(details.url, defaultURL); - assert.equal(details.method, 'POST'); - assert.equal(details.uploadData.length, 1); - var data = qs.parse(details.uploadData[0].bytes.toString()); - assert.deepEqual(data, postData); + } + ses.webRequest.onBeforeRequest(function (details, callback) { + assert.equal(details.url, defaultURL) + assert.equal(details.method, 'POST') + assert.equal(details.uploadData.length, 1) + var data = qs.parse(details.uploadData[0].bytes.toString()) + assert.deepEqual(data, postData) callback({ cancel: true - }); - }); + }) + }) $.ajax({ url: defaultURL, type: 'POST', data: postData, - success: function() { - }, - error: function() { - done(); + success: function () {}, + error: function () { + done() } - }); - }); + }) + }) - it('can redirect the request', function(done) { - ses.webRequest.onBeforeRequest(function(details, callback) { + it('can redirect the request', function (done) { + ses.webRequest.onBeforeRequest(function (details, callback) { if (details.url === defaultURL) { callback({ - redirectURL: defaultURL + "redirect" - }); + redirectURL: defaultURL + 'redirect' + }) } else { - callback({}); + callback({}) } - }); + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/redirect'); - done(); + success: function (data) { + assert.equal(data, '/redirect') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onBeforeSendHeaders', function() { - afterEach(function() { - ses.webRequest.onBeforeSendHeaders(null); - }); + describe('webRequest.onBeforeSendHeaders', function () { + afterEach(function () { + ses.webRequest.onBeforeSendHeaders(null) + }) - it('receives details object', function(done) { - ses.webRequest.onBeforeSendHeaders(function(details, callback) { - assert.equal(typeof details.requestHeaders, 'object'); - callback({}); - }); + it('receives details object', function (done) { + ses.webRequest.onBeforeSendHeaders(function (details, callback) { + assert.equal(typeof details.requestHeaders, 'object') + callback({}) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/'); - done(); + success: function (data) { + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('can change the request headers', function(done) { - ses.webRequest.onBeforeSendHeaders(function(details, callback) { - var requestHeaders = details.requestHeaders; - requestHeaders.Accept = '*/*;test/header'; + it('can change the request headers', function (done) { + ses.webRequest.onBeforeSendHeaders(function (details, callback) { + var requestHeaders = details.requestHeaders + requestHeaders.Accept = '*/*;test/header' callback({ requestHeaders: requestHeaders - }); - }); + }) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/header/received'); - done(); + success: function (data) { + assert.equal(data, '/header/received') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('resets the whole headers', function(done) { + it('resets the whole headers', function (done) { var requestHeaders = { Test: 'header' - }; - ses.webRequest.onBeforeSendHeaders(function(details, callback) { + } + ses.webRequest.onBeforeSendHeaders(function (details, callback) { callback({ requestHeaders: requestHeaders - }); - }); - ses.webRequest.onSendHeaders(function(details) { - assert.deepEqual(details.requestHeaders, requestHeaders); - done(); - }); + }) + }) + ses.webRequest.onSendHeaders(function (details) { + assert.deepEqual(details.requestHeaders, requestHeaders) + done() + }) $.ajax({ url: defaultURL, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onSendHeaders', function() { - afterEach(function() { - ses.webRequest.onSendHeaders(null); - }); + describe('webRequest.onSendHeaders', function () { + afterEach(function () { + ses.webRequest.onSendHeaders(null) + }) - it('receives details object', function(done) { - ses.webRequest.onSendHeaders(function(details) { - assert.equal(typeof details.requestHeaders, 'object'); - }); + it('receives details object', function (done) { + ses.webRequest.onSendHeaders(function (details) { + assert.equal(typeof details.requestHeaders, 'object') + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/'); - done(); + success: function (data) { + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onHeadersReceived', function() { - afterEach(function() { - ses.webRequest.onHeadersReceived(null); - }); + describe('webRequest.onHeadersReceived', function () { + afterEach(function () { + ses.webRequest.onHeadersReceived(null) + }) - it('receives details object', function(done) { - ses.webRequest.onHeadersReceived(function(details, callback) { - assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); - assert.equal(details.statusCode, 200); - assert.equal(details.responseHeaders['Custom'], 'Header'); - callback({}); - }); + it('receives details object', function (done) { + ses.webRequest.onHeadersReceived(function (details, callback) { + assert.equal(details.statusLine, 'HTTP/1.1 200 OK') + assert.equal(details.statusCode, 200) + assert.equal(details.responseHeaders['Custom'], 'Header') + callback({}) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/'); - done(); + success: function (data) { + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('can change the response header', function(done) { - ses.webRequest.onHeadersReceived(function(details, callback) { - var responseHeaders = details.responseHeaders; - responseHeaders['Custom'] = ['Changed']; + it('can change the response header', function (done) { + ses.webRequest.onHeadersReceived(function (details, callback) { + var responseHeaders = details.responseHeaders + responseHeaders['Custom'] = ['Changed'] callback({ responseHeaders: responseHeaders - }); - }); + }) + }) $.ajax({ url: defaultURL, - success: function(data, status, xhr) { - assert.equal(xhr.getResponseHeader('Custom'), 'Changed'); - assert.equal(data, '/'); - done(); + success: function (data, status, xhr) { + assert.equal(xhr.getResponseHeader('Custom'), 'Changed') + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); + }) + }) - it('does not change header by default', function(done) { - ses.webRequest.onHeadersReceived(function(details, callback) { - callback({}); - }); + it('does not change header by default', function (done) { + ses.webRequest.onHeadersReceived(function (details, callback) { + callback({}) + }) $.ajax({ url: defaultURL, - success: function(data, status, xhr) { - assert.equal(xhr.getResponseHeader('Custom'), 'Header'); - assert.equal(data, '/'); - done(); + success: function (data, status, xhr) { + assert.equal(xhr.getResponseHeader('Custom'), 'Header') + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onResponseStarted', function() { - afterEach(function() { - ses.webRequest.onResponseStarted(null); - }); + describe('webRequest.onResponseStarted', function () { + afterEach(function () { + ses.webRequest.onResponseStarted(null) + }) - it('receives details object', function(done) { - ses.webRequest.onResponseStarted(function(details) { - assert.equal(typeof details.fromCache, 'boolean'); - assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); - assert.equal(details.statusCode, 200); - assert.equal(details.responseHeaders['Custom'], 'Header'); - }); + it('receives details object', function (done) { + ses.webRequest.onResponseStarted(function (details) { + assert.equal(typeof details.fromCache, 'boolean') + assert.equal(details.statusLine, 'HTTP/1.1 200 OK') + assert.equal(details.statusCode, 200) + assert.equal(details.responseHeaders['Custom'], 'Header') + }) $.ajax({ url: defaultURL, - success: function(data, status, xhr) { - assert.equal(xhr.getResponseHeader('Custom'), 'Header'); - assert.equal(data, '/'); - done(); + success: function (data, status, xhr) { + assert.equal(xhr.getResponseHeader('Custom'), 'Header') + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onBeforeRedirect', function() { - afterEach(function() { - ses.webRequest.onBeforeRedirect(null); - ses.webRequest.onBeforeRequest(null); - }); + describe('webRequest.onBeforeRedirect', function () { + afterEach(function () { + ses.webRequest.onBeforeRedirect(null) + ses.webRequest.onBeforeRequest(null) + }) - it('receives details object', function(done) { - var redirectURL = defaultURL + "redirect"; - ses.webRequest.onBeforeRequest(function(details, callback) { + it('receives details object', function (done) { + var redirectURL = defaultURL + 'redirect' + ses.webRequest.onBeforeRequest(function (details, callback) { if (details.url === defaultURL) { callback({ redirectURL: redirectURL - }); + }) } else { - callback({}); + callback({}) } - }); - ses.webRequest.onBeforeRedirect(function(details) { - assert.equal(typeof details.fromCache, 'boolean'); - assert.equal(details.statusLine, 'HTTP/1.1 307 Internal Redirect'); - assert.equal(details.statusCode, 307); - assert.equal(details.redirectURL, redirectURL); - }); + }) + ses.webRequest.onBeforeRedirect(function (details) { + assert.equal(typeof details.fromCache, 'boolean') + assert.equal(details.statusLine, 'HTTP/1.1 307 Internal Redirect') + assert.equal(details.statusCode, 307) + assert.equal(details.redirectURL, redirectURL) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/redirect'); - done(); + success: function (data) { + assert.equal(data, '/redirect') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onCompleted', function() { - afterEach(function() { - ses.webRequest.onCompleted(null); - }); + describe('webRequest.onCompleted', function () { + afterEach(function () { + ses.webRequest.onCompleted(null) + }) - it('receives details object', function(done) { - ses.webRequest.onCompleted(function(details) { - assert.equal(typeof details.fromCache, 'boolean'); - assert.equal(details.statusLine, 'HTTP/1.1 200 OK'); - assert.equal(details.statusCode, 200); - }); + it('receives details object', function (done) { + ses.webRequest.onCompleted(function (details) { + assert.equal(typeof details.fromCache, 'boolean') + assert.equal(details.statusLine, 'HTTP/1.1 200 OK') + assert.equal(details.statusCode, 200) + }) $.ajax({ url: defaultURL, - success: function(data) { - assert.equal(data, '/'); - done(); + success: function (data) { + assert.equal(data, '/') + done() }, - error: function(xhr, errorType) { - done(errorType); + error: function (xhr, errorType) { + done(errorType) } - }); - }); - }); + }) + }) + }) - describe('webRequest.onErrorOccurred', function() { - afterEach(function() { - ses.webRequest.onErrorOccurred(null); - ses.webRequest.onBeforeRequest(null); - }); + describe('webRequest.onErrorOccurred', function () { + afterEach(function () { + ses.webRequest.onErrorOccurred(null) + ses.webRequest.onBeforeRequest(null) + }) - it('receives details object', function(done) { - ses.webRequest.onBeforeRequest(function(details, callback) { + it('receives details object', function (done) { + ses.webRequest.onBeforeRequest(function (details, callback) { callback({ cancel: true - }); - }); - ses.webRequest.onErrorOccurred(function(details) { - assert.equal(details.error, 'net::ERR_BLOCKED_BY_CLIENT'); - done(); - }); + }) + }) + ses.webRequest.onErrorOccurred(function (details) { + assert.equal(details.error, 'net::ERR_BLOCKED_BY_CLIENT') + done() + }) $.ajax({ url: defaultURL, - success: function() { - done('unexpected success'); + success: function () { + done('unexpected success') } - }); - }); - }); -}); + }) + }) + }) +}) diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 0e0a7f89f17..050d8d7deda 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -1,813 +1,813 @@ -const assert = require('assert'); -const child_process = require('child_process'); -const fs = require('fs'); -const path = require('path'); +const assert = require('assert') +const child_process = require('child_process') +const fs = require('fs') +const path = require('path') -const nativeImage = require('electron').nativeImage; -const remote = require('electron').remote; +const nativeImage = require('electron').nativeImage +const remote = require('electron').remote -const ipcMain = remote.require('electron').ipcMain; -const BrowserWindow = remote.require('electron').BrowserWindow; +const ipcMain = remote.require('electron').ipcMain +const BrowserWindow = remote.require('electron').BrowserWindow -describe('asar package', function() { - var fixtures = path.join(__dirname, 'fixtures'); +describe('asar package', function () { + var fixtures = path.join(__dirname, 'fixtures') - describe('node api', function() { - describe('fs.readFileSync', function() { - it('does not leak fd', function() { - var readCalls = 1; + describe('node api', function () { + describe('fs.readFileSync', function () { + it('does not leak fd', function () { + var readCalls = 1 while(readCalls <= 10000) { - fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'ipc.js')); - readCalls++; + fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'ipc.js')) + readCalls++ } - }); + }) - it('reads a normal file', function() { - var file1 = path.join(fixtures, 'asar', 'a.asar', 'file1'); - assert.equal(fs.readFileSync(file1).toString().trim(), 'file1'); - var file2 = path.join(fixtures, 'asar', 'a.asar', 'file2'); - assert.equal(fs.readFileSync(file2).toString().trim(), 'file2'); - var file3 = path.join(fixtures, 'asar', 'a.asar', 'file3'); - assert.equal(fs.readFileSync(file3).toString().trim(), 'file3'); - }); + it('reads a normal file', function () { + var file1 = path.join(fixtures, 'asar', 'a.asar', 'file1') + assert.equal(fs.readFileSync(file1).toString().trim(), 'file1') + var file2 = path.join(fixtures, 'asar', 'a.asar', 'file2') + assert.equal(fs.readFileSync(file2).toString().trim(), 'file2') + var file3 = path.join(fixtures, 'asar', 'a.asar', 'file3') + assert.equal(fs.readFileSync(file3).toString().trim(), 'file3') + }) - it('reads from a empty file', function() { - var file = path.join(fixtures, 'asar', 'empty.asar', 'file1'); - var buffer = fs.readFileSync(file); - assert.equal(buffer.length, 0); - assert.equal(buffer.toString(), ''); - }); + it('reads from a empty file', function () { + var file = path.join(fixtures, 'asar', 'empty.asar', 'file1') + var buffer = fs.readFileSync(file) + assert.equal(buffer.length, 0) + assert.equal(buffer.toString(), '') + }) - it('reads a linked file', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'link1'); - assert.equal(fs.readFileSync(p).toString().trim(), 'file1'); - }); + it('reads a linked file', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'link1') + assert.equal(fs.readFileSync(p).toString().trim(), 'file1') + }) - it('reads a file from linked directory', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'file1'); - assert.equal(fs.readFileSync(p).toString().trim(), 'file1'); - p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1'); - assert.equal(fs.readFileSync(p).toString().trim(), 'file1'); - }); + it('reads a file from linked directory', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'file1') + assert.equal(fs.readFileSync(p).toString().trim(), 'file1') + p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1') + assert.equal(fs.readFileSync(p).toString().trim(), 'file1') + }) - it('throws ENOENT error when can not find file', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - var throws = function() { - fs.readFileSync(p); - }; - assert.throws(throws, /ENOENT/); - }); + it('throws ENOENT error when can not find file', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + var throws = function () { + fs.readFileSync(p) + } + assert.throws(throws, /ENOENT/) + }) - it('passes ENOENT error to callback when can not find file', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - var async = false; - fs.readFile(p, function(e) { - assert(async); - assert(/ENOENT/.test(e)); - }); - async = true; - }); + it('passes ENOENT error to callback when can not find file', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + var async = false + fs.readFile(p, function (e) { + assert(async) + assert(/ENOENT/.test(e)) + }) + async = true + }) - it('reads a normal file with unpacked files', function() { - var p = path.join(fixtures, 'asar', 'unpack.asar', 'a.txt'); - assert.equal(fs.readFileSync(p).toString().trim(), 'a'); - }); - }); + it('reads a normal file with unpacked files', function () { + var p = path.join(fixtures, 'asar', 'unpack.asar', 'a.txt') + assert.equal(fs.readFileSync(p).toString().trim(), 'a') + }) + }) - describe('fs.readFile', function() { - it('reads a normal file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'file1'); - fs.readFile(p, function(err, content) { - assert.equal(err, null); - assert.equal(String(content).trim(), 'file1'); - done(); - }); - }); + describe('fs.readFile', function () { + it('reads a normal file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'file1') + fs.readFile(p, function (err, content) { + assert.equal(err, null) + assert.equal(String(content).trim(), 'file1') + done() + }) + }) - it('reads from a empty file', function(done) { - var p = path.join(fixtures, 'asar', 'empty.asar', 'file1'); - fs.readFile(p, function(err, content) { - assert.equal(err, null); - assert.equal(String(content), ''); - done(); - }); - }); + it('reads from a empty file', function (done) { + var p = path.join(fixtures, 'asar', 'empty.asar', 'file1') + fs.readFile(p, function (err, content) { + assert.equal(err, null) + assert.equal(String(content), '') + done() + }) + }) - it('reads a linked file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link1'); - fs.readFile(p, function(err, content) { - assert.equal(err, null); - assert.equal(String(content).trim(), 'file1'); - done(); - }); - }); + it('reads a linked file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link1') + fs.readFile(p, function (err, content) { + assert.equal(err, null) + assert.equal(String(content).trim(), 'file1') + done() + }) + }) - it('reads a file from linked directory', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1'); - fs.readFile(p, function(err, content) { - assert.equal(err, null); - assert.equal(String(content).trim(), 'file1'); - done(); - }); - }); + it('reads a file from linked directory', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1') + fs.readFile(p, function (err, content) { + assert.equal(err, null) + assert.equal(String(content).trim(), 'file1') + done() + }) + }) - it('throws ENOENT error when can not find file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - fs.readFile(p, function(err) { - assert.equal(err.code, 'ENOENT'); - done(); - }); - }); - }); + it('throws ENOENT error when can not find file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + fs.readFile(p, function (err) { + assert.equal(err.code, 'ENOENT') + done() + }) + }) + }) - describe('fs.lstatSync', function() { - it('handles path with trailing slash correctly', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1'); - fs.lstatSync(p); - fs.lstatSync(p + '/'); - }); + describe('fs.lstatSync', function () { + it('handles path with trailing slash correctly', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1') + fs.lstatSync(p) + fs.lstatSync(p + '/') + }) - it('returns information of root', function() { - var p = path.join(fixtures, 'asar', 'a.asar'); - var stats = fs.lstatSync(p); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), true); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 0); - }); + it('returns information of root', function () { + var p = path.join(fixtures, 'asar', 'a.asar') + var stats = fs.lstatSync(p) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), true) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 0) + }) - it('returns information of a normal file', function() { - var file, j, len, p, ref2, stats; - ref2 = ['file1', 'file2', 'file3', path.join('dir1', 'file1'), path.join('link2', 'file1')]; + it('returns information of a normal file', function () { + var file, j, len, p, ref2, stats + ref2 = ['file1', 'file2', 'file3', path.join('dir1', 'file1'), path.join('link2', 'file1')] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - stats = fs.lstatSync(p); - assert.equal(stats.isFile(), true); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 6); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + stats = fs.lstatSync(p) + assert.equal(stats.isFile(), true) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 6) } - }); + }) - it('returns information of a normal directory', function() { - var file, j, len, p, ref2, stats; - ref2 = ['dir1', 'dir2', 'dir3']; + it('returns information of a normal directory', function () { + var file, j, len, p, ref2, stats + ref2 = ['dir1', 'dir2', 'dir3'] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - stats = fs.lstatSync(p); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), true); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 0); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + stats = fs.lstatSync(p) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), true) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 0) } - }); + }) - it('returns information of a linked file', function() { - var file, j, len, p, ref2, stats; - ref2 = ['link1', path.join('dir1', 'link1'), path.join('link2', 'link2')]; + it('returns information of a linked file', function () { + var file, j, len, p, ref2, stats + ref2 = ['link1', path.join('dir1', 'link1'), path.join('link2', 'link2')] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - stats = fs.lstatSync(p); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), true); - assert.equal(stats.size, 0); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + stats = fs.lstatSync(p) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), true) + assert.equal(stats.size, 0) } - }); + }) - it('returns information of a linked directory', function() { - var file, j, len, p, ref2, stats; - ref2 = ['link2', path.join('dir1', 'link2'), path.join('link2', 'link2')]; + it('returns information of a linked directory', function () { + var file, j, len, p, ref2, stats + ref2 = ['link2', path.join('dir1', 'link2'), path.join('link2', 'link2')] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - stats = fs.lstatSync(p); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), true); - assert.equal(stats.size, 0); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + stats = fs.lstatSync(p) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), true) + assert.equal(stats.size, 0) } - }); + }) - it('throws ENOENT error when can not find file', function() { - var file, j, len, p, ref2, throws; - ref2 = ['file4', 'file5', path.join('dir1', 'file4')]; + it('throws ENOENT error when can not find file', function () { + var file, j, len, p, ref2, throws + ref2 = ['file4', 'file5', path.join('dir1', 'file4')] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - throws = function() { - fs.lstatSync(p); - }; - assert.throws(throws, /ENOENT/); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + throws = function () { + fs.lstatSync(p) + } + assert.throws(throws, /ENOENT/) } - }); - }); + }) + }) - describe('fs.lstat', function() { - it('handles path with trailing slash correctly', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1'); - fs.lstat(p + '/', done); - }); + describe('fs.lstat', function () { + it('handles path with trailing slash correctly', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2', 'file1') + fs.lstat(p + '/', done) + }) - it('returns information of root', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar'); - fs.lstat(p, function(err, stats) { - assert.equal(err, null); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), true); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 0); - done(); - }); - }); + it('returns information of root', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar') + fs.lstat(p, function (err, stats) { + assert.equal(err, null) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), true) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 0) + done() + }) + }) - it('returns information of a normal file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'file1'); - fs.lstat(p, function(err, stats) { - assert.equal(err, null); - assert.equal(stats.isFile(), true); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 6); - done(); - }); - }); + it('returns information of a normal file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'file1') + fs.lstat(p, function (err, stats) { + assert.equal(err, null) + assert.equal(stats.isFile(), true) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 6) + done() + }) + }) - it('returns information of a normal directory', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'dir1'); - fs.lstat(p, function(err, stats) { - assert.equal(err, null); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), true); - assert.equal(stats.isSymbolicLink(), false); - assert.equal(stats.size, 0); - done(); - }); - }); + it('returns information of a normal directory', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'dir1') + fs.lstat(p, function (err, stats) { + assert.equal(err, null) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), true) + assert.equal(stats.isSymbolicLink(), false) + assert.equal(stats.size, 0) + done() + }) + }) - it('returns information of a linked file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link1'); - fs.lstat(p, function(err, stats) { - assert.equal(err, null); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), true); - assert.equal(stats.size, 0); - done(); - }); - }); + it('returns information of a linked file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link1') + fs.lstat(p, function (err, stats) { + assert.equal(err, null) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), true) + assert.equal(stats.size, 0) + done() + }) + }) - it('returns information of a linked directory', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2'); - fs.lstat(p, function(err, stats) { - assert.equal(err, null); - assert.equal(stats.isFile(), false); - assert.equal(stats.isDirectory(), false); - assert.equal(stats.isSymbolicLink(), true); - assert.equal(stats.size, 0); - done(); - }); - }); + it('returns information of a linked directory', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2') + fs.lstat(p, function (err, stats) { + assert.equal(err, null) + assert.equal(stats.isFile(), false) + assert.equal(stats.isDirectory(), false) + assert.equal(stats.isSymbolicLink(), true) + assert.equal(stats.size, 0) + done() + }) + }) - it('throws ENOENT error when can not find file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'file4'); - fs.lstat(p, function(err) { - assert.equal(err.code, 'ENOENT'); - done(); - }); - }); - }); + it('throws ENOENT error when can not find file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'file4') + fs.lstat(p, function (err) { + assert.equal(err.code, 'ENOENT') + done() + }) + }) + }) - describe('fs.realpathSync', function() { - it('returns real path root', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = 'a.asar'; - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, p)); - }); + describe('fs.realpathSync', function () { + it('returns real path root', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = 'a.asar' + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, p)) + }) - it('returns real path of a normal file', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'file1'); - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, p)); - }); + it('returns real path of a normal file', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'file1') + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, p)) + }) - it('returns real path of a normal directory', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'dir1'); - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, p)); - }); + it('returns real path of a normal directory', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'dir1') + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, p)) + }) - it('returns real path of a linked file', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'link2', 'link1'); - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, 'a.asar', 'file1')); - }); + it('returns real path of a linked file', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'link2', 'link1') + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, 'a.asar', 'file1')) + }) - it('returns real path of a linked directory', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'link2', 'link2'); - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, 'a.asar', 'dir1')); - }); + it('returns real path of a linked directory', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'link2', 'link2') + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, 'a.asar', 'dir1')) + }) - it('returns real path of an unpacked file', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('unpack.asar', 'a.txt'); - var r = fs.realpathSync(path.join(parent, p)); - assert.equal(r, path.join(parent, p)); - }); + it('returns real path of an unpacked file', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('unpack.asar', 'a.txt') + var r = fs.realpathSync(path.join(parent, p)) + assert.equal(r, path.join(parent, p)) + }) - it('throws ENOENT error when can not find file', function() { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'not-exist'); - var throws = function() { - fs.realpathSync(path.join(parent, p)); - }; - assert.throws(throws, /ENOENT/); - }); - }); + it('throws ENOENT error when can not find file', function () { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'not-exist') + var throws = function () { + fs.realpathSync(path.join(parent, p)) + } + assert.throws(throws, /ENOENT/) + }) + }) - describe('fs.realpath', function() { - it('returns real path root', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = 'a.asar'; - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, p)); - done(); - }); - }); + describe('fs.realpath', function () { + it('returns real path root', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = 'a.asar' + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, p)) + done() + }) + }) - it('returns real path of a normal file', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'file1'); - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, p)); - done(); - }); - }); + it('returns real path of a normal file', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'file1') + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, p)) + done() + }) + }) - it('returns real path of a normal directory', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'dir1'); - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, p)); - done(); - }); - }); + it('returns real path of a normal directory', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'dir1') + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, p)) + done() + }) + }) - it('returns real path of a linked file', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'link2', 'link1'); - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, 'a.asar', 'file1')); - done(); - }); - }); + it('returns real path of a linked file', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'link2', 'link1') + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, 'a.asar', 'file1')) + done() + }) + }) - it('returns real path of a linked directory', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'link2', 'link2'); - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, 'a.asar', 'dir1')); - done(); - }); - }); + it('returns real path of a linked directory', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'link2', 'link2') + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, 'a.asar', 'dir1')) + done() + }) + }) - it('returns real path of an unpacked file', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('unpack.asar', 'a.txt'); - fs.realpath(path.join(parent, p), function(err, r) { - assert.equal(err, null); - assert.equal(r, path.join(parent, p)); - done(); - }); - }); + it('returns real path of an unpacked file', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('unpack.asar', 'a.txt') + fs.realpath(path.join(parent, p), function (err, r) { + assert.equal(err, null) + assert.equal(r, path.join(parent, p)) + done() + }) + }) - it('throws ENOENT error when can not find file', function(done) { - var parent = fs.realpathSync(path.join(fixtures, 'asar')); - var p = path.join('a.asar', 'not-exist'); - fs.realpath(path.join(parent, p), function(err) { - assert.equal(err.code, 'ENOENT'); - done(); - }); - }); - }); - describe('fs.readdirSync', function() { - it('reads dirs from root', function() { - var p = path.join(fixtures, 'asar', 'a.asar'); - var dirs = fs.readdirSync(p); - assert.deepEqual(dirs, ['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); - }); + it('throws ENOENT error when can not find file', function (done) { + var parent = fs.realpathSync(path.join(fixtures, 'asar')) + var p = path.join('a.asar', 'not-exist') + fs.realpath(path.join(parent, p), function (err) { + assert.equal(err.code, 'ENOENT') + done() + }) + }) + }) + describe('fs.readdirSync', function () { + it('reads dirs from root', function () { + var p = path.join(fixtures, 'asar', 'a.asar') + var dirs = fs.readdirSync(p) + assert.deepEqual(dirs, ['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']) + }) - it('reads dirs from a normal dir', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'dir1'); - var dirs = fs.readdirSync(p); - assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']); - }); + it('reads dirs from a normal dir', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'dir1') + var dirs = fs.readdirSync(p) + assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']) + }) - it('reads dirs from a linked dir', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2'); - var dirs = fs.readdirSync(p); - assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']); - }); + it('reads dirs from a linked dir', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2') + var dirs = fs.readdirSync(p) + assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']) + }) - it('throws ENOENT error when can not find file', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - var throws = function() { - fs.readdirSync(p); - }; - assert.throws(throws, /ENOENT/); - }); - }); + it('throws ENOENT error when can not find file', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + var throws = function () { + fs.readdirSync(p) + } + assert.throws(throws, /ENOENT/) + }) + }) - describe('fs.readdir', function() { - it('reads dirs from root', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar'); - fs.readdir(p, function(err, dirs) { - assert.equal(err, null); - assert.deepEqual(dirs, ['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); - done(); - }); - }); + describe('fs.readdir', function () { + it('reads dirs from root', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar') + fs.readdir(p, function (err, dirs) { + assert.equal(err, null) + assert.deepEqual(dirs, ['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']) + done() + }) + }) - it('reads dirs from a normal dir', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'dir1'); - fs.readdir(p, function(err, dirs) { - assert.equal(err, null); - assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']); - done(); - }); - }); - it('reads dirs from a linked dir', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2'); - fs.readdir(p, function(err, dirs) { - assert.equal(err, null); - assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']); - done(); - }); - }); + it('reads dirs from a normal dir', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'dir1') + fs.readdir(p, function (err, dirs) { + assert.equal(err, null) + assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']) + done() + }) + }) + it('reads dirs from a linked dir', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'link2', 'link2') + fs.readdir(p, function (err, dirs) { + assert.equal(err, null) + assert.deepEqual(dirs, ['file1', 'file2', 'file3', 'link1', 'link2']) + done() + }) + }) - it('throws ENOENT error when can not find file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - fs.readdir(p, function(err) { - assert.equal(err.code, 'ENOENT'); - done(); - }); - }); - }); + it('throws ENOENT error when can not find file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + fs.readdir(p, function (err) { + assert.equal(err.code, 'ENOENT') + done() + }) + }) + }) - describe('fs.openSync', function() { - it('opens a normal/linked/under-linked-directory file', function() { - var buffer, fd, file, j, len, p, ref2; - ref2 = ['file1', 'link1', path.join('link2', 'file1')]; + describe('fs.openSync', function () { + it('opens a normal/linked/under-linked-directory file', function () { + var buffer, fd, file, j, len, p, ref2 + ref2 = ['file1', 'link1', path.join('link2', 'file1')] for (j = 0, len = ref2.length; j < len; j++) { - file = ref2[j]; - p = path.join(fixtures, 'asar', 'a.asar', file); - fd = fs.openSync(p, 'r'); - buffer = new Buffer(6); - fs.readSync(fd, buffer, 0, 6, 0); - assert.equal(String(buffer).trim(), 'file1'); - fs.closeSync(fd); + file = ref2[j] + p = path.join(fixtures, 'asar', 'a.asar', file) + fd = fs.openSync(p, 'r') + buffer = new Buffer(6) + fs.readSync(fd, buffer, 0, 6, 0) + assert.equal(String(buffer).trim(), 'file1') + fs.closeSync(fd) } - }); + }) - it('throws ENOENT error when can not find file', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - var throws = function() { - fs.openSync(p); - }; - assert.throws(throws, /ENOENT/); - }); - }); + it('throws ENOENT error when can not find file', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + var throws = function () { + fs.openSync(p) + } + assert.throws(throws, /ENOENT/) + }) + }) - describe('fs.open', function() { - it('opens a normal file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'file1'); - fs.open(p, 'r', function(err, fd) { - assert.equal(err, null); - var buffer = new Buffer(6); - fs.read(fd, buffer, 0, 6, 0, function(err) { - assert.equal(err, null); - assert.equal(String(buffer).trim(), 'file1'); - fs.close(fd, done); - }); - }); - }); + describe('fs.open', function () { + it('opens a normal file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'file1') + fs.open(p, 'r', function (err, fd) { + assert.equal(err, null) + var buffer = new Buffer(6) + fs.read(fd, buffer, 0, 6, 0, function (err) { + assert.equal(err, null) + assert.equal(String(buffer).trim(), 'file1') + fs.close(fd, done) + }) + }) + }) - it('throws ENOENT error when can not find file', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - fs.open(p, 'r', function(err) { - assert.equal(err.code, 'ENOENT'); - done(); - }); - }); - }); + it('throws ENOENT error when can not find file', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + fs.open(p, 'r', function (err) { + assert.equal(err.code, 'ENOENT') + done() + }) + }) + }) - describe('fs.mkdir', function() { - it('throws error when calling inside asar archive', function(done) { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - fs.mkdir(p, function(err) { - assert.equal(err.code, 'ENOTDIR'); - done(); - }); - }); - }); + describe('fs.mkdir', function () { + it('throws error when calling inside asar archive', function (done) { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + fs.mkdir(p, function (err) { + assert.equal(err.code, 'ENOTDIR') + done() + }) + }) + }) - describe('fs.mkdirSync', function() { - it('throws error when calling inside asar archive', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - assert.throws((function() { - fs.mkdirSync(p); - }), new RegExp('ENOTDIR')); - }); - }); + describe('fs.mkdirSync', function () { + it('throws error when calling inside asar archive', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + assert.throws((function () { + fs.mkdirSync(p) + }), new RegExp('ENOTDIR')) + }) + }) - describe('child_process.fork', function() { - it('opens a normal js file', function(done) { - var child = child_process.fork(path.join(fixtures, 'asar', 'a.asar', 'ping.js')); - child.on('message', function(msg) { - assert.equal(msg, 'message'); - done(); - }); - child.send('message'); - }); + describe('child_process.fork', function () { + it('opens a normal js file', function (done) { + var child = child_process.fork(path.join(fixtures, 'asar', 'a.asar', 'ping.js')) + child.on('message', function (msg) { + assert.equal(msg, 'message') + done() + }) + child.send('message') + }) - it('supports asar in the forked js', function(done) { - var file = path.join(fixtures, 'asar', 'a.asar', 'file1'); - var child = child_process.fork(path.join(fixtures, 'module', 'asar.js')); - child.on('message', function(content) { - assert.equal(content, fs.readFileSync(file).toString()); - done(); - }); - child.send(file); - }); - }); + it('supports asar in the forked js', function (done) { + var file = path.join(fixtures, 'asar', 'a.asar', 'file1') + var child = child_process.fork(path.join(fixtures, 'module', 'asar.js')) + child.on('message', function (content) { + assert.equal(content, fs.readFileSync(file).toString()) + done() + }) + child.send(file) + }) + }) - describe('child_process.execFile', function() { - var echo, execFile, execFileSync, ref2; + describe('child_process.execFile', function () { + var echo, execFile, execFileSync, ref2 if (process.platform !== 'darwin') { - return; + return } - ref2 = require('child_process'), execFile = ref2.execFile, execFileSync = ref2.execFileSync; - echo = path.join(fixtures, 'asar', 'echo.asar', 'echo'); + ref2 = require('child_process'), execFile = ref2.execFile, execFileSync = ref2.execFileSync + echo = path.join(fixtures, 'asar', 'echo.asar', 'echo') - it('executes binaries', function(done) { - execFile(echo, ['test'], function(error, stdout) { - assert.equal(error, null); - assert.equal(stdout, 'test\n'); - done(); - }); - }); + it('executes binaries', function (done) { + execFile(echo, ['test'], function (error, stdout) { + assert.equal(error, null) + assert.equal(stdout, 'test\n') + done() + }) + }) - xit('execFileSync executes binaries', function() { - var output = execFileSync(echo, ['test']); - assert.equal(String(output), 'test\n'); - }); - }); + xit('execFileSync executes binaries', function () { + var output = execFileSync(echo, ['test']) + assert.equal(String(output), 'test\n') + }) + }) - describe('internalModuleReadFile', function() { - var internalModuleReadFile = process.binding('fs').internalModuleReadFile; + describe('internalModuleReadFile', function () { + var internalModuleReadFile = process.binding('fs').internalModuleReadFile - it('read a normal file', function() { - var file1 = path.join(fixtures, 'asar', 'a.asar', 'file1'); - assert.equal(internalModuleReadFile(file1).toString().trim(), 'file1'); - var file2 = path.join(fixtures, 'asar', 'a.asar', 'file2'); - assert.equal(internalModuleReadFile(file2).toString().trim(), 'file2'); - var file3 = path.join(fixtures, 'asar', 'a.asar', 'file3'); - assert.equal(internalModuleReadFile(file3).toString().trim(), 'file3'); - }); + it('read a normal file', function () { + var file1 = path.join(fixtures, 'asar', 'a.asar', 'file1') + assert.equal(internalModuleReadFile(file1).toString().trim(), 'file1') + var file2 = path.join(fixtures, 'asar', 'a.asar', 'file2') + assert.equal(internalModuleReadFile(file2).toString().trim(), 'file2') + var file3 = path.join(fixtures, 'asar', 'a.asar', 'file3') + assert.equal(internalModuleReadFile(file3).toString().trim(), 'file3') + }) - it('reads a normal file with unpacked files', function() { - var p = path.join(fixtures, 'asar', 'unpack.asar', 'a.txt'); - assert.equal(internalModuleReadFile(p).toString().trim(), 'a'); - }); - }); + it('reads a normal file with unpacked files', function () { + var p = path.join(fixtures, 'asar', 'unpack.asar', 'a.txt') + assert.equal(internalModuleReadFile(p).toString().trim(), 'a') + }) + }) - describe('process.noAsar', function() { - var errorName = process.platform === 'win32' ? 'ENOENT' : 'ENOTDIR'; + describe('process.noAsar', function () { + var errorName = process.platform === 'win32' ? 'ENOENT' : 'ENOTDIR' - beforeEach(function() { - process.noAsar = true; - }); + beforeEach(function () { + process.noAsar = true + }) - afterEach(function() { - process.noAsar = false; - }); + afterEach(function () { + process.noAsar = false + }) - it('disables asar support in sync API', function() { - var file = path.join(fixtures, 'asar', 'a.asar', 'file1'); - var dir = path.join(fixtures, 'asar', 'a.asar', 'dir1'); - assert.throws((function() { - fs.readFileSync(file); - }), new RegExp(errorName)); - assert.throws((function() { - fs.lstatSync(file); - }), new RegExp(errorName)); - assert.throws((function() { - fs.realpathSync(file); - }), new RegExp(errorName)); - assert.throws((function() { - fs.readdirSync(dir); - }), new RegExp(errorName)); - }); + it('disables asar support in sync API', function () { + var file = path.join(fixtures, 'asar', 'a.asar', 'file1') + var dir = path.join(fixtures, 'asar', 'a.asar', 'dir1') + assert.throws((function () { + fs.readFileSync(file) + }), new RegExp(errorName)) + assert.throws((function () { + fs.lstatSync(file) + }), new RegExp(errorName)) + assert.throws((function () { + fs.realpathSync(file) + }), new RegExp(errorName)) + assert.throws((function () { + fs.readdirSync(dir) + }), new RegExp(errorName)) + }) - it('disables asar support in async API', function(done) { - var file = path.join(fixtures, 'asar', 'a.asar', 'file1'); - var dir = path.join(fixtures, 'asar', 'a.asar', 'dir1'); - fs.readFile(file, function(error) { - assert.equal(error.code, errorName); - fs.lstat(file, function(error) { - assert.equal(error.code, errorName); - fs.realpath(file, function(error) { - assert.equal(error.code, errorName); - fs.readdir(dir, function(error) { - assert.equal(error.code, errorName); - done(); - }); - }); - }); - }); - }); + it('disables asar support in async API', function (done) { + var file = path.join(fixtures, 'asar', 'a.asar', 'file1') + var dir = path.join(fixtures, 'asar', 'a.asar', 'dir1') + fs.readFile(file, function (error) { + assert.equal(error.code, errorName) + fs.lstat(file, function (error) { + assert.equal(error.code, errorName) + fs.realpath(file, function (error) { + assert.equal(error.code, errorName) + fs.readdir(dir, function (error) { + assert.equal(error.code, errorName) + done() + }) + }) + }) + }) + }) - it('treats *.asar as normal file', function() { - var originalFs = require('original-fs'); - var asar = path.join(fixtures, 'asar', 'a.asar'); - var content1 = fs.readFileSync(asar); - var content2 = originalFs.readFileSync(asar); - assert.equal(content1.compare(content2), 0); - assert.throws((function() { - fs.readdirSync(asar); - }), /ENOTDIR/); - }); - }); - }); + it('treats *.asar as normal file', function () { + var originalFs = require('original-fs') + var asar = path.join(fixtures, 'asar', 'a.asar') + var content1 = fs.readFileSync(asar) + var content2 = originalFs.readFileSync(asar) + assert.equal(content1.compare(content2), 0) + assert.throws((function () { + fs.readdirSync(asar) + }), /ENOTDIR/) + }) + }) + }) - describe('asar protocol', function() { - var url = require('url'); + describe('asar protocol', function () { + var url = require('url') - it('can request a file in package', function(done) { - var p = path.resolve(fixtures, 'asar', 'a.asar', 'file1'); - $.get("file://" + p, function(data) { - assert.equal(data.trim(), 'file1'); - done(); - }); - }); + it('can request a file in package', function (done) { + var p = path.resolve(fixtures, 'asar', 'a.asar', 'file1') + $.get('file://' + p, function (data) { + assert.equal(data.trim(), 'file1') + done() + }) + }) - it('can request a file in package with unpacked files', function(done) { - var p = path.resolve(fixtures, 'asar', 'unpack.asar', 'a.txt'); - $.get("file://" + p, function(data) { - assert.equal(data.trim(), 'a'); - done(); - }); - }); + it('can request a file in package with unpacked files', function (done) { + var p = path.resolve(fixtures, 'asar', 'unpack.asar', 'a.txt') + $.get('file://' + p, function (data) { + assert.equal(data.trim(), 'a') + done() + }) + }) - it('can request a linked file in package', function(done) { - var p = path.resolve(fixtures, 'asar', 'a.asar', 'link2', 'link1'); - $.get("file://" + p, function(data) { - assert.equal(data.trim(), 'file1'); - done(); - }); - }); + it('can request a linked file in package', function (done) { + var p = path.resolve(fixtures, 'asar', 'a.asar', 'link2', 'link1') + $.get('file://' + p, function (data) { + assert.equal(data.trim(), 'file1') + done() + }) + }) - it('can request a file in filesystem', function(done) { - var p = path.resolve(fixtures, 'asar', 'file'); - $.get("file://" + p, function(data) { - assert.equal(data.trim(), 'file'); - done(); - }); - }); + it('can request a file in filesystem', function (done) { + var p = path.resolve(fixtures, 'asar', 'file') + $.get('file://' + p, function (data) { + assert.equal(data.trim(), 'file') + done() + }) + }) - it('gets 404 when file is not found', function(done) { - var p = path.resolve(fixtures, 'asar', 'a.asar', 'no-exist'); + it('gets 404 when file is not found', function (done) { + var p = path.resolve(fixtures, 'asar', 'a.asar', 'no-exist') $.ajax({ - url: "file://" + p, - error: function(err) { - assert.equal(err.status, 404); - done(); + url: 'file://' + p, + error: function (err) { + assert.equal(err.status, 404) + done() } - }); - }); + }) + }) - it('sets __dirname correctly', function(done) { - after(function() { - w.destroy(); - ipcMain.removeAllListeners('dirname'); - }); + it('sets __dirname correctly', function (done) { + after(function () { + w.destroy() + ipcMain.removeAllListeners('dirname') + }) var w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - var p = path.resolve(fixtures, 'asar', 'web.asar', 'index.html'); + }) + var p = path.resolve(fixtures, 'asar', 'web.asar', 'index.html') var u = url.format({ protocol: 'file', slashed: true, pathname: p - }); - ipcMain.once('dirname', function(event, dirname) { - assert.equal(dirname, path.dirname(p)); - done(); - }); - w.loadURL(u); - }); + }) + ipcMain.once('dirname', function (event, dirname) { + assert.equal(dirname, path.dirname(p)) + done() + }) + w.loadURL(u) + }) - it('loads script tag in html', function(done) { - after(function() { - w.destroy(); - ipcMain.removeAllListeners('ping'); - }); + it('loads script tag in html', function (done) { + after(function () { + w.destroy() + ipcMain.removeAllListeners('ping') + }) var w = new BrowserWindow({ show: false, width: 400, height: 400 - }); - var p = path.resolve(fixtures, 'asar', 'script.asar', 'index.html'); + }) + var p = path.resolve(fixtures, 'asar', 'script.asar', 'index.html') var u = url.format({ protocol: 'file', slashed: true, pathname: p - }); - w.loadURL(u); - ipcMain.once('ping', function(event, message) { - assert.equal(message, 'pong'); - done(); - }); - }); - }); + }) + w.loadURL(u) + ipcMain.once('ping', function (event, message) { + assert.equal(message, 'pong') + done() + }) + }) + }) - describe('original-fs module', function() { - var originalFs = require('original-fs'); + describe('original-fs module', function () { + var originalFs = require('original-fs') - it('treats .asar as file', function() { - var file = path.join(fixtures, 'asar', 'a.asar'); - var stats = originalFs.statSync(file); - assert(stats.isFile()); - }); + it('treats .asar as file', function () { + var file = path.join(fixtures, 'asar', 'a.asar') + var stats = originalFs.statSync(file) + assert(stats.isFile()) + }) - it('is available in forked scripts', function(done) { - var child = child_process.fork(path.join(fixtures, 'module', 'original-fs.js')); - child.on('message', function(msg) { - assert.equal(msg, 'object'); - done(); - }); - child.send('message'); - }); - }); + it('is available in forked scripts', function (done) { + var child = child_process.fork(path.join(fixtures, 'module', 'original-fs.js')) + child.on('message', function (msg) { + assert.equal(msg, 'object') + done() + }) + child.send('message') + }) + }) - describe('graceful-fs module', function() { - var gfs = require('graceful-fs'); + describe('graceful-fs module', function () { + var gfs = require('graceful-fs') - it('recognize asar archvies', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'link1'); - assert.equal(gfs.readFileSync(p).toString().trim(), 'file1'); - }); - it('does not touch global fs object', function() { - assert.notEqual(fs.readdir, gfs.readdir); - }); - }); + it('recognize asar archvies', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'link1') + assert.equal(gfs.readFileSync(p).toString().trim(), 'file1') + }) + it('does not touch global fs object', function () { + assert.notEqual(fs.readdir, gfs.readdir) + }) + }) - describe('mkdirp module', function() { - var mkdirp = require('mkdirp'); + describe('mkdirp module', function () { + var mkdirp = require('mkdirp') - it('throws error when calling inside asar archive', function() { - var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist'); - assert.throws((function() { - mkdirp.sync(p); - }), new RegExp('ENOTDIR')); - }); - }); + it('throws error when calling inside asar archive', function () { + var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') + assert.throws((function () { + mkdirp.sync(p) + }), new RegExp('ENOTDIR')) + }) + }) - describe('native-image', function() { - it('reads image from asar archive', function() { - var p = path.join(fixtures, 'asar', 'logo.asar', 'logo.png'); - var logo = nativeImage.createFromPath(p); + describe('native-image', function () { + it('reads image from asar archive', function () { + var p = path.join(fixtures, 'asar', 'logo.asar', 'logo.png') + var logo = nativeImage.createFromPath(p) assert.deepEqual(logo.getSize(), { width: 55, height: 55 - }); - }); + }) + }) - it('reads image from asar archive with unpacked files', function() { - var p = path.join(fixtures, 'asar', 'unpack.asar', 'atom.png'); - var logo = nativeImage.createFromPath(p); + it('reads image from asar archive with unpacked files', function () { + var p = path.join(fixtures, 'asar', 'unpack.asar', 'atom.png') + var logo = nativeImage.createFromPath(p) assert.deepEqual(logo.getSize(), { width: 1024, height: 1024 - }); - }); - }); -}); + }) + }) + }) +}) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index ac9403a7ecd..40e46dcb5ea 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -1,432 +1,432 @@ -const assert = require('assert'); -const http = require('http'); -const path = require('path'); -const ws = require('ws'); -const remote = require('electron').remote; +const assert = require('assert') +const http = require('http') +const path = require('path') +const ws = require('ws') +const remote = require('electron').remote -const BrowserWindow = remote.require('electron').BrowserWindow; -const session = remote.require('electron').session; +const BrowserWindow = remote.require('electron').BrowserWindow +const session = remote.require('electron').session -const isCI = remote.getGlobal('isCi'); +const isCI = remote.getGlobal('isCi') -describe('chromium feature', function() { - var fixtures = path.resolve(__dirname, 'fixtures'); - var listener = null; +describe('chromium feature', function () { + var fixtures = path.resolve(__dirname, 'fixtures') + var listener = null - afterEach(function() { + afterEach(function () { if (listener != null) { - window.removeEventListener('message', listener); + window.removeEventListener('message', listener) } - listener = null; - }); + listener = null + }) - xdescribe('heap snapshot', function() { - it('does not crash', function() { - process.atomBinding('v8_util').takeHeapSnapshot(); - }); - }); + xdescribe('heap snapshot', function () { + it('does not crash', function () { + process.atomBinding('v8_util').takeHeapSnapshot() + }) + }) - describe('sending request of http protocol urls', function() { - it('does not crash', function(done) { - this.timeout(5000); + describe('sending request of http protocol urls', function () { + it('does not crash', function (done) { + this.timeout(5000) - var server = http.createServer(function(req, res) { - res.end(); - server.close(); - done(); - }); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - $.get("http://127.0.0.1:" + port); - }); - }); - }); + var server = http.createServer(function (req, res) { + res.end() + server.close() + done() + }) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + $.get('http://127.0.0.1:' + port) + }) + }) + }) - describe('document.hidden', function() { - var url = "file://" + fixtures + "/pages/document-hidden.html"; - var w = null; + describe('document.hidden', function () { + var url = 'file://' + fixtures + '/pages/document-hidden.html' + var w = null - afterEach(function() { - w != null ? w.destroy() : void 0; - }); + afterEach(function () { + w != null ? w.destroy() : void 0 + }) - it('is set correctly when window is not shown', function(done) { + it('is set correctly when window is not shown', function (done) { w = new BrowserWindow({ show: false - }); - w.webContents.on('ipc-message', function(event, args) { - assert.deepEqual(args, ['hidden', true]); - done(); - }); - w.loadURL(url); - }); + }) + w.webContents.on('ipc-message', function (event, args) { + assert.deepEqual(args, ['hidden', true]) + done() + }) + w.loadURL(url) + }) - it('is set correctly when window is inactive', function(done) { + it('is set correctly when window is inactive', function (done) { w = new BrowserWindow({ show: false - }); - w.webContents.on('ipc-message', function(event, args) { - assert.deepEqual(args, ['hidden', false]); - done(); - }); - w.showInactive(); - w.loadURL(url); - }); - }); + }) + w.webContents.on('ipc-message', function (event, args) { + assert.deepEqual(args, ['hidden', false]) + done() + }) + w.showInactive() + w.loadURL(url) + }) + }) - xdescribe('navigator.webkitGetUserMedia', function() { - it('calls its callbacks', function(done) { - this.timeout(5000); + xdescribe('navigator.webkitGetUserMedia', function () { + it('calls its callbacks', function (done) { + this.timeout(5000) navigator.webkitGetUserMedia({ audio: true, video: false - }, function() { - done(); - }, function() { - done(); - }); - }); - }); + }, function () { + done() + }, function () { + done() + }) + }) + }) - describe('navigator.mediaDevices', function() { + describe('navigator.mediaDevices', function () { if (process.env.TRAVIS === 'true') { - return; + return } if (isCI && process.platform === 'linux') { - return; + return } - it('can return labels of enumerated devices', function(done) { + it('can return labels of enumerated devices', function (done) { navigator.mediaDevices.enumerateDevices().then((devices) => { - const labels = devices.map((device) => device.label); - const labelFound = labels.some((label) => !!label); + const labels = devices.map((device) => device.label) + const labelFound = labels.some((label) => !!label) if (labelFound) - done(); + done() else - done('No device labels found: ' + JSON.stringify(labels)); - }).catch(done); - }); - }); + done('No device labels found: ' + JSON.stringify(labels)) + }).catch(done) + }) + }) - describe('navigator.language', function() { - it('should not be empty', function() { - assert.notEqual(navigator.language, ''); - }); - }); + describe('navigator.language', function () { + it('should not be empty', function () { + assert.notEqual(navigator.language, '') + }) + }) - describe('navigator.serviceWorker', function() { - var url = "file://" + fixtures + "/pages/service-worker/index.html"; - var w = null; + describe('navigator.serviceWorker', function () { + var url = 'file://' + fixtures + '/pages/service-worker/index.html' + var w = null - afterEach(function() { - w != null ? w.destroy() : void 0; - }); + afterEach(function () { + w != null ? w.destroy() : void 0 + }) - it('should register for file scheme', function(done) { + it('should register for file scheme', function (done) { w = new BrowserWindow({ show: false - }); - w.webContents.on('ipc-message', function(event, args) { + }) + w.webContents.on('ipc-message', function (event, args) { if (args[0] === 'reload') { - w.webContents.reload(); + w.webContents.reload() } else if (args[0] === 'error') { - done('unexpected error : ' + args[1]); + done('unexpected error : ' + args[1]) } else if (args[0] === 'response') { - assert.equal(args[1], 'Hello from serviceWorker!'); + assert.equal(args[1], 'Hello from serviceWorker!') session.defaultSession.clearStorageData({ storages: ['serviceworkers'] - }, function() { - done(); - }); + }, function () { + done() + }) } - }); - w.loadURL(url); - }); - }); + }) + w.loadURL(url) + }) + }) - describe('window.open', function() { - this.timeout(20000); + describe('window.open', function () { + this.timeout(20000) - it('returns a BrowserWindowProxy object', function() { - var b = window.open('about:blank', '', 'show=no'); - assert.equal(b.closed, false); - assert.equal(b.constructor.name, 'BrowserWindowProxy'); - b.close(); - }); + it('returns a BrowserWindowProxy object', function () { + var b = window.open('about:blank', '', 'show=no') + assert.equal(b.closed, false) + assert.equal(b.constructor.name, 'BrowserWindowProxy') + b.close() + }) - it('accepts "nodeIntegration" as feature', function(done) { - var b; - listener = function(event) { - assert.equal(event.data, 'undefined'); - b.close(); - done(); - }; - window.addEventListener('message', listener); - b = window.open("file://" + fixtures + "/pages/window-opener-node.html", '', 'nodeIntegration=no,show=no'); - }); + it('accepts "nodeIntegration" as feature', function (done) { + var b + listener = function (event) { + assert.equal(event.data, 'undefined') + b.close() + done() + } + window.addEventListener('message', listener) + b = window.open('file://' + fixtures + '/pages/window-opener-node.html', '', 'nodeIntegration=no,show=no') + }) - it('inherit options of parent window', function(done) { - var b; - listener = function(event) { - var height, ref1, width; - ref1 = remote.getCurrentWindow().getSize(), width = ref1[0], height = ref1[1]; - assert.equal(event.data, "size: " + width + " " + height); - b.close(); - done(); - }; - window.addEventListener('message', listener); - b = window.open("file://" + fixtures + "/pages/window-open-size.html", '', 'show=no'); - }); + it('inherit options of parent window', function (done) { + var b + listener = function (event) { + var height, ref1, width + ref1 = remote.getCurrentWindow().getSize(), width = ref1[0], height = ref1[1] + assert.equal(event.data, 'size: ' + width + ' ' + height) + b.close() + done() + } + window.addEventListener('message', listener) + b = window.open('file://' + fixtures + '/pages/window-open-size.html', '', 'show=no') + }) - it('does not override child options', function(done) { - var b, size; + it('does not override child options', function (done) { + var b, size size = { width: 350, height: 450 - }; - listener = function(event) { - assert.equal(event.data, "size: " + size.width + " " + size.height); - b.close(); - done(); - }; - window.addEventListener('message', listener); - b = window.open("file://" + fixtures + "/pages/window-open-size.html", '', "show=no,width=" + size.width + ",height=" + size.height); - }); + } + listener = function (event) { + assert.equal(event.data, 'size: ' + size.width + ' ' + size.height) + b.close() + done() + } + window.addEventListener('message', listener) + b = window.open('file://' + fixtures + '/pages/window-open-size.html', '', 'show=no,width=' + size.width + ',height=' + size.height) + }) - it('defines a window.location getter', function(done) { - var b, targetURL; - targetURL = "file://" + fixtures + "/pages/base-page.html"; - b = window.open(targetURL); - BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { - assert.equal(b.location, targetURL); - b.close(); - done(); - }); - }); + it('defines a window.location getter', function (done) { + var b, targetURL + targetURL = 'file://' + fixtures + '/pages/base-page.html' + b = window.open(targetURL) + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { + assert.equal(b.location, targetURL) + b.close() + done() + }) + }) - it('defines a window.location setter', function(done) { + it('defines a window.location setter', function (done) { // Load a page that definitely won't redirect - var b; - b = window.open("about:blank"); - BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { + var b + b = window.open('about:blank') + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { // When it loads, redirect - b.location = "file://" + fixtures + "/pages/base-page.html"; - BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { + b.location = 'file://' + fixtures + '/pages/base-page.html' + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { // After our second redirect, cleanup and callback - b.close(); - done(); - }); - }); - }); - }); + b.close() + done() + }) + }) + }) + }) - describe('window.opener', function() { - this.timeout(10000); + describe('window.opener', function () { + this.timeout(10000) - var url = "file://" + fixtures + "/pages/window-opener.html"; - var w = null; + var url = 'file://' + fixtures + '/pages/window-opener.html' + var w = null - afterEach(function() { - w != null ? w.destroy() : void 0; - }); + afterEach(function () { + w != null ? w.destroy() : void 0 + }) - it('is null for main window', function(done) { + it('is null for main window', function (done) { w = new BrowserWindow({ show: false - }); - w.webContents.on('ipc-message', function(event, args) { - assert.deepEqual(args, ['opener', null]); - done(); - }); - w.loadURL(url); - }); + }) + w.webContents.on('ipc-message', function (event, args) { + assert.deepEqual(args, ['opener', null]) + done() + }) + w.loadURL(url) + }) - it('is not null for window opened by window.open', function(done) { - var b; - listener = function(event) { - assert.equal(event.data, 'object'); - b.close(); - done(); - }; - window.addEventListener('message', listener); - b = window.open(url, '', 'show=no'); - }); - }); - - describe('window.postMessage', function() { - it('sets the source and origin correctly', function(done) { - var b, sourceId; - sourceId = remote.getCurrentWindow().id; - listener = function(event) { - window.removeEventListener('message', listener); - b.close(); - var message = JSON.parse(event.data); - assert.equal(message.data, 'testing'); - assert.equal(message.origin, 'file://'); - assert.equal(message.sourceEqualsOpener, true); - assert.equal(message.sourceId, sourceId); - assert.equal(event.origin, 'file://'); - done(); - }; - window.addEventListener('message', listener); - b = window.open("file://" + fixtures + "/pages/window-open-postMessage.html", '', 'show=no'); - BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function() { - b.postMessage('testing', '*'); - }); - }); - }); - - describe('window.opener.postMessage', function() { - it('sets source and origin correctly', function(done) { - var b; - listener = function(event) { - window.removeEventListener('message', listener); - b.close(); - assert.equal(event.source, b); - 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', function() { - it('does not crash', function() { - var RUint8Array = remote.getGlobal('Uint8Array'); - new RUint8Array; - }); - }); - - describe('webgl', function() { - it('can be get as context in canvas', function() { - if (process.platform === 'linux') { - return; + it('is not null for window opened by window.open', function (done) { + var b + listener = function (event) { + assert.equal(event.data, 'object') + b.close() + done() } - var webgl = document.createElement('canvas').getContext('webgl'); - assert.notEqual(webgl, null); - }); - }); + window.addEventListener('message', listener) + b = window.open(url, '', 'show=no') + }) + }) - describe('web workers', function() { - it('Worker can work', function(done) { - var worker = new Worker('../fixtures/workers/worker.js'); - var message = 'ping'; - worker.onmessage = function(event) { - assert.equal(event.data, message); - worker.terminate(); - done(); - }; - worker.postMessage(message); - }); + describe('window.postMessage', function () { + it('sets the source and origin correctly', function (done) { + var b, sourceId + sourceId = remote.getCurrentWindow().id + listener = function (event) { + window.removeEventListener('message', listener) + b.close() + var message = JSON.parse(event.data) + assert.equal(message.data, 'testing') + assert.equal(message.origin, 'file://') + assert.equal(message.sourceEqualsOpener, true) + assert.equal(message.sourceId, sourceId) + assert.equal(event.origin, 'file://') + done() + } + window.addEventListener('message', listener) + b = window.open('file://' + fixtures + '/pages/window-open-postMessage.html', '', 'show=no') + BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { + b.postMessage('testing', '*') + }) + }) + }) - it('SharedWorker can work', function(done) { - var worker = new SharedWorker('../fixtures/workers/shared_worker.js'); - var message = 'ping'; - worker.port.onmessage = function(event) { - assert.equal(event.data, message); - done(); - }; - worker.port.postMessage(message); - }); - }); + describe('window.opener.postMessage', function () { + it('sets source and origin correctly', function (done) { + var b + listener = function (event) { + window.removeEventListener('message', listener) + b.close() + assert.equal(event.source, b) + assert.equal(event.origin, 'file://') + done() + } + window.addEventListener('message', listener) + b = window.open('file://' + fixtures + '/pages/window-opener-postMessage.html', '', 'show=no') + }) + }) - describe('iframe', function() { - var iframe = null; + describe('creating a Uint8Array under browser side', function () { + it('does not crash', function () { + var RUint8Array = remote.getGlobal('Uint8Array') + new RUint8Array + }) + }) - beforeEach(function() { - iframe = document.createElement('iframe'); - }); + describe('webgl', function () { + it('can be get as context in canvas', function () { + if (process.platform === 'linux') { + return + } + var webgl = document.createElement('canvas').getContext('webgl') + assert.notEqual(webgl, null) + }) + }) - afterEach(function() { - document.body.removeChild(iframe); - }); + describe('web workers', function () { + it('Worker can work', function (done) { + var worker = new Worker('../fixtures/workers/worker.js') + var message = 'ping' + worker.onmessage = function (event) { + assert.equal(event.data, message) + worker.terminate() + done() + } + worker.postMessage(message) + }) - it('does not have node integration', function(done) { - iframe.src = "file://" + fixtures + "/pages/set-global.html"; - document.body.appendChild(iframe); - iframe.onload = function() { - assert.equal(iframe.contentWindow.test, 'undefined undefined undefined'); - done(); - }; - }); - }); + it('SharedWorker can work', function (done) { + var worker = new SharedWorker('../fixtures/workers/shared_worker.js') + var message = 'ping' + worker.port.onmessage = function (event) { + assert.equal(event.data, message) + done() + } + worker.port.postMessage(message) + }) + }) - describe('storage', function() { - it('requesting persitent quota works', function(done) { - navigator.webkitPersistentStorage.requestQuota(1024 * 1024, function(grantedBytes) { - assert.equal(grantedBytes, 1048576); - done(); - }); - }); - }); + describe('iframe', function () { + var iframe = null - describe('websockets', function() { - var wss = null; - var server = null; - var WebSocketServer = ws.Server; + beforeEach(function () { + iframe = document.createElement('iframe') + }) - afterEach(function() { - wss.close(); - server.close(); - }); + afterEach(function () { + document.body.removeChild(iframe) + }) - it('has user agent', function(done) { - server = http.createServer(); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; + it('does not have node integration', function (done) { + iframe.src = 'file://' + fixtures + '/pages/set-global.html' + document.body.appendChild(iframe) + iframe.onload = function () { + assert.equal(iframe.contentWindow.test, 'undefined undefined undefined') + done() + } + }) + }) + + describe('storage', function () { + it('requesting persitent quota works', function (done) { + navigator.webkitPersistentStorage.requestQuota(1024 * 1024, function (grantedBytes) { + assert.equal(grantedBytes, 1048576) + done() + }) + }) + }) + + describe('websockets', function () { + var wss = null + var server = null + var WebSocketServer = ws.Server + + afterEach(function () { + wss.close() + server.close() + }) + + it('has user agent', function (done) { + server = http.createServer() + server.listen(0, '127.0.0.1', function () { + var port = server.address().port wss = new WebSocketServer({ server: server - }); - wss.on('error', done); - wss.on('connection', function(ws) { + }) + wss.on('error', done) + wss.on('connection', function (ws) { if (ws.upgradeReq.headers['user-agent']) { - done(); + done() } else { - done('user agent is empty'); + done('user agent is empty') } - }); - new WebSocket("ws://127.0.0.1:" + port); - }); - }); - }); + }) + new WebSocket('ws://127.0.0.1:' + port) + }) + }) + }) - describe('Promise', function() { - it('resolves correctly in Node.js calls', function(done) { + describe('Promise', function () { + it('resolves correctly in Node.js calls', function (done) { document.registerElement('x-element', { prototype: Object.create(HTMLElement.prototype, { createdCallback: { - value: function() {} + value: function () {} } }) - }); - setImmediate(function() { - var called = false; - Promise.resolve().then(function() { - done(called ? void 0 : new Error('wrong sequence')); - }); - document.createElement('x-element'); - called = true; - }); - }); + }) + setImmediate(function () { + var called = false + Promise.resolve().then(function () { + done(called ? void 0 : new Error('wrong sequence')) + }) + document.createElement('x-element') + called = true + }) + }) - it('resolves correctly in Electron calls', function(done) { + it('resolves correctly in Electron calls', function (done) { document.registerElement('y-element', { prototype: Object.create(HTMLElement.prototype, { createdCallback: { - value: function() {} + value: function () {} } }) - }); - remote.getGlobal('setImmediate')(function() { - var called = false; - Promise.resolve().then(function() { - done(called ? void 0 : new Error('wrong sequence')); - }); - document.createElement('y-element'); - called = true; - }); - }); - }); -}); + }) + remote.getGlobal('setImmediate')(function () { + var called = false + Promise.resolve().then(function () { + done(called ? void 0 : new Error('wrong sequence')) + }) + document.createElement('y-element') + called = true + }) + }) + }) +}) diff --git a/spec/fixtures/api/quit-app/main.js b/spec/fixtures/api/quit-app/main.js index 114e830076a..e2f97affe6d 100644 --- a/spec/fixtures/api/quit-app/main.js +++ b/spec/fixtures/api/quit-app/main.js @@ -1,12 +1,12 @@ -var app = require('electron').app; +var app = require('electron').app app.on('ready', function () { // This setImmediate call gets the spec passing on Linux setImmediate(function () { - app.exit(123); - }); -}); + app.exit(123) + }) +}) process.on('exit', function (code) { - console.log('Exit event with code: ' + code); -}); + console.log('Exit event with code: ' + code) +}) diff --git a/spec/fixtures/module/asar.js b/spec/fixtures/module/asar.js index 1fb8750878a..e01b64a2eca 100644 --- a/spec/fixtures/module/asar.js +++ b/spec/fixtures/module/asar.js @@ -1,4 +1,4 @@ -var fs = require('fs'); -process.on('message', function(file) { - process.send(fs.readFileSync(file).toString()); -}); +var fs = require('fs') +process.on('message', function (file) { + process.send(fs.readFileSync(file).toString()) +}) diff --git a/spec/fixtures/module/call.js b/spec/fixtures/module/call.js index ce0eb6324df..d09d677199b 100644 --- a/spec/fixtures/module/call.js +++ b/spec/fixtures/module/call.js @@ -1,7 +1,7 @@ -exports.call = function(func) { - return func(); -}; +exports.call = function (func) { + return func() +} -exports.constructor = function() { - this.test = 'test'; -}; +exports.constructor = function () { + this.test = 'test' +} diff --git a/spec/fixtures/module/class.js b/spec/fixtures/module/class.js index f25eb2593ff..c961dd8040c 100644 --- a/spec/fixtures/module/class.js +++ b/spec/fixtures/module/class.js @@ -1,22 +1,22 @@ -'use strict'; +'use strict' -let value = 'old'; +let value = 'old' class BaseClass { - method() { - return 'method'; + method () { + return 'method' } - get readonly() { - return 'readonly'; + get readonly () { + return 'readonly' } - get value() { - return value; + get value () { + return value } - set value(val) { - value = val; + set value (val) { + value = val } } diff --git a/spec/fixtures/module/create_socket.js b/spec/fixtures/module/create_socket.js index 2a8b475c519..2528b993d65 100644 --- a/spec/fixtures/module/create_socket.js +++ b/spec/fixtures/module/create_socket.js @@ -1,4 +1,4 @@ -var net = require('net'); -var server = net.createServer(function() {}); -server.listen(process.argv[2]); -process.exit(0); +var net = require('net') +var server = net.createServer(function () {}) +server.listen(process.argv[2]) +process.exit(0) diff --git a/spec/fixtures/module/fork_ping.js b/spec/fixtures/module/fork_ping.js index a43f7d8dce7..76bf1b0e368 100644 --- a/spec/fixtures/module/fork_ping.js +++ b/spec/fixtures/module/fork_ping.js @@ -1,14 +1,14 @@ -process.on('uncaughtException', function(error) { - process.send(error.stack); -}); +process.on('uncaughtException', function (error) { + process.send(error.stack) +}) -var child = require('child_process').fork(__dirname + '/ping.js'); -process.on('message', function(msg) { - child.send(msg); -}); +var child = require('child_process').fork(__dirname + '/ping.js') +process.on('message', function (msg) { + child.send(msg) +}) child.on('message', function (msg) { - process.send(msg); -}); -child.on('exit', function(code) { - process.exit(code); -}); + process.send(msg) +}) +child.on('exit', function (code) { + process.exit(code) +}) diff --git a/spec/fixtures/module/function.js b/spec/fixtures/module/function.js index 803a2838d37..526daf76fa8 100644 --- a/spec/fixtures/module/function.js +++ b/spec/fixtures/module/function.js @@ -1 +1 @@ -exports.aFunction = function() { return 1127; }; +exports.aFunction = function () { return 1127; } diff --git a/spec/fixtures/module/id.js b/spec/fixtures/module/id.js index 5bfae457fe0..2faec9d3832 100644 --- a/spec/fixtures/module/id.js +++ b/spec/fixtures/module/id.js @@ -1 +1 @@ -exports.id = 1127; +exports.id = 1127 diff --git a/spec/fixtures/module/locale-compare.js b/spec/fixtures/module/locale-compare.js index 32dfb309926..3446e2f443d 100644 --- a/spec/fixtures/module/locale-compare.js +++ b/spec/fixtures/module/locale-compare.js @@ -3,5 +3,5 @@ process.on('message', function () { 'a'.localeCompare('a'), 'ä'.localeCompare('z', 'de'), 'ä'.localeCompare('a', 'sv', { sensitivity: 'base' }), - ]); -}); + ]) +}) diff --git a/spec/fixtures/module/original-fs.js b/spec/fixtures/module/original-fs.js index 7a527c63358..341dcb2e0de 100644 --- a/spec/fixtures/module/original-fs.js +++ b/spec/fixtures/module/original-fs.js @@ -1,3 +1,3 @@ process.on('message', function () { - process.send(typeof require('original-fs')); -}); + process.send(typeof require('original-fs')) +}) diff --git a/spec/fixtures/module/ping.js b/spec/fixtures/module/ping.js index fdb9d1ec4ce..90b3d1fb20a 100644 --- a/spec/fixtures/module/ping.js +++ b/spec/fixtures/module/ping.js @@ -1,4 +1,4 @@ -process.on('message', function(msg) { - process.send(msg); - process.exit(0); -}); +process.on('message', function (msg) { + process.send(msg) + process.exit(0) +}) diff --git a/spec/fixtures/module/preload-ipc.js b/spec/fixtures/module/preload-ipc.js index ed95055c124..3f7e5ea35ce 100644 --- a/spec/fixtures/module/preload-ipc.js +++ b/spec/fixtures/module/preload-ipc.js @@ -1,4 +1,4 @@ -var ipcRenderer = require('electron').ipcRenderer; -ipcRenderer.on('ping', function(event, message) { - ipcRenderer.sendToHost('pong', message); -}); +var ipcRenderer = require('electron').ipcRenderer +ipcRenderer.on('ping', function (event, message) { + ipcRenderer.sendToHost('pong', message) +}) diff --git a/spec/fixtures/module/preload-node-off.js b/spec/fixtures/module/preload-node-off.js index 9020f4513a1..54fe343a9ca 100644 --- a/spec/fixtures/module/preload-node-off.js +++ b/spec/fixtures/module/preload-node-off.js @@ -1,7 +1,7 @@ -setImmediate(function() { +setImmediate(function () { try { - console.log([typeof process, typeof setImmediate, typeof global].join(' ')); + console.log([typeof process, typeof setImmediate, typeof global].join(' ')) } catch (e) { - console.log(e.message); + console.log(e.message) } -}); +}) diff --git a/spec/fixtures/module/preload.js b/spec/fixtures/module/preload.js index 205a077ddb1..39c8b11fbe3 100644 --- a/spec/fixtures/module/preload.js +++ b/spec/fixtures/module/preload.js @@ -1 +1 @@ -console.log([typeof require, typeof module, typeof process].join(' ')); +console.log([typeof require, typeof module, typeof process].join(' ')) diff --git a/spec/fixtures/module/print_name.js b/spec/fixtures/module/print_name.js index 96ac2d6f3cb..db4f71d407b 100644 --- a/spec/fixtures/module/print_name.js +++ b/spec/fixtures/module/print_name.js @@ -1,7 +1,7 @@ -exports.print = function(obj) { - return obj.constructor.name; -}; +exports.print = function (obj) { + return obj.constructor.name +} -exports.echo = function(obj) { - return obj; -}; +exports.echo = function (obj) { + return obj +} diff --git a/spec/fixtures/module/process_args.js b/spec/fixtures/module/process_args.js index bba351154f6..56e3906c553 100644 --- a/spec/fixtures/module/process_args.js +++ b/spec/fixtures/module/process_args.js @@ -1,4 +1,4 @@ -process.on('message', function() { - process.send(process.argv); - process.exit(0); -}); +process.on('message', function () { + process.send(process.argv) + process.exit(0) +}) diff --git a/spec/fixtures/module/promise.js b/spec/fixtures/module/promise.js index b9b568855e3..d34058cc803 100644 --- a/spec/fixtures/module/promise.js +++ b/spec/fixtures/module/promise.js @@ -1,5 +1,5 @@ exports.twicePromise = function (promise) { return promise.then(function (value) { - return value * 2; - }); -}; + return value * 2 + }) +} diff --git a/spec/fixtures/module/property.js b/spec/fixtures/module/property.js index 36286d800e1..88e596f7308 100644 --- a/spec/fixtures/module/property.js +++ b/spec/fixtures/module/property.js @@ -1 +1 @@ -exports.property = 1127; +exports.property = 1127 diff --git a/spec/fixtures/module/runas.js b/spec/fixtures/module/runas.js index c4845e026f2..6422fce052a 100644 --- a/spec/fixtures/module/runas.js +++ b/spec/fixtures/module/runas.js @@ -1,6 +1,6 @@ -process.on('uncaughtException', function(err) { - process.send(err.message); -}); +process.on('uncaughtException', function (err) { + process.send(err.message) +}) -require('runas'); -process.send('ok'); +require('runas') +process.send('ok') diff --git a/spec/fixtures/module/send-later.js b/spec/fixtures/module/send-later.js index 704f47d328d..8eb16f72f8c 100644 --- a/spec/fixtures/module/send-later.js +++ b/spec/fixtures/module/send-later.js @@ -1,4 +1,4 @@ -var ipcRenderer = require('electron').ipcRenderer; -window.onload = function() { - ipcRenderer.send('answer', typeof window.process); -}; +var ipcRenderer = require('electron').ipcRenderer +window.onload = function () { + ipcRenderer.send('answer', typeof window.process) +} diff --git a/spec/fixtures/module/set-global.js b/spec/fixtures/module/set-global.js index f39919ff9d8..ba4f30d155b 100644 --- a/spec/fixtures/module/set-global.js +++ b/spec/fixtures/module/set-global.js @@ -1 +1 @@ -window.test = 'preload'; +window.test = 'preload' diff --git a/spec/fixtures/module/set-immediate.js b/spec/fixtures/module/set-immediate.js index d36355ee23b..69563fd0a83 100644 --- a/spec/fixtures/module/set-immediate.js +++ b/spec/fixtures/module/set-immediate.js @@ -1,11 +1,11 @@ -process.on('uncaughtException', function(error) { - process.send(error.message); - process.exit(1); -}); +process.on('uncaughtException', function (error) { + process.send(error.message) + process.exit(1) +}) -process.on('message', function() { - setImmediate(function() { - process.send('ok'); - process.exit(0); - }); -}); +process.on('message', function () { + setImmediate(function () { + process.send('ok') + process.exit(0) + }) +}) diff --git a/spec/fixtures/pages/service-worker/service-worker.js b/spec/fixtures/pages/service-worker/service-worker.js index 854b3558a95..7d80f45e2df 100644 --- a/spec/fixtures/pages/service-worker/service-worker.js +++ b/spec/fixtures/pages/service-worker/service-worker.js @@ -1,9 +1,9 @@ -self.addEventListener('fetch', function(event) { - var requestUrl = new URL(event.request.url); +self.addEventListener('fetch', function (event) { + var requestUrl = new URL(event.request.url) if (requestUrl.pathname === '/echo' && - event.request.headers.has('X-Mock-Response')) { - var mockResponse = new Response('Hello from serviceWorker!'); - event.respondWith(mockResponse); + event.request.headers.has('X-Mock-Response')) { + var mockResponse = new Response('Hello from serviceWorker!') + event.respondWith(mockResponse) } -}); +}) diff --git a/spec/fixtures/workers/shared_worker.js b/spec/fixtures/workers/shared_worker.js index 40220793979..35cb40d03b5 100644 --- a/spec/fixtures/workers/shared_worker.js +++ b/spec/fixtures/workers/shared_worker.js @@ -1,7 +1,7 @@ -this.onconnect = function(event) { - var port = event.ports[0]; - port.start(); - port.onmessage = function(event) { - port.postMessage(event.data); - }; -}; +this.onconnect = function (event) { + var port = event.ports[0] + port.start() + port.onmessage = function (event) { + port.postMessage(event.data) + } +} diff --git a/spec/fixtures/workers/worker.js b/spec/fixtures/workers/worker.js index 4f445470b9a..884c17ac86e 100644 --- a/spec/fixtures/workers/worker.js +++ b/spec/fixtures/workers/worker.js @@ -1,3 +1,3 @@ -this.onmessage = function(msg) { - this.postMessage(msg.data); -}; +this.onmessage = function (msg) { + this.postMessage(msg.data) +} diff --git a/spec/modules-spec.js b/spec/modules-spec.js index fb53a90cf73..0f694e5e6d8 100644 --- a/spec/modules-spec.js +++ b/spec/modules-spec.js @@ -1,47 +1,47 @@ -const assert = require('assert'); -const path = require('path'); -const temp = require('temp'); +const assert = require('assert') +const path = require('path') +const temp = require('temp') -describe('third-party module', function() { - var fixtures = path.join(__dirname, 'fixtures'); - temp.track(); +describe('third-party module', function () { + var fixtures = path.join(__dirname, 'fixtures') + temp.track() if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) { - describe('runas', function() { - it('can be required in renderer', function() { - require('runas'); - }); + describe('runas', function () { + it('can be required in renderer', function () { + require('runas') + }) - it('can be required in node binary', function(done) { - var runas = path.join(fixtures, 'module', 'runas.js'); - var child = require('child_process').fork(runas); - child.on('message', function(msg) { - assert.equal(msg, 'ok'); - done(); - }); - }); - }); + it('can be required in node binary', function (done) { + var runas = path.join(fixtures, 'module', 'runas.js') + var child = require('child_process').fork(runas) + child.on('message', function (msg) { + assert.equal(msg, 'ok') + done() + }) + }) + }) - describe('ffi', function() { - it('does not crash', function() { - var ffi = require('ffi'); + describe('ffi', function () { + it('does not crash', function () { + var ffi = require('ffi') var libm = ffi.Library('libm', { ceil: ['double', ['double']] - }); - assert.equal(libm.ceil(1.5), 2); - }); - }); + }) + assert.equal(libm.ceil(1.5), 2) + }) + }) } - describe('q', function() { - var Q = require('q'); - describe('Q.when', function() { - it('emits the fullfil callback', function(done) { - Q(true).then(function(val) { - assert.equal(val, true); - done(); - }); - }); - }); - }); -}); + describe('q', function () { + var Q = require('q') + describe('Q.when', function () { + it('emits the fullfil callback', function (done) { + Q(true).then(function (val) { + assert.equal(val, true) + done() + }) + }) + }) + }) +}) diff --git a/spec/node-spec.js b/spec/node-spec.js index 83f685d95f0..286c4d6f916 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -1,220 +1,220 @@ -const assert = require('assert'); -const child_process = require('child_process'); -const fs = require('fs'); -const path = require('path'); -const os = require('os'); -const remote = require('electron').remote; +const assert = require('assert') +const child_process = require('child_process') +const fs = require('fs') +const path = require('path') +const os = require('os') +const remote = require('electron').remote -describe('node feature', function() { - var fixtures = path.join(__dirname, 'fixtures'); +describe('node feature', function () { + var fixtures = path.join(__dirname, 'fixtures') - describe('child_process', function() { - describe('child_process.fork', function() { - it('works in current process', function(done) { - var child = child_process.fork(path.join(fixtures, 'module', 'ping.js')); - child.on('message', function(msg) { - assert.equal(msg, 'message'); - done(); - }); - child.send('message'); - }); + describe('child_process', function () { + describe('child_process.fork', function () { + it('works in current process', function (done) { + var child = child_process.fork(path.join(fixtures, 'module', 'ping.js')) + child.on('message', function (msg) { + assert.equal(msg, 'message') + done() + }) + child.send('message') + }) - it('preserves args', function(done) { - var args = ['--expose_gc', '-test', '1']; - var child = child_process.fork(path.join(fixtures, 'module', 'process_args.js'), args); - child.on('message', function(msg) { - assert.deepEqual(args, msg.slice(2)); - done(); - }); - child.send('message'); - }); + it('preserves args', function (done) { + var args = ['--expose_gc', '-test', '1'] + var child = child_process.fork(path.join(fixtures, 'module', 'process_args.js'), args) + child.on('message', function (msg) { + assert.deepEqual(args, msg.slice(2)) + done() + }) + child.send('message') + }) - it('works in forked process', function(done) { - var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js')); - child.on('message', function(msg) { - assert.equal(msg, 'message'); - done(); - }); - child.send('message'); - }); + it('works in forked process', function (done) { + var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js')) + child.on('message', function (msg) { + assert.equal(msg, 'message') + done() + }) + child.send('message') + }) - it('works in forked process when options.env is specifed', function(done) { + it('works in forked process when options.env is specifed', function (done) { var child = child_process.fork(path.join(fixtures, 'module', 'fork_ping.js'), [], { path: process.env['PATH'] - }); - child.on('message', function(msg) { - assert.equal(msg, 'message'); - done(); - }); - child.send('message'); - }); + }) + child.on('message', function (msg) { + assert.equal(msg, 'message') + done() + }) + child.send('message') + }) - it('works in browser process', function(done) { - var fork = remote.require('child_process').fork; - var child = fork(path.join(fixtures, 'module', 'ping.js')); - child.on('message', function(msg) { - assert.equal(msg, 'message'); - done(); - }); - child.send('message'); - }); + it('works in browser process', function (done) { + var fork = remote.require('child_process').fork + var child = fork(path.join(fixtures, 'module', 'ping.js')) + child.on('message', function (msg) { + assert.equal(msg, 'message') + done() + }) + child.send('message') + }) - it('has String::localeCompare working in script', function(done) { - var child = child_process.fork(path.join(fixtures, 'module', 'locale-compare.js')); - child.on('message', function(msg) { - assert.deepEqual(msg, [0, -1, 1]); - done(); - }); - child.send('message'); - }); + it('has String::localeCompare working in script', function (done) { + var child = child_process.fork(path.join(fixtures, 'module', 'locale-compare.js')) + child.on('message', function (msg) { + assert.deepEqual(msg, [0, -1, 1]) + done() + }) + child.send('message') + }) - it('has setImmediate working in script', function(done) { - var child = child_process.fork(path.join(fixtures, 'module', 'set-immediate.js')); - child.on('message', function(msg) { - assert.equal(msg, 'ok'); - done(); - }); - child.send('message'); - }); - }); - }); + it('has setImmediate working in script', function (done) { + var child = child_process.fork(path.join(fixtures, 'module', 'set-immediate.js')) + child.on('message', function (msg) { + assert.equal(msg, 'ok') + done() + }) + child.send('message') + }) + }) + }) - describe('contexts', function() { - describe('setTimeout in fs callback', function() { + describe('contexts', function () { + describe('setTimeout in fs callback', function () { if (process.env.TRAVIS === 'true') { - return; + return } - it('does not crash', function(done) { - fs.readFile(__filename, function() { - setTimeout(done, 0); - }); - }); - }); + it('does not crash', function (done) { + fs.readFile(__filename, function () { + setTimeout(done, 0) + }) + }) + }) - describe('throw error in node context', function() { - it('gets caught', function(done) { - var error = new Error('boo!'); - var lsts = process.listeners('uncaughtException'); - process.removeAllListeners('uncaughtException'); - process.on('uncaughtException', function() { - var i, len, lst; - process.removeAllListeners('uncaughtException'); + describe('throw error in node context', function () { + it('gets caught', function (done) { + var error = new Error('boo!') + var lsts = process.listeners('uncaughtException') + process.removeAllListeners('uncaughtException') + process.on('uncaughtException', function () { + var i, len, lst + process.removeAllListeners('uncaughtException') for (i = 0, len = lsts.length; i < len; i++) { - lst = lsts[i]; - process.on('uncaughtException', lst); + lst = lsts[i] + process.on('uncaughtException', lst) } - done(); - }); - fs.readFile(__filename, function() { - throw error; - }); - }); - }); + done() + }) + fs.readFile(__filename, function () { + throw error + }) + }) + }) - describe('setTimeout called under Chromium event loop in browser process', function() { - it('can be scheduled in time', function(done) { - remote.getGlobal('setTimeout')(done, 0); - }); - }); + describe('setTimeout called under Chromium event loop in browser process', function () { + it('can be scheduled in time', function (done) { + remote.getGlobal('setTimeout')(done, 0) + }) + }) - describe('setInterval called under Chromium event loop in browser process', function() { - it('can be scheduled in time', function(done) { - var clear, interval; - clear = function() { - remote.getGlobal('clearInterval')(interval); - done(); - }; - interval = remote.getGlobal('setInterval')(clear, 10); - }); - }); - }); + describe('setInterval called under Chromium event loop in browser process', function () { + it('can be scheduled in time', function (done) { + var clear, interval + clear = function () { + remote.getGlobal('clearInterval')(interval) + done() + } + interval = remote.getGlobal('setInterval')(clear, 10) + }) + }) + }) - describe('message loop', function() { - describe('process.nextTick', function() { - it('emits the callback', function(done) { - process.nextTick(done); - }); + describe('message loop', function () { + describe('process.nextTick', function () { + it('emits the callback', function (done) { + process.nextTick(done) + }) - it('works in nested calls', function(done) { - process.nextTick(function() { - process.nextTick(function() { - process.nextTick(done); - }); - }); - }); - }); + it('works in nested calls', function (done) { + process.nextTick(function () { + process.nextTick(function () { + process.nextTick(done) + }) + }) + }) + }) - describe('setImmediate', function() { - it('emits the callback', function(done) { - setImmediate(done); - }); + describe('setImmediate', function () { + it('emits the callback', function (done) { + setImmediate(done) + }) - it('works in nested calls', function(done) { - setImmediate(function() { - setImmediate(function() { - setImmediate(done); - }); - }); - }); - }); - }); + it('works in nested calls', function (done) { + setImmediate(function () { + setImmediate(function () { + setImmediate(done) + }) + }) + }) + }) + }) - describe('net.connect', function() { + describe('net.connect', function () { if (process.platform !== 'darwin') { - return; + return } - it('emit error when connect to a socket path without listeners', function(done) { - var socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock'); - var script = path.join(fixtures, 'module', 'create_socket.js'); - var child = child_process.fork(script, [socketPath]); - child.on('exit', function(code) { - assert.equal(code, 0); - var client = require('net').connect(socketPath); - client.on('error', function(error) { - assert.equal(error.code, 'ECONNREFUSED'); - done(); - }); - }); - }); - }); + it('emit error when connect to a socket path without listeners', function (done) { + var socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock') + var script = path.join(fixtures, 'module', 'create_socket.js') + var child = child_process.fork(script, [socketPath]) + child.on('exit', function (code) { + assert.equal(code, 0) + var client = require('net').connect(socketPath) + client.on('error', function (error) { + assert.equal(error.code, 'ECONNREFUSED') + done() + }) + }) + }) + }) - describe('Buffer', function() { - it('can be created from WebKit external string', function() { - var p = document.createElement('p'); - p.innerText = '闲云潭影日悠悠,物换星移几度秋'; - var b = new Buffer(p.innerText); - assert.equal(b.toString(), '闲云潭影日悠悠,物换星移几度秋'); - assert.equal(Buffer.byteLength(p.innerText), 45); - }); + describe('Buffer', function () { + it('can be created from WebKit external string', function () { + var p = document.createElement('p') + p.innerText = '闲云潭影日悠悠,物换星移几度秋' + var b = new Buffer(p.innerText) + assert.equal(b.toString(), '闲云潭影日悠悠,物换星移几度秋') + assert.equal(Buffer.byteLength(p.innerText), 45) + }) - it('correctly parses external one-byte UTF8 string', function() { - var p = document.createElement('p'); - p.innerText = 'Jøhänñéß'; - var b = new Buffer(p.innerText); - assert.equal(b.toString(), 'Jøhänñéß'); - assert.equal(Buffer.byteLength(p.innerText), 13); - }); - }); + it('correctly parses external one-byte UTF8 string', function () { + var p = document.createElement('p') + p.innerText = 'Jøhänñéß' + var b = new Buffer(p.innerText) + assert.equal(b.toString(), 'Jøhänñéß') + assert.equal(Buffer.byteLength(p.innerText), 13) + }) + }) - describe('process.stdout', function() { - it('should not throw exception', function() { - process.stdout; - }); + describe('process.stdout', function () { + it('should not throw exception', function () { + process.stdout + }) - it('should not throw exception when calling write()', function() { - process.stdout.write('test'); - }); + it('should not throw exception when calling write()', function () { + process.stdout.write('test') + }) - xit('should have isTTY defined', function() { - assert.equal(typeof process.stdout.isTTY, 'boolean'); - }); - }); + xit('should have isTTY defined', function () { + assert.equal(typeof process.stdout.isTTY, 'boolean') + }) + }) - describe('vm.createContext', function() { - it('should not crash', function() { - require('vm').runInNewContext(''); - }); - }); -}); + describe('vm.createContext', function () { + it('should not crash', function () { + require('vm').runInNewContext('') + }) + }) +}) diff --git a/spec/static/main.js b/spec/static/main.js index 77a3c392722..f1d2a5eafa6 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -1,81 +1,81 @@ // Disable use of deprecated functions. -process.throwDeprecation = true; +process.throwDeprecation = true -const electron = require('electron'); -const app = electron.app; -const ipcMain = electron.ipcMain; -const dialog = electron.dialog; -const BrowserWindow = electron.BrowserWindow; +const electron = require('electron') +const app = electron.app +const ipcMain = electron.ipcMain +const dialog = electron.dialog +const BrowserWindow = electron.BrowserWindow -const path = require('path'); -const url = require('url'); +const path = require('path') +const url = require('url') var argv = require('yargs') .boolean('ci') .string('g').alias('g', 'grep') .boolean('i').alias('i', 'invert') - .argv; + .argv -var window = null; -process.port = 0; // will be used by crash-reporter spec. +var window = null +process.port = 0; // will be used by crash-reporter spec. -app.commandLine.appendSwitch('js-flags', '--expose_gc'); -app.commandLine.appendSwitch('ignore-certificate-errors'); -app.commandLine.appendSwitch('disable-renderer-backgrounding'); +app.commandLine.appendSwitch('js-flags', '--expose_gc') +app.commandLine.appendSwitch('ignore-certificate-errors') +app.commandLine.appendSwitch('disable-renderer-backgrounding') // 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; +process.stdout // Access console to reproduce #3482. -console; +console -ipcMain.on('message', function(event, arg) { - event.sender.send('message', arg); -}); +ipcMain.on('message', function (event, arg) { + event.sender.send('message', arg) +}) -ipcMain.on('console.log', function(event, args) { - console.error.apply(console, args); -}); +ipcMain.on('console.log', function (event, args) { + console.error.apply(console, args) +}) -ipcMain.on('console.error', function(event, args) { - console.error.apply(console, args); -}); +ipcMain.on('console.error', function (event, args) { + console.error.apply(console, args) +}) -ipcMain.on('process.exit', function(event, code) { - process.exit(code); -}); +ipcMain.on('process.exit', function (event, code) { + process.exit(code) +}) -ipcMain.on('eval', function(event, script) { - event.returnValue = eval(script); -}); +ipcMain.on('eval', function (event, script) { + event.returnValue = eval(script) +}) -ipcMain.on('echo', function(event, msg) { - event.returnValue = msg; -}); +ipcMain.on('echo', function (event, msg) { + event.returnValue = msg +}) -global.isCi = !!argv.ci; +global.isCi = !!argv.ci if (global.isCi) { - process.removeAllListeners('uncaughtException'); - process.on('uncaughtException', function(error) { - console.error(error, error.stack); - process.exit(1); - }); + process.removeAllListeners('uncaughtException') + process.on('uncaughtException', function (error) { + console.error(error, error.stack) + process.exit(1) + }) } -app.on('window-all-closed', function() { - app.quit(); -}); +app.on('window-all-closed', function () { + app.quit() +}) -app.on('ready', function() { +app.on('ready', function () { // Test if using protocol module would crash. - electron.protocol.registerStringProtocol('test-if-crashes', function() {}); + electron.protocol.registerStringProtocol('test-if-crashes', function () {}) // Send auto updater errors to window to be verified in specs electron.autoUpdater.on('error', function (error) { - window.send('auto-updater-error', error.message); - }); + window.send('auto-updater-error', error.message) + }) window = new BrowserWindow({ title: 'Electron Tests', @@ -83,70 +83,70 @@ app.on('ready', function() { width: 800, height: 600, webPreferences: { - javascript: true // Test whether web preferences crashes. + javascript: true // Test whether web preferences crashes. }, - }); + }) window.loadURL(url.format({ pathname: __dirname + '/index.html', protocol: 'file', query: { grep: argv.grep, - invert: argv.invert ? 'true': '' + invert: argv.invert ? 'true' : '' } - })); - window.on('unresponsive', function() { + })) + window.on('unresponsive', function () { var chosen = dialog.showMessageBox(window, { type: 'warning', buttons: ['Close', 'Keep Waiting'], message: 'Window is not responsing', detail: 'The window is not responding. Would you like to force close it or just keep waiting?' - }); - if (chosen === 0) window.destroy(); - }); + }) + if (chosen === 0) window.destroy() + }) // For session's download test, listen 'will-download' event in browser, and // reply the result to renderer for verifying - var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); - ipcMain.on('set-download-option', function(event, need_cancel, prevent_default) { - window.webContents.session.once('will-download', function(e, item) { + var downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf') + ipcMain.on('set-download-option', function (event, need_cancel, prevent_default) { + window.webContents.session.once('will-download', function (e, item) { if (prevent_default) { - e.preventDefault(); - const url = item.getURL(); - const filename = item.getFilename(); - setImmediate(function() { + e.preventDefault() + const url = item.getURL() + const filename = item.getFilename() + setImmediate(function () { try { - item.getURL(); + item.getURL() } catch(err) { - window.webContents.send('download-error', url, filename, err.message); + window.webContents.send('download-error', url, filename, err.message) } - }); + }) } else { - item.setSavePath(downloadFilePath); - item.on('done', function(e, state) { + item.setSavePath(downloadFilePath) + item.on('done', function (e, state) { window.webContents.send('download-done', - state, - item.getURL(), - item.getMimeType(), - item.getReceivedBytes(), - item.getTotalBytes(), - item.getContentDisposition(), - item.getFilename()); - }); + state, + item.getURL(), + item.getMimeType(), + item.getReceivedBytes(), + item.getTotalBytes(), + item.getContentDisposition(), + item.getFilename()) + }) if (need_cancel) - item.cancel(); + item.cancel() } - }); - event.returnValue = "done"; - }); + }) + event.returnValue = 'done' + }) - ipcMain.on('executeJavaScript', function(event, code, hasCallback) { + ipcMain.on('executeJavaScript', function (event, code, hasCallback) { if (hasCallback) { window.webContents.executeJavaScript(code, (result) => { - window.webContents.send('executeJavaScript-response', result); - }); + window.webContents.send('executeJavaScript-response', result) + }) } else { - window.webContents.executeJavaScript(code); - event.returnValue = "success"; + window.webContents.executeJavaScript(code) + event.returnValue = 'success' } - }); -}); + }) +}) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 2d0a6282be3..1bb18c0b5e7 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -1,746 +1,746 @@ -const assert = require('assert'); -const path = require('path'); -const http = require('http'); -const url = require('url'); +const assert = require('assert') +const path = require('path') +const http = require('http') +const url = require('url') -describe(' tag', function() { - this.timeout(10000); +describe(' tag', function () { + this.timeout(10000) - var fixtures = path.join(__dirname, 'fixtures'); - var webview = null; + var fixtures = path.join(__dirname, 'fixtures') + var webview = null - beforeEach(function() { - webview = new WebView; - }); + beforeEach(function () { + webview = new WebView + }) - afterEach(function() { + afterEach(function () { if (document.body.contains(webview)) { - document.body.removeChild(webview); + document.body.removeChild(webview) } - }); + }) - describe('src attribute', function() { - it('specifies the page to load', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'a'); - done(); - }); - webview.src = "file://" + fixtures + "/pages/a.html"; - document.body.appendChild(webview); - }); + describe('src attribute', function () { + it('specifies the page to load', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'a') + done() + }) + webview.src = 'file://' + fixtures + '/pages/a.html' + document.body.appendChild(webview) + }) - it('navigates to new page when changed', function(done) { - var listener = function() { - webview.src = "file://" + fixtures + "/pages/b.html"; - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'b'); - done(); - }); - webview.removeEventListener('did-finish-load', listener); - }; - webview.addEventListener('did-finish-load', listener); - webview.src = "file://" + fixtures + "/pages/a.html"; - document.body.appendChild(webview); - }); - }); + it('navigates to new page when changed', function (done) { + var listener = function () { + webview.src = 'file://' + fixtures + '/pages/b.html' + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'b') + done() + }) + webview.removeEventListener('did-finish-load', listener) + } + webview.addEventListener('did-finish-load', listener) + webview.src = 'file://' + fixtures + '/pages/a.html' + document.body.appendChild(webview) + }) + }) - describe('nodeintegration attribute', function() { - it('inserts no node symbols when not set', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'undefined undefined undefined undefined'); - done(); - }); - webview.src = "file://" + fixtures + "/pages/c.html"; - document.body.appendChild(webview); - }); + describe('nodeintegration attribute', function () { + it('inserts no node symbols when not set', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'undefined undefined undefined undefined') + done() + }) + webview.src = 'file://' + fixtures + '/pages/c.html' + document.body.appendChild(webview) + }) - it('inserts node symbols when set', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'function object object'); - done(); - }); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/d.html"; - document.body.appendChild(webview); - }); + it('inserts node symbols when set', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'function object object') + done() + }) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/d.html' + document.body.appendChild(webview) + }) - it('loads node symbols after POST navigation when set', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'function object object'); - done(); - }); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/post.html"; - document.body.appendChild(webview); - }); + it('loads node symbols after POST navigation when set', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'function object object') + done() + }) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/post.html' + document.body.appendChild(webview) + }) if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) { - it('loads native modules when navigation happens', function(done) { - var listener = function() { - webview.removeEventListener('did-finish-load', listener); - var listener2 = function(e) { - assert.equal(e.message, 'function'); - done(); - }; - webview.addEventListener('console-message', listener2); - webview.reload(); - }; - webview.addEventListener('did-finish-load', listener); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/native-module.html"; - document.body.appendChild(webview); - }); + it('loads native modules when navigation happens', function (done) { + var listener = function () { + webview.removeEventListener('did-finish-load', listener) + var listener2 = function (e) { + assert.equal(e.message, 'function') + done() + } + webview.addEventListener('console-message', listener2) + webview.reload() + } + webview.addEventListener('did-finish-load', listener) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/native-module.html' + document.body.appendChild(webview) + }) } - }); + }) - describe('preload attribute', function() { - it('loads the script before other scripts in window', function(done) { - var listener = function(e) { - assert.equal(e.message, 'function object object'); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.setAttribute('preload', fixtures + "/module/preload.js"); - webview.src = "file://" + fixtures + "/pages/e.html"; - document.body.appendChild(webview); - }); + describe('preload attribute', function () { + it('loads the script before other scripts in window', function (done) { + var listener = function (e) { + assert.equal(e.message, 'function object object') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('preload', fixtures + '/module/preload.js') + webview.src = 'file://' + fixtures + '/pages/e.html' + document.body.appendChild(webview) + }) - it('preload script can still use "process" in required modules when nodeintegration is off', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'object undefined object'); - done(); - }); - webview.setAttribute('preload', fixtures + "/module/preload-node-off.js"); - webview.src = "file://" + fixtures + "/api/blank.html"; - document.body.appendChild(webview); - }); + it('preload script can still use "process" in required modules when nodeintegration is off', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'object undefined object') + done() + }) + webview.setAttribute('preload', fixtures + '/module/preload-node-off.js') + webview.src = 'file://' + fixtures + '/api/blank.html' + document.body.appendChild(webview) + }) - it('receives ipc message in preload script', function(done) { - var message = 'boom!'; - var listener = function(e) { - assert.equal(e.channel, 'pong'); - assert.deepEqual(e.args, [message]); - webview.removeEventListener('ipc-message', listener); - done(); - }; - var listener2 = function() { - webview.send('ping', message); - webview.removeEventListener('did-finish-load', listener2); - }; - webview.addEventListener('ipc-message', listener); - webview.addEventListener('did-finish-load', listener2); - webview.setAttribute('preload', fixtures + "/module/preload-ipc.js"); - webview.src = "file://" + fixtures + "/pages/e.html"; - document.body.appendChild(webview); - }); - }); + it('receives ipc message in preload script', function (done) { + var message = 'boom!' + var listener = function (e) { + assert.equal(e.channel, 'pong') + assert.deepEqual(e.args, [message]) + webview.removeEventListener('ipc-message', listener) + done() + } + var listener2 = function () { + webview.send('ping', message) + webview.removeEventListener('did-finish-load', listener2) + } + webview.addEventListener('ipc-message', listener) + webview.addEventListener('did-finish-load', listener2) + webview.setAttribute('preload', fixtures + '/module/preload-ipc.js') + webview.src = 'file://' + fixtures + '/pages/e.html' + document.body.appendChild(webview) + }) + }) - describe('httpreferrer attribute', function() { - it('sets the referrer url', function(done) { - var referrer = 'http://github.com/'; - var listener = function(e) { - assert.equal(e.message, referrer); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.setAttribute('httpreferrer', referrer); - webview.src = "file://" + fixtures + "/pages/referrer.html"; - document.body.appendChild(webview); - }); - }); + describe('httpreferrer attribute', function () { + it('sets the referrer url', function (done) { + var referrer = 'http://github.com/' + var listener = function (e) { + assert.equal(e.message, referrer) + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('httpreferrer', referrer) + webview.src = 'file://' + fixtures + '/pages/referrer.html' + document.body.appendChild(webview) + }) + }) - describe('useragent attribute', function() { - it('sets the user agent', function(done) { - var referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'; - var listener = function(e) { - assert.equal(e.message, referrer); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.setAttribute('useragent', referrer); - webview.src = "file://" + fixtures + "/pages/useragent.html"; - document.body.appendChild(webview); - }); - }); + describe('useragent attribute', function () { + it('sets the user agent', function (done) { + var referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko' + var listener = function (e) { + assert.equal(e.message, referrer) + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('useragent', referrer) + webview.src = 'file://' + fixtures + '/pages/useragent.html' + document.body.appendChild(webview) + }) + }) - describe('disablewebsecurity attribute', function() { - it('does not disable web security when not set', function(done) { - var src = " "; - var encoded = btoa(unescape(encodeURIComponent(src))); - var listener = function(e) { - assert(/Not allowed to load local resource/.test(e.message)); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.src = "data:text/html;base64," + encoded; - document.body.appendChild(webview); - }); + describe('disablewebsecurity attribute', function () { + it('does not disable web security when not set', function (done) { + var src = " " + var encoded = btoa(unescape(encodeURIComponent(src))) + var listener = function (e) { + assert(/Not allowed to load local resource/.test(e.message)) + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.src = 'data:text/html;base64,' + encoded + document.body.appendChild(webview) + }) - it('disables web security when set', function(done) { - var src = " "; - var encoded = btoa(unescape(encodeURIComponent(src))); - var listener = function(e) { - assert.equal(e.message, 'ok'); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.setAttribute('disablewebsecurity', ''); - webview.src = "data:text/html;base64," + encoded; - document.body.appendChild(webview); - }); - }); + it('disables web security when set', function (done) { + var src = " " + var encoded = btoa(unescape(encodeURIComponent(src))) + var listener = function (e) { + assert.equal(e.message, 'ok') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('disablewebsecurity', '') + webview.src = 'data:text/html;base64,' + encoded + document.body.appendChild(webview) + }) + }) - describe('partition attribute', function() { - it('inserts no node symbols when not set', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'undefined undefined undefined undefined'); - done(); - }); - webview.src = "file://" + fixtures + "/pages/c.html"; - webview.partition = 'test1'; - document.body.appendChild(webview); - }); + describe('partition attribute', function () { + it('inserts no node symbols when not set', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'undefined undefined undefined undefined') + done() + }) + webview.src = 'file://' + fixtures + '/pages/c.html' + webview.partition = 'test1' + document.body.appendChild(webview) + }) - it('inserts node symbols when set', function(done) { - webview.addEventListener('console-message', function(e) { - assert.equal(e.message, 'function object object'); - done(); - }); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/d.html"; - webview.partition = 'test2'; - document.body.appendChild(webview); - }); + it('inserts node symbols when set', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'function object object') + done() + }) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/d.html' + webview.partition = 'test2' + document.body.appendChild(webview) + }) - it('isolates storage for different id', function(done) { - var listener = function(e) { - assert.equal(e.message, " 0"); - webview.removeEventListener('console-message', listener); - done(); - }; - window.localStorage.setItem('test', 'one'); - webview.addEventListener('console-message', listener); - webview.src = "file://" + fixtures + "/pages/partition/one.html"; - webview.partition = 'test3'; - document.body.appendChild(webview); - }); + it('isolates storage for different id', function (done) { + var listener = function (e) { + assert.equal(e.message, ' 0') + webview.removeEventListener('console-message', listener) + done() + } + window.localStorage.setItem('test', 'one') + webview.addEventListener('console-message', listener) + webview.src = 'file://' + fixtures + '/pages/partition/one.html' + webview.partition = 'test3' + document.body.appendChild(webview) + }) - it('uses current session storage when no id is provided', function(done) { - var listener = function(e) { - assert.equal(e.message, "one 1"); - webview.removeEventListener('console-message', listener); - done(); - }; - window.localStorage.setItem('test', 'one'); - webview.addEventListener('console-message', listener); - webview.src = "file://" + fixtures + "/pages/partition/one.html"; - document.body.appendChild(webview); - }); - }); + it('uses current session storage when no id is provided', function (done) { + var listener = function (e) { + assert.equal(e.message, 'one 1') + webview.removeEventListener('console-message', listener) + done() + } + window.localStorage.setItem('test', 'one') + webview.addEventListener('console-message', listener) + webview.src = 'file://' + fixtures + '/pages/partition/one.html' + document.body.appendChild(webview) + }) + }) - describe('allowpopups attribute', function() { - it('can not open new window when not set', function(done) { - var listener = function(e) { - assert.equal(e.message, 'null'); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.src = "file://" + fixtures + "/pages/window-open-hide.html"; - document.body.appendChild(webview); - }); + describe('allowpopups attribute', function () { + it('can not open new window when not set', function (done) { + var listener = function (e) { + assert.equal(e.message, 'null') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.src = 'file://' + fixtures + '/pages/window-open-hide.html' + document.body.appendChild(webview) + }) - it('can open new window when set', function(done) { - var listener = function(e) { - assert.equal(e.message, 'window'); - webview.removeEventListener('console-message', listener); - done(); - }; - webview.addEventListener('console-message', listener); - webview.setAttribute('allowpopups', 'on'); - webview.src = "file://" + fixtures + "/pages/window-open-hide.html"; - document.body.appendChild(webview); - }); - }); + it('can open new window when set', function (done) { + var listener = function (e) { + assert.equal(e.message, 'window') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('allowpopups', 'on') + webview.src = 'file://' + fixtures + '/pages/window-open-hide.html' + document.body.appendChild(webview) + }) + }) - describe('new-window event', function() { - it('emits when window.open is called', function(done) { - webview.addEventListener('new-window', function(e) { - assert.equal(e.url, 'http://host/'); - assert.equal(e.frameName, 'host'); - done(); - }); - webview.src = "file://" + fixtures + "/pages/window-open.html"; - document.body.appendChild(webview); - }); + describe('new-window event', function () { + it('emits when window.open is called', function (done) { + webview.addEventListener('new-window', function (e) { + assert.equal(e.url, 'http://host/') + assert.equal(e.frameName, 'host') + done() + }) + webview.src = 'file://' + fixtures + '/pages/window-open.html' + document.body.appendChild(webview) + }) - it('emits when link with target is called', function(done) { - webview.addEventListener('new-window', function(e) { - assert.equal(e.url, 'http://host/'); - assert.equal(e.frameName, 'target'); - done(); - }); - webview.src = "file://" + fixtures + "/pages/target-name.html"; - document.body.appendChild(webview); - }); - }); + it('emits when link with target is called', function (done) { + webview.addEventListener('new-window', function (e) { + assert.equal(e.url, 'http://host/') + assert.equal(e.frameName, 'target') + done() + }) + webview.src = 'file://' + fixtures + '/pages/target-name.html' + document.body.appendChild(webview) + }) + }) - describe('ipc-message event', function() { - it('emits when guest sends a ipc message to browser', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert.equal(e.channel, 'channel'); - assert.deepEqual(e.args, ['arg1', 'arg2']); - done(); - }); - webview.src = "file://" + fixtures + "/pages/ipc-message.html"; - webview.setAttribute('nodeintegration', 'on'); - document.body.appendChild(webview); - }); - }); + describe('ipc-message event', function () { + it('emits when guest sends a ipc message to browser', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert.equal(e.channel, 'channel') + assert.deepEqual(e.args, ['arg1', 'arg2']) + done() + }) + webview.src = 'file://' + fixtures + '/pages/ipc-message.html' + webview.setAttribute('nodeintegration', 'on') + document.body.appendChild(webview) + }) + }) - describe('page-title-set event', function() { - it('emits when title is set', function(done) { - webview.addEventListener('page-title-set', function(e) { - assert.equal(e.title, 'test'); - assert(e.explicitSet); - done(); - }); - webview.src = "file://" + fixtures + "/pages/a.html"; - document.body.appendChild(webview); - }); - }); + describe('page-title-set event', function () { + it('emits when title is set', function (done) { + webview.addEventListener('page-title-set', function (e) { + assert.equal(e.title, 'test') + assert(e.explicitSet) + done() + }) + webview.src = 'file://' + fixtures + '/pages/a.html' + document.body.appendChild(webview) + }) + }) - describe('page-favicon-updated event', function() { - it('emits when favicon urls are received', function(done) { - webview.addEventListener('page-favicon-updated', function(e) { - assert.equal(e.favicons.length, 2); - var pageUrl = process.platform === 'win32' ? 'file:///C:/favicon.png' : 'file:///favicon.png'; - assert.equal(e.favicons[0], pageUrl); - done(); - }); - webview.src = "file://" + fixtures + "/pages/a.html"; - document.body.appendChild(webview); - }); - }); + describe('page-favicon-updated event', function () { + it('emits when favicon urls are received', function (done) { + webview.addEventListener('page-favicon-updated', function (e) { + assert.equal(e.favicons.length, 2) + var pageUrl = process.platform === 'win32' ? 'file:///C:/favicon.png' : 'file:///favicon.png' + assert.equal(e.favicons[0], pageUrl) + done() + }) + webview.src = 'file://' + fixtures + '/pages/a.html' + document.body.appendChild(webview) + }) + }) - describe('will-navigate event', function() { - it('emits when a url that leads to oustide of the page is clicked', function(done) { - webview.addEventListener('will-navigate', function(e) { - assert.equal(e.url, "http://host/"); - done(); - }); - webview.src = "file://" + fixtures + "/pages/webview-will-navigate.html"; - document.body.appendChild(webview); - }); - }); + describe('will-navigate event', function () { + it('emits when a url that leads to oustide of the page is clicked', function (done) { + webview.addEventListener('will-navigate', function (e) { + assert.equal(e.url, 'http://host/') + done() + }) + webview.src = 'file://' + fixtures + '/pages/webview-will-navigate.html' + document.body.appendChild(webview) + }) + }) - describe('did-navigate event', function() { - var p = path.join(fixtures, 'pages', 'webview-will-navigate.html'); - p = p.replace(/\\/g, '/'); + describe('did-navigate event', function () { + var p = path.join(fixtures, 'pages', 'webview-will-navigate.html') + p = p.replace(/\\/g, '/') var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p - }); + }) - it('emits when a url that leads to outside of the page is clicked', function(done) { - webview.addEventListener('did-navigate', function(e) { - assert.equal(e.url, pageUrl); - done(); - }); - webview.src = pageUrl; - document.body.appendChild(webview); - }); - }); + it('emits when a url that leads to outside of the page is clicked', function (done) { + webview.addEventListener('did-navigate', function (e) { + assert.equal(e.url, pageUrl) + done() + }) + webview.src = pageUrl + document.body.appendChild(webview) + }) + }) - describe('did-navigate-in-page event', function() { - it('emits when an anchor link is clicked', function(done) { - var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html'); - p = p.replace(/\\/g, '/'); + describe('did-navigate-in-page event', function () { + it('emits when an anchor link is clicked', function (done) { + var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html') + p = p.replace(/\\/g, '/') var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p - }); - webview.addEventListener('did-navigate-in-page', function(e) { - assert.equal(e.url, pageUrl + "#test_content"); - done(); - }); - webview.src = pageUrl; - document.body.appendChild(webview); - }); + }) + webview.addEventListener('did-navigate-in-page', function (e) { + assert.equal(e.url, pageUrl + '#test_content') + done() + }) + webview.src = pageUrl + document.body.appendChild(webview) + }) - it('emits when window.history.replaceState is called', function(done) { - webview.addEventListener('did-navigate-in-page', function(e) { - assert.equal(e.url, "http://host/"); - done(); - }); - webview.src = "file://" + fixtures + "/pages/webview-did-navigate-in-page-with-history.html"; - document.body.appendChild(webview); - }); + it('emits when window.history.replaceState is called', function (done) { + webview.addEventListener('did-navigate-in-page', function (e) { + assert.equal(e.url, 'http://host/') + done() + }) + webview.src = 'file://' + fixtures + '/pages/webview-did-navigate-in-page-with-history.html' + document.body.appendChild(webview) + }) - it('emits when window.location.hash is changed', function(done) { - var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html'); - p = p.replace(/\\/g, '/'); + it('emits when window.location.hash is changed', function (done) { + var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html') + p = p.replace(/\\/g, '/') var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p - }); - webview.addEventListener('did-navigate-in-page', function(e) { - assert.equal(e.url, pageUrl + "#test"); - done(); - }); - webview.src = pageUrl; - document.body.appendChild(webview); - }); - }); + }) + webview.addEventListener('did-navigate-in-page', function (e) { + assert.equal(e.url, pageUrl + '#test') + done() + }) + webview.src = pageUrl + document.body.appendChild(webview) + }) + }) - describe('close event', function() { - it('should fire when interior page calls window.close', function(done) { - webview.addEventListener('close', function() { - done(); - }); - webview.src = "file://" + fixtures + "/pages/close.html"; - document.body.appendChild(webview); - }); - }); + describe('close event', function () { + it('should fire when interior page calls window.close', function (done) { + webview.addEventListener('close', function () { + done() + }) + webview.src = 'file://' + fixtures + '/pages/close.html' + document.body.appendChild(webview) + }) + }) - describe('devtools-opened event', function() { - it('should fire when webview.openDevTools() is called', function(done) { - var listener = function() { - webview.removeEventListener('devtools-opened', listener); - webview.closeDevTools(); - done(); - }; - webview.addEventListener('devtools-opened', listener); - webview.addEventListener('dom-ready', function() { - webview.openDevTools(); - }); - webview.src = "file://" + fixtures + "/pages/base-page.html"; - document.body.appendChild(webview); - }); - }); + describe('devtools-opened event', function () { + it('should fire when webview.openDevTools() is called', function (done) { + var listener = function () { + webview.removeEventListener('devtools-opened', listener) + webview.closeDevTools() + done() + } + webview.addEventListener('devtools-opened', listener) + webview.addEventListener('dom-ready', function () { + webview.openDevTools() + }) + webview.src = 'file://' + fixtures + '/pages/base-page.html' + document.body.appendChild(webview) + }) + }) - describe('devtools-closed event', function() { - it('should fire when webview.closeDevTools() is called', function(done) { - var listener2 = function() { - webview.removeEventListener('devtools-closed', listener2); - done(); - }; - var listener = function() { - webview.removeEventListener('devtools-opened', listener); - webview.closeDevTools(); - }; - webview.addEventListener('devtools-opened', listener); - webview.addEventListener('devtools-closed', listener2); - webview.addEventListener('dom-ready', function() { - webview.openDevTools(); - }); - webview.src = "file://" + fixtures + "/pages/base-page.html"; - document.body.appendChild(webview); - }); - }); + describe('devtools-closed event', function () { + it('should fire when webview.closeDevTools() is called', function (done) { + var listener2 = function () { + webview.removeEventListener('devtools-closed', listener2) + done() + } + var listener = function () { + webview.removeEventListener('devtools-opened', listener) + webview.closeDevTools() + } + webview.addEventListener('devtools-opened', listener) + webview.addEventListener('devtools-closed', listener2) + webview.addEventListener('dom-ready', function () { + webview.openDevTools() + }) + webview.src = 'file://' + fixtures + '/pages/base-page.html' + document.body.appendChild(webview) + }) + }) - describe('devtools-focused event', function() { - it('should fire when webview.openDevTools() is called', function(done) { - var listener = function() { - webview.removeEventListener('devtools-focused', listener); - webview.closeDevTools(); - done(); - }; - webview.addEventListener('devtools-focused', listener); - webview.addEventListener('dom-ready', function() { - webview.openDevTools(); - }); - webview.src = "file://" + fixtures + "/pages/base-page.html"; - document.body.appendChild(webview); - }); - }); + describe('devtools-focused event', function () { + it('should fire when webview.openDevTools() is called', function (done) { + var listener = function () { + webview.removeEventListener('devtools-focused', listener) + webview.closeDevTools() + done() + } + webview.addEventListener('devtools-focused', listener) + webview.addEventListener('dom-ready', function () { + webview.openDevTools() + }) + webview.src = 'file://' + fixtures + '/pages/base-page.html' + document.body.appendChild(webview) + }) + }) - describe('.reload()', function() { - it('should emit beforeunload handler', function(done) { - var listener = function(e) { - assert.equal(e.channel, 'onbeforeunload'); - webview.removeEventListener('ipc-message', listener); - done(); - }; - var listener2 = function() { - webview.reload(); - webview.removeEventListener('did-finish-load', listener2); - }; - webview.addEventListener('ipc-message', listener); - webview.addEventListener('did-finish-load', listener2); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/beforeunload-false.html"; - document.body.appendChild(webview); - }); - }); + describe('.reload()', function () { + it('should emit beforeunload handler', function (done) { + var listener = function (e) { + assert.equal(e.channel, 'onbeforeunload') + webview.removeEventListener('ipc-message', listener) + done() + } + var listener2 = function () { + webview.reload() + webview.removeEventListener('did-finish-load', listener2) + } + webview.addEventListener('ipc-message', listener) + webview.addEventListener('did-finish-load', listener2) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/beforeunload-false.html' + document.body.appendChild(webview) + }) + }) - describe('.clearHistory()', function() { - it('should clear the navigation history', function(done) { - var listener = function(e) { - assert.equal(e.channel, 'history'); - assert.equal(e.args[0], 2); - assert(webview.canGoBack()); - webview.clearHistory(); - assert(!webview.canGoBack()); - webview.removeEventListener('ipc-message', listener); - done(); - }; - webview.addEventListener('ipc-message', listener); - webview.setAttribute('nodeintegration', 'on'); - webview.src = "file://" + fixtures + "/pages/history.html"; - document.body.appendChild(webview); - }); - }); + describe('.clearHistory()', function () { + it('should clear the navigation history', function (done) { + var listener = function (e) { + assert.equal(e.channel, 'history') + assert.equal(e.args[0], 2) + assert(webview.canGoBack()) + webview.clearHistory() + assert(!webview.canGoBack()) + webview.removeEventListener('ipc-message', listener) + done() + } + webview.addEventListener('ipc-message', listener) + webview.setAttribute('nodeintegration', 'on') + webview.src = 'file://' + fixtures + '/pages/history.html' + document.body.appendChild(webview) + }) + }) - describe('basic auth', function() { - var auth = require('basic-auth'); + describe('basic auth', function () { + var auth = require('basic-auth') - it('should authenticate with correct credentials', function(done) { - var message = 'Authenticated'; - var server = http.createServer(function(req, res) { - var credentials = auth(req); + it('should authenticate with correct credentials', function (done) { + var message = 'Authenticated' + var server = http.createServer(function (req, res) { + var credentials = auth(req) if (credentials.name === 'test' && credentials.pass === 'test') { - res.end(message); + res.end(message) } else { - res.end('failed'); + res.end('failed') } - server.close(); - }); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - webview.addEventListener('ipc-message', function(e) { - assert.equal(e.channel, message); - done(); - }); - webview.src = "file://" + fixtures + "/pages/basic-auth.html?port=" + port; - webview.setAttribute('nodeintegration', 'on'); - document.body.appendChild(webview); - }); - }); - }); + server.close() + }) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + webview.addEventListener('ipc-message', function (e) { + assert.equal(e.channel, message) + done() + }) + webview.src = 'file://' + fixtures + '/pages/basic-auth.html?port=' + port + webview.setAttribute('nodeintegration', 'on') + document.body.appendChild(webview) + }) + }) + }) - describe('dom-ready event', function() { - it('emits when document is loaded', function(done) { - var server = http.createServer(function() {}); - server.listen(0, '127.0.0.1', function() { - var port = server.address().port; - webview.addEventListener('dom-ready', function() { - done(); - }); - webview.src = "file://" + fixtures + "/pages/dom-ready.html?port=" + port; - document.body.appendChild(webview); - }); - }); + describe('dom-ready event', function () { + it('emits when document is loaded', function (done) { + var server = http.createServer(function () {}) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + webview.addEventListener('dom-ready', function () { + done() + }) + webview.src = 'file://' + fixtures + '/pages/dom-ready.html?port=' + port + document.body.appendChild(webview) + }) + }) - it('throws a custom error when an API method is called before the event is emitted', function() { + it('throws a custom error when an API method is called before the event is emitted', function () { assert.throws(function () { - webview.stop(); - }, 'Cannot call stop because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.'); - }); - }); + webview.stop() + }, 'Cannot call stop because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.') + }) + }) - describe('executeJavaScript', function() { - it('should support user gesture', function(done) { + describe('executeJavaScript', function () { + it('should support user gesture', function (done) { if (process.env.TRAVIS !== 'true' || process.platform == 'darwin') - return done(); + return done() - var listener = function() { - webview.removeEventListener('enter-html-full-screen', listener); - done(); - }; - var listener2 = function() { - var jsScript = "document.querySelector('video').webkitRequestFullscreen()"; - webview.executeJavaScript(jsScript, true); - webview.removeEventListener('did-finish-load', listener2); - }; - webview.addEventListener('enter-html-full-screen', listener); - webview.addEventListener('did-finish-load', listener2); - webview.src = "file://" + fixtures + "/pages/fullscreen.html"; - document.body.appendChild(webview); - }); + var listener = function () { + webview.removeEventListener('enter-html-full-screen', listener) + done() + } + var listener2 = function () { + var jsScript = "document.querySelector('video').webkitRequestFullscreen()" + webview.executeJavaScript(jsScript, true) + webview.removeEventListener('did-finish-load', listener2) + } + webview.addEventListener('enter-html-full-screen', listener) + webview.addEventListener('did-finish-load', listener2) + webview.src = 'file://' + fixtures + '/pages/fullscreen.html' + document.body.appendChild(webview) + }) - it('can return the result of the executed script', function(done) { + it('can return the result of the executed script', function (done) { if (process.env.TRAVIS === 'true' && process.platform == 'darwin') - return done(); + return done() - var listener = function() { - var jsScript = "'4'+2"; - webview.executeJavaScript(jsScript, false, function(result) { - assert.equal(result, '42'); - done(); - }); - webview.removeEventListener('did-finish-load', listener); - }; - webview.addEventListener('did-finish-load', listener); - webview.src = "about:blank"; - document.body.appendChild(webview); - }); - }); + var listener = function () { + var jsScript = "'4'+2" + webview.executeJavaScript(jsScript, false, function (result) { + assert.equal(result, '42') + done() + }) + webview.removeEventListener('did-finish-load', listener) + } + webview.addEventListener('did-finish-load', listener) + webview.src = 'about:blank' + document.body.appendChild(webview) + }) + }) - describe('sendInputEvent', function() { - it('can send keyboard event', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert.equal(e.channel, 'keyup'); - assert.deepEqual(e.args, [67, true, false]); - done(); - }); - webview.addEventListener('dom-ready', function() { + describe('sendInputEvent', function () { + it('can send keyboard event', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert.equal(e.channel, 'keyup') + assert.deepEqual(e.args, [67, true, false]) + done() + }) + webview.addEventListener('dom-ready', function () { webview.sendInputEvent({ type: 'keyup', keyCode: 'c', modifiers: ['shift'] - }); - }); - webview.src = "file://" + fixtures + "/pages/onkeyup.html"; - webview.setAttribute('nodeintegration', 'on'); - document.body.appendChild(webview); - }); + }) + }) + webview.src = 'file://' + fixtures + '/pages/onkeyup.html' + webview.setAttribute('nodeintegration', 'on') + document.body.appendChild(webview) + }) - it('can send mouse event', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert.equal(e.channel, 'mouseup'); - assert.deepEqual(e.args, [10, 20, false, true]); - done(); - }); - webview.addEventListener('dom-ready', function() { + it('can send mouse event', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert.equal(e.channel, 'mouseup') + assert.deepEqual(e.args, [10, 20, false, true]) + done() + }) + webview.addEventListener('dom-ready', function () { webview.sendInputEvent({ type: 'mouseup', modifiers: ['ctrl'], x: 10, y: 20 - }); - }); - webview.src = "file://" + fixtures + "/pages/onmouseup.html"; - webview.setAttribute('nodeintegration', 'on'); - document.body.appendChild(webview); - }); - }); + }) + }) + webview.src = 'file://' + fixtures + '/pages/onmouseup.html' + webview.setAttribute('nodeintegration', 'on') + document.body.appendChild(webview) + }) + }) - describe('media-started-playing media-paused events', function() { - it('emits when audio starts and stops playing', function(done) { - var audioPlayed = false; - webview.addEventListener('media-started-playing', function() { - audioPlayed = true; - }); - webview.addEventListener('media-paused', function() { - assert(audioPlayed); - done(); - }); - webview.src = "file://" + fixtures + "/pages/audio.html"; - document.body.appendChild(webview); - }); - }); + describe('media-started-playing media-paused events', function () { + it('emits when audio starts and stops playing', function (done) { + var audioPlayed = false + webview.addEventListener('media-started-playing', function () { + audioPlayed = true + }) + webview.addEventListener('media-paused', function () { + assert(audioPlayed) + done() + }) + webview.src = 'file://' + fixtures + '/pages/audio.html' + document.body.appendChild(webview) + }) + }) - describe('found-in-page event', function() { - it('emits when a request is made', function(done) { - var requestId = null; - var totalMatches = null; - var activeMatchOrdinal = []; - var listener = function(e) { - assert.equal(e.result.requestId, requestId); + describe('found-in-page event', function () { + it('emits when a request is made', function (done) { + var requestId = null + var totalMatches = null + var activeMatchOrdinal = [] + var listener = function (e) { + assert.equal(e.result.requestId, requestId) if (e.result.finalUpdate) { - assert.equal(e.result.matches, 3); - totalMatches = e.result.matches; - listener2(); + assert.equal(e.result.matches, 3) + totalMatches = e.result.matches + listener2() } else { - activeMatchOrdinal.push(e.result.activeMatchOrdinal); + activeMatchOrdinal.push(e.result.activeMatchOrdinal) if (e.result.activeMatchOrdinal == totalMatches) { - assert.deepEqual(activeMatchOrdinal, [1, 2, 3]); - webview.stopFindInPage("clearSelection"); - done(); + assert.deepEqual(activeMatchOrdinal, [1, 2, 3]) + webview.stopFindInPage('clearSelection') + done() } } - }; - var listener2 = function() { - requestId = webview.findInPage("virtual"); - }; - webview.addEventListener('found-in-page', listener); - webview.addEventListener('did-finish-load', listener2); - webview.src = "file://" + fixtures + "/pages/content.html"; - document.body.appendChild(webview); - }); - }); + } + var listener2 = function () { + requestId = webview.findInPage('virtual') + } + webview.addEventListener('found-in-page', listener) + webview.addEventListener('did-finish-load', listener2) + webview.src = 'file://' + fixtures + '/pages/content.html' + document.body.appendChild(webview) + }) + }) - xdescribe('did-change-theme-color event', function() { - it('emits when theme color changes', function(done) { - webview.addEventListener('did-change-theme-color', function() { - done(); - }); - webview.src = "file://" + fixtures + "/pages/theme-color.html"; - document.body.appendChild(webview); - }); - }); + xdescribe('did-change-theme-color event', function () { + it('emits when theme color changes', function (done) { + webview.addEventListener('did-change-theme-color', function () { + done() + }) + webview.src = 'file://' + fixtures + '/pages/theme-color.html' + document.body.appendChild(webview) + }) + }) - describe('permission-request event', function() { - function setUpRequestHandler(webview, requested_permission) { - const session = require('electron').remote.session; - var listener = function(webContents, permission, callback) { - if (webContents.getId() === webview.getId() ) { - assert.equal(permission, requested_permission); - callback(false); + describe('permission-request event', function () { + function setUpRequestHandler (webview, requested_permission) { + const session = require('electron').remote.session + var listener = function (webContents, permission, callback) { + if (webContents.getId() === webview.getId()) { + assert.equal(permission, requested_permission) + callback(false) } - }; - session.fromPartition(webview.partition).setPermissionRequestHandler(listener); + } + session.fromPartition(webview.partition).setPermissionRequestHandler(listener) } - it('emits when using navigator.getUserMedia api', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert(e.channel, 'message'); - assert(e.args, ['PermissionDeniedError']); - done(); - }); - webview.src = "file://" + fixtures + "/pages/permissions/media.html"; - webview.partition = "permissionTest"; - webview.setAttribute('nodeintegration', 'on'); - setUpRequestHandler(webview, "media"); - document.body.appendChild(webview); - }); + it('emits when using navigator.getUserMedia api', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert(e.channel, 'message') + assert(e.args, ['PermissionDeniedError']) + done() + }) + webview.src = 'file://' + fixtures + '/pages/permissions/media.html' + webview.partition = 'permissionTest' + webview.setAttribute('nodeintegration', 'on') + setUpRequestHandler(webview, 'media') + document.body.appendChild(webview) + }) - it('emits when using navigator.geolocation api', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert(e.channel, 'message'); - assert(e.args, ['ERROR(1): User denied Geolocation']); - done(); - }); - webview.src = "file://" + fixtures + "/pages/permissions/geolocation.html"; - webview.partition = "permissionTest"; - webview.setAttribute('nodeintegration', 'on'); - setUpRequestHandler(webview, "geolocation"); - document.body.appendChild(webview); - }); + it('emits when using navigator.geolocation api', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert(e.channel, 'message') + assert(e.args, ['ERROR(1): User denied Geolocation']) + done() + }) + webview.src = 'file://' + fixtures + '/pages/permissions/geolocation.html' + webview.partition = 'permissionTest' + webview.setAttribute('nodeintegration', 'on') + setUpRequestHandler(webview, 'geolocation') + document.body.appendChild(webview) + }) - it('emits when using navigator.requestMIDIAccess api', function(done) { - webview.addEventListener('ipc-message', function(e) { - assert(e.channel, 'message'); - assert(e.args, ['SecurityError']); - done(); - }); - webview.src = "file://" + fixtures + "/pages/permissions/midi.html"; - webview.partition = "permissionTest"; - webview.setAttribute('nodeintegration', 'on'); - setUpRequestHandler(webview, "midiSysex"); - document.body.appendChild(webview); - }); - }); + it('emits when using navigator.requestMIDIAccess api', function (done) { + webview.addEventListener('ipc-message', function (e) { + assert(e.channel, 'message') + assert(e.args, ['SecurityError']) + done() + }) + webview.src = 'file://' + fixtures + '/pages/permissions/midi.html' + webview.partition = 'permissionTest' + webview.setAttribute('nodeintegration', 'on') + setUpRequestHandler(webview, 'midiSysex') + document.body.appendChild(webview) + }) + }) - describe('.getWebContents', function() { - it('can return the webcontents associated', function(done) { - webview.addEventListener('did-finish-load', function() { - const webviewContents = webview.getWebContents(); - assert(webviewContents); - assert.equal(webviewContents.getURL(), 'about:blank'); - done(); - }); - webview.src = "about:blank"; - document.body.appendChild(webview); - }); - }); -}); + describe('.getWebContents', function () { + it('can return the webcontents associated', function (done) { + webview.addEventListener('did-finish-load', function () { + const webviewContents = webview.getWebContents() + assert(webviewContents) + assert.equal(webviewContents.getURL(), 'about:blank') + done() + }) + webview.src = 'about:blank' + document.body.appendChild(webview) + }) + }) +}) diff --git a/tools/dump-version-info.js b/tools/dump-version-info.js index e76f09ba2f9..b4b44fe61aa 100644 --- a/tools/dump-version-info.js +++ b/tools/dump-version-info.js @@ -1,31 +1,31 @@ -var app = require('app'); -var fs = require('fs'); -var path = require('path'); -var request = require('request'); +var app = require('app') +var fs = require('fs') +var path = require('path') +var request = require('request') -var TARGET_URL = 'https://atom.io/download/atom-shell/index.json'; +var TARGET_URL = 'https://atom.io/download/atom-shell/index.json' -function getDate() { - var today = new Date(); - var year = today.getFullYear(); - var month = today.getMonth() + 1; +function getDate () { + var today = new Date() + var year = today.getFullYear() + var month = today.getMonth() + 1 if (month <= 9) - month = '0' + month; - var day= today.getDate(); + month = '0' + month + var day = today.getDate() if (day <= 9) - day = '0' + day; - return year + '-' + month + '-' + day; + day = '0' + day + return year + '-' + month + '-' + day } -function getInfoForCurrentVersion() { - var json = {}; - json.version = process.versions['atom-shell']; - json.date = getDate(); +function getInfoForCurrentVersion () { + var json = {} + json.version = process.versions['atom-shell'] + json.date = getDate() var names = ['node', 'v8', 'uv', 'zlib', 'openssl', 'modules', 'chrome'] for (var i in names) { - var name = names[i]; - json[name] = process.versions[name]; + var name = names[i] + json[name] = process.versions[name] } json.files = [ @@ -39,44 +39,44 @@ function getInfoForCurrentVersion() { 'win32-ia32-symbols', 'win32-x64', 'win32-x64-symbols', - ]; + ] - return json; + return json } -function getIndexJsInServer(callback) { - request(TARGET_URL, function(e, res, body) { +function getIndexJsInServer (callback) { + request(TARGET_URL, function (e, res, body) { if (e) - callback(e); + callback(e) else if (res.statusCode != 200) - callback(new Error('Server returned ' + res.statusCode)); + callback(new Error('Server returned ' + res.statusCode)) else - callback(null, JSON.parse(body)); - }); + callback(null, JSON.parse(body)) + }) } -function findObjectByVersion(all, version) { +function findObjectByVersion (all, version) { for (var i in all) if (all[i].version == version) - return i; - return -1; + return i + return -1 } -app.on('ready', function() { - getIndexJsInServer(function(e, all) { +app.on('ready', function () { + getIndexJsInServer(function (e, all) { if (e) { - console.error(e); - process.exit(1); + console.error(e) + process.exit(1) } - var current = getInfoForCurrentVersion(); - var found = findObjectByVersion(all, current.version); + var current = getInfoForCurrentVersion() + var found = findObjectByVersion(all, current.version) if (found == -1) - all.unshift(current); + all.unshift(current) else - all[found] = current; + all[found] = current - fs.writeFileSync(process.argv[2], JSON.stringify(all)); - process.exit(0); - }); -}); + fs.writeFileSync(process.argv[2], JSON.stringify(all)) + process.exit(0) + }) +}) diff --git a/tools/win/register_msdia80_dll.js b/tools/win/register_msdia80_dll.js index 5691ef9caf5..e90b9714d1f 100644 --- a/tools/win/register_msdia80_dll.js +++ b/tools/win/register_msdia80_dll.js @@ -1,12 +1,12 @@ -var fs = require('fs'); -var path = require('path'); -var runas = require('runas'); +var fs = require('fs') +var path = require('path') +var runas = require('runas') -var source = path.resolve(__dirname, '..', '..', 'vendor', 'breakpad', 'msdia80.dll'); -var target = 'C:\\Program Files\\Common Files\\Microsoft Shared\\VC\\msdia80.dll'; -if (fs.existsSync(target)) - return; +var source = path.resolve(__dirname, '..', '..', 'vendor', 'breakpad', 'msdia80.dll') +var target = 'C:\\Program Files\\Common Files\\Microsoft Shared\\VC\\msdia80.dll' -runas('cmd', - ['/K', 'copy', source, target, '&', 'regsvr32', '/s', target, '&', 'exit'], - {admin: true}); +if (!fs.existsSync(target)) { + runas('cmd', + ['/K', 'copy', source, target, '&', 'regsvr32', '/s', target, '&', 'exit'], + {admin: true}) +} From 7404b848a2141ace3a863b5640ac72f232efc452 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 25 Mar 2016 13:11:05 -0700 Subject: [PATCH 0311/1265] tell standard to ignore /vendor directory --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 9f22ef2ae07..42815e3a3d6 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,8 @@ "standard": { "ignore": [ "/lib/browser/rpc-server.js", - "/lib/common/asar.js" + "/lib/common/asar.js", + "/vendor" ] }, "private": true, From 2fb92076b615e90d43e931f32652d5f7b665494b Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 25 Mar 2016 13:16:56 -0700 Subject: [PATCH 0312/1265] standard-format has done its work; on to snazzy --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 42815e3a3d6..10683e0f997 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "asar": "^0.10.0", "eslint": "^2.1.0", "request": "*", - "standard-format": "^2.1.1" + "snazzy": "^3.0.0" }, "optionalDependencies": { "runas": "^3.0.0" From 67d189474c49ea0f700d902491b864105245a157 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Sun, 27 Mar 2016 10:38:32 -0700 Subject: [PATCH 0313/1265] autoformat more files --- default_app/default_app.js | 2 +- default_app/main.js | 31 +++++++++++++++---------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/default_app/default_app.js b/default_app/default_app.js index c2d95158cd0..eda1300f007 100644 --- a/default_app/default_app.js +++ b/default_app/default_app.js @@ -15,7 +15,7 @@ exports.load = function (appUrl) { width: 800, height: 600, autoHideMenuBar: true, - useContentSize: true, + useContentSize: true }) mainWindow.loadURL(appUrl) mainWindow.focus() diff --git a/default_app/main.js b/default_app/main.js index 49ad78f60ba..e4cdb8c8d54 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -13,23 +13,23 @@ const url = require('url') var argv = process.argv.slice(1) var option = { file: null, help: null, version: null, webdriver: null, modules: [] } for (var i = 0; i < argv.length; i++) { - if (argv[i] == '--version' || argv[i] == '-v') { + if (argv[i] === '--version' || argv[i] === '-v') { option.version = true break } else if (argv[i].match(/^--app=/)) { option.file = argv[i].split('=')[1] break - } else if (argv[i] == '--help' || argv[i] == '-h') { + } else if (argv[i] === '--help' || argv[i] === '-h') { option.help = true break - } else if (argv[i] == '--interactive' || argv[i] == '-i') { + } else if (argv[i] === '--interactive' || argv[i] === '-i') { option.interactive = true - } else if (argv[i] == '--test-type=webdriver') { + } else if (argv[i] === '--test-type=webdriver') { option.webdriver = true - } else if (argv[i] == '--require' || argv[i] == '-r') { + } else if (argv[i] === '--require' || argv[i] === '-r') { option.modules.push(argv[++i]) continue - } else if (argv[i][0] == '-') { + } else if (argv[i][0] === '-') { continue } else { option.file = argv[i] @@ -39,14 +39,14 @@ for (var i = 0; i < argv.length; i++) { // Quit when all windows are closed and no other one is listening to this. app.on('window-all-closed', function () { - if (app.listeners('window-all-closed').length == 1 && !option.interactive) + if (app.listeners('window-all-closed').length === 1 && !option.interactive) { app.quit() + } }) // Create default menu. app.once('ready', function () { - if (Menu.getApplicationMenu()) - return + if (Menu.getApplicationMenu()) return var template = [ { @@ -84,7 +84,7 @@ app.once('ready', function () { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' - }, + } ] }, { @@ -94,14 +94,13 @@ app.once('ready', function () { label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function (item, focusedWindow) { - if (focusedWindow) - focusedWindow.reload() + if (focusedWindow) focusedWindow.reload() } }, { label: 'Toggle Full Screen', accelerator: (function () { - if (process.platform == 'darwin') + if (process.platform === 'darwin') return 'Ctrl+Command+F' else return 'F11' @@ -114,7 +113,7 @@ app.once('ready', function () { { label: 'Toggle Developer Tools', accelerator: (function () { - if (process.platform == 'darwin') + if (process.platform === 'darwin') return 'Alt+Command+I' else return 'Ctrl+Shift+I' @@ -176,7 +175,7 @@ app.once('ready', function () { }, ] - if (process.platform == 'darwin') { + if (process.platform === 'darwin') { template.unshift({ label: 'Electron', submenu: [ @@ -259,7 +258,7 @@ function loadApplicationPackage (packagePath) { // Run the app. require('module')._load(packagePath, module, true) } catch(e) { - if (e.code == 'MODULE_NOT_FOUND') { + if (e.code === 'MODULE_NOT_FOUND') { app.focus() dialog.showErrorBox( 'Error opening app', From 09635ae50eb5dafb398c194ed6a16655c3ee2da0 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 13:09:03 -0700 Subject: [PATCH 0314/1265] reduce ignore list in favor of one-liner ignores --- lib/browser/rpc-server.js | 4 ++-- package.json | 6 +----- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index 79a52b13262..eb1d0385fa1 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -281,7 +281,7 @@ ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) { // Call new with array of arguments. // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible - let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) + let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) // eslint-disable-line event.returnValue = valueToMeta(event.sender, obj) } catch (error) { event.returnValue = exceptionToMeta(error) @@ -304,7 +304,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) let constructor = objectsRegistry.get(id)[method] // Call new with array of arguments. - let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) + let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) // eslint-disable-line event.returnValue = valueToMeta(event.sender, obj) } catch (error) { event.returnValue = exceptionToMeta(error) diff --git a/package.json b/package.json index 10683e0f997..46584638dfb 100644 --- a/package.json +++ b/package.json @@ -11,11 +11,7 @@ "runas": "^3.0.0" }, "standard": { - "ignore": [ - "/lib/browser/rpc-server.js", - "/lib/common/asar.js", - "/vendor" - ] + "ignore": ["/vendor"], }, "private": true, "scripts": { From 3a55f0d1f709680f67e35e22657349ee98f79ce7 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 13:09:18 -0700 Subject: [PATCH 0315/1265] set standard.globals --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 46584638dfb..855d5155504 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ }, "standard": { "ignore": ["/vendor"], + "globals": ["afterEach", "beforeEach", "describe", "it", "location"] }, "private": true, "scripts": { From 68510cbe49b357adbee61205e182af41c8fb6aa5 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 13:19:41 -0700 Subject: [PATCH 0316/1265] standardize more --- default_app/main.js | 36 +++++++++++++++--------------------- tools/dump-version-info.js | 16 +++++++--------- 2 files changed, 22 insertions(+), 30 deletions(-) diff --git a/default_app/main.js b/default_app/main.js index e4cdb8c8d54..dcbe2ca0c65 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -100,29 +100,21 @@ app.once('ready', function () { { label: 'Toggle Full Screen', accelerator: (function () { - if (process.platform === 'darwin') - return 'Ctrl+Command+F' - else - return 'F11' + return (process.platform === 'darwin') ? 'Ctrl+Command+F' : 'F11' })(), click: function (item, focusedWindow) { - if (focusedWindow) - focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) + if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } }, { label: 'Toggle Developer Tools', accelerator: (function () { - if (process.platform === 'darwin') - return 'Alt+Command+I' - else - return 'Ctrl+Shift+I' + return (process.platform === 'darwin') ? 'Alt+Command+I' : 'Ctrl+Shift+I' })(), click: function (item, focusedWindow) { - if (focusedWindow) - focusedWindow.toggleDevTools() + if (focusedWindow) focusedWindow.toggleDevTools() } - }, + } ] }, { @@ -138,7 +130,7 @@ app.once('ready', function () { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' - }, + } ] }, { @@ -172,7 +164,7 @@ app.once('ready', function () { } } ] - }, + } ] if (process.platform === 'darwin') { @@ -214,8 +206,8 @@ app.once('ready', function () { { label: 'Quit', accelerator: 'Command+Q', - click: function () { app.quit(); } - }, + click: function () { app.quit() } + } ] }) template[3].submenu.push( @@ -244,12 +236,14 @@ function loadApplicationPackage (packagePath) { var packageJsonPath = path.join(packagePath, 'package.json') if (fs.existsSync(packageJsonPath)) { var packageJson = JSON.parse(fs.readFileSync(packageJsonPath)) - if (packageJson.version) - app.setVersion(packageJson.version) - if (packageJson.productName) + if (packageJson.version) app.setVersion(packageJson.version) + + if (packageJson.productName) { app.setName(packageJson.productName) - else if (packageJson.name) + } else if (packageJson.name) { app.setName(packageJson.name) + } + app.setPath('userData', path.join(app.getPath('appData'), app.getName())) app.setPath('userCache', path.join(app.getPath('cache'), app.getName())) app.setAppPath(packagePath) diff --git a/tools/dump-version-info.js b/tools/dump-version-info.js index b4b44fe61aa..1abe2ac1398 100644 --- a/tools/dump-version-info.js +++ b/tools/dump-version-info.js @@ -1,6 +1,5 @@ var app = require('app') var fs = require('fs') -var path = require('path') var request = require('request') var TARGET_URL = 'https://atom.io/download/atom-shell/index.json' @@ -9,11 +8,9 @@ function getDate () { var today = new Date() var year = today.getFullYear() var month = today.getMonth() + 1 - if (month <= 9) - month = '0' + month + if (month <= 9) month = '0' + month var day = today.getDate() - if (day <= 9) - day = '0' + day + if (day <= 9) day = '0' + day return year + '-' + month + '-' + day } @@ -38,7 +35,7 @@ function getInfoForCurrentVersion () { 'win32-ia32', 'win32-ia32-symbols', 'win32-x64', - 'win32-x64-symbols', + 'win32-x64-symbols' ] return json @@ -46,12 +43,13 @@ function getInfoForCurrentVersion () { function getIndexJsInServer (callback) { request(TARGET_URL, function (e, res, body) { - if (e) + if (e) { callback(e) - else if (res.statusCode != 200) + } else if (res.statusCode != 200) { callback(new Error('Server returned ' + res.statusCode)) - else + } else { callback(null, JSON.parse(body)) + } }) } From f47fa25e3914cd80a994b012d55e099ab8b1ec0c Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 13:47:31 -0700 Subject: [PATCH 0317/1265] tiptoe --- spec/webview-spec.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 1bb18c0b5e7..4fdba97249a 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -1,3 +1,5 @@ +/* globals btoa, WebView, xdescribe */ + const assert = require('assert') const path = require('path') const http = require('http') @@ -10,7 +12,7 @@ describe(' tag', function () { var webview = null beforeEach(function () { - webview = new WebView + webview = new WebView() }) afterEach(function () { @@ -168,7 +170,8 @@ describe(' tag', function () { describe('disablewebsecurity attribute', function () { it('does not disable web security when not set', function (done) { - var src = " " + var jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js') + var src = ` ` var encoded = btoa(unescape(encodeURIComponent(src))) var listener = function (e) { assert(/Not allowed to load local resource/.test(e.message)) @@ -181,7 +184,8 @@ describe(' tag', function () { }) it('disables web security when set', function (done) { - var src = " " + var jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js') + var src = ` ` var encoded = btoa(unescape(encodeURIComponent(src))) var listener = function (e) { assert.equal(e.message, 'ok') @@ -549,8 +553,7 @@ describe(' tag', function () { describe('executeJavaScript', function () { it('should support user gesture', function (done) { - if (process.env.TRAVIS !== 'true' || process.platform == 'darwin') - return done() + if (process.env.TRAVIS !== 'true' || process.platform === 'darwin') return done() var listener = function () { webview.removeEventListener('enter-html-full-screen', listener) @@ -568,8 +571,7 @@ describe(' tag', function () { }) it('can return the result of the executed script', function (done) { - if (process.env.TRAVIS === 'true' && process.platform == 'darwin') - return done() + if (process.env.TRAVIS === 'true' && process.platform === 'darwin') return done() var listener = function () { var jsScript = "'4'+2" @@ -652,7 +654,7 @@ describe(' tag', function () { listener2() } else { activeMatchOrdinal.push(e.result.activeMatchOrdinal) - if (e.result.activeMatchOrdinal == totalMatches) { + if (e.result.activeMatchOrdinal === totalMatches) { assert.deepEqual(activeMatchOrdinal, [1, 2, 3]) webview.stopFindInPage('clearSelection') done() From c4b6cf4a8eacfa89c609910e7967d773be593d8d Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 14:00:41 -0700 Subject: [PATCH 0318/1265] do more manual cleanup and specify globals --- lib/common/asar.js | 2 ++ lib/renderer/inspector.js | 2 ++ package.json | 3 ++- spec/api-web-request-spec.js | 2 ++ spec/fixtures/module/fork_ping.js | 4 +++- spec/fixtures/module/function.js | 2 +- spec/fixtures/module/locale-compare.js | 2 +- spec/fixtures/pages/service-worker/service-worker.js | 2 ++ spec/node-spec.js | 2 ++ spec/static/main.js | 8 ++++---- 10 files changed, 21 insertions(+), 8 deletions(-) diff --git a/lib/common/asar.js b/lib/common/asar.js index 26241281322..dbf56705025 100644 --- a/lib/common/asar.js +++ b/lib/common/asar.js @@ -1,3 +1,5 @@ +/* globals $, xit */ + (function () { const asar = process.binding('atom_common_asar') const child_process = require('child_process') diff --git a/lib/renderer/inspector.js b/lib/renderer/inspector.js index 61be586f788..2b0fcbc80c1 100644 --- a/lib/renderer/inspector.js +++ b/lib/renderer/inspector.js @@ -1,3 +1,5 @@ +/* globals InspectorFrontendHost, WebInspector, DevToolsAPI, DevToolsAPI, Blob */ + window.onload = function () { // Use menu API to show context menu. InspectorFrontendHost.showContextMenuAtPoint = createMenu diff --git a/package.json b/package.json index 855d5155504..2d5c61f494f 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ }, "standard": { "ignore": ["/vendor"], - "globals": ["afterEach", "beforeEach", "describe", "it", "location"] + "globals": ["$", "after", "afterEach", "before", + "beforeEach", "describe", "it", "location"] }, "private": true, "scripts": { diff --git a/spec/api-web-request-spec.js b/spec/api-web-request-spec.js index abc4f9568cd..8ce4bca8db1 100644 --- a/spec/api-web-request-spec.js +++ b/spec/api-web-request-spec.js @@ -1,3 +1,5 @@ +/* globals $ */ + const assert = require('assert') const http = require('http') const qs = require('querystring') diff --git a/spec/fixtures/module/fork_ping.js b/spec/fixtures/module/fork_ping.js index 76bf1b0e368..aa515333400 100644 --- a/spec/fixtures/module/fork_ping.js +++ b/spec/fixtures/module/fork_ping.js @@ -1,8 +1,10 @@ +const path = require('path') + process.on('uncaughtException', function (error) { process.send(error.stack) }) -var child = require('child_process').fork(__dirname + '/ping.js') +var child = require('child_process').fork(path.join(__dirname, '/ping.js')) process.on('message', function (msg) { child.send(msg) }) diff --git a/spec/fixtures/module/function.js b/spec/fixtures/module/function.js index 526daf76fa8..8a2bb6c421e 100644 --- a/spec/fixtures/module/function.js +++ b/spec/fixtures/module/function.js @@ -1 +1 @@ -exports.aFunction = function () { return 1127; } +exports.aFunction = function () { return 1127 } diff --git a/spec/fixtures/module/locale-compare.js b/spec/fixtures/module/locale-compare.js index 3446e2f443d..40275400443 100644 --- a/spec/fixtures/module/locale-compare.js +++ b/spec/fixtures/module/locale-compare.js @@ -2,6 +2,6 @@ process.on('message', function () { process.send([ 'a'.localeCompare('a'), 'ä'.localeCompare('z', 'de'), - 'ä'.localeCompare('a', 'sv', { sensitivity: 'base' }), + 'ä'.localeCompare('a', 'sv', { sensitivity: 'base' }) ]) }) diff --git a/spec/fixtures/pages/service-worker/service-worker.js b/spec/fixtures/pages/service-worker/service-worker.js index 7d80f45e2df..be5ecefd570 100644 --- a/spec/fixtures/pages/service-worker/service-worker.js +++ b/spec/fixtures/pages/service-worker/service-worker.js @@ -1,3 +1,5 @@ +/* globals self, URL, Response */ + self.addEventListener('fetch', function (event) { var requestUrl = new URL(event.request.url) diff --git a/spec/node-spec.js b/spec/node-spec.js index 286c4d6f916..68b328b2ab9 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -1,3 +1,5 @@ +/* globals xit */ + const assert = require('assert') const child_process = require('child_process') const fs = require('fs') diff --git a/spec/static/main.js b/spec/static/main.js index f1d2a5eafa6..d48285a5191 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -17,7 +17,7 @@ var argv = require('yargs') .argv var window = null -process.port = 0; // will be used by crash-reporter spec. +process.port = 0 // will be used by crash-reporter spec. app.commandLine.appendSwitch('js-flags', '--expose_gc') app.commandLine.appendSwitch('ignore-certificate-errors') @@ -48,7 +48,7 @@ ipcMain.on('process.exit', function (event, code) { }) ipcMain.on('eval', function (event, script) { - event.returnValue = eval(script) + event.returnValue = eval(script) // eslint-disable-line }) ipcMain.on('echo', function (event, msg) { @@ -84,10 +84,10 @@ app.on('ready', function () { height: 600, webPreferences: { javascript: true // Test whether web preferences crashes. - }, + } }) window.loadURL(url.format({ - pathname: __dirname + '/index.html', + pathname: path.join(__dirname, '/index.html'), protocol: 'file', query: { grep: argv.grep, From 9db733a4ffd0a6ada67b95232ae64aead1370550 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 16:11:00 -0700 Subject: [PATCH 0319/1265] mostly more globals --- spec/api-web-frame-spec.js | 2 ++ spec/asar-spec.js | 30 +++++++++++++++++------------- spec/chromium-spec.js | 13 ++++++++----- spec/fixtures/module/class.js | 4 ++-- spec/static/main.js | 5 ++--- tools/dump-version-info.js | 14 +++++++------- 6 files changed, 38 insertions(+), 30 deletions(-) diff --git a/spec/api-web-frame-spec.js b/spec/api-web-frame-spec.js index 519966c8cea..83fb4a560c5 100644 --- a/spec/api-web-frame-spec.js +++ b/spec/api-web-frame-spec.js @@ -1,3 +1,5 @@ +/* globals fetch */ + const assert = require('assert') const path = require('path') const webFrame = require('electron').webFrame diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 050d8d7deda..de235eb66ed 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -1,3 +1,5 @@ +/* globals xit */ + const assert = require('assert') const child_process = require('child_process') const fs = require('fs') @@ -560,7 +562,9 @@ describe('asar package', function () { if (process.platform !== 'darwin') { return } - ref2 = require('child_process'), execFile = ref2.execFile, execFileSync = ref2.execFileSync + ref2 = require('child_process') + execFile = ref2.execFile + execFileSync = ref2.execFileSync echo = path.join(fixtures, 'asar', 'echo.asar', 'echo') it('executes binaries', function (done) { @@ -609,18 +613,18 @@ describe('asar package', function () { it('disables asar support in sync API', function () { var file = path.join(fixtures, 'asar', 'a.asar', 'file1') var dir = path.join(fixtures, 'asar', 'a.asar', 'dir1') - assert.throws((function () { + assert.throws(function () { fs.readFileSync(file) - }), new RegExp(errorName)) - assert.throws((function () { + }, new RegExp(errorName)) + assert.throws(function () { fs.lstatSync(file) - }), new RegExp(errorName)) - assert.throws((function () { + }, new RegExp(errorName)) + assert.throws(function () { fs.realpathSync(file) - }), new RegExp(errorName)) - assert.throws((function () { + }, new RegExp(errorName)) + assert.throws(function () { fs.readdirSync(dir) - }), new RegExp(errorName)) + }, new RegExp(errorName)) }) it('disables asar support in async API', function (done) { @@ -647,9 +651,9 @@ describe('asar package', function () { var content1 = fs.readFileSync(asar) var content2 = originalFs.readFileSync(asar) assert.equal(content1.compare(content2), 0) - assert.throws((function () { + assert.throws(function () { fs.readdirSync(asar) - }), /ENOTDIR/) + }, /ENOTDIR/) }) }) }) @@ -785,9 +789,9 @@ describe('asar package', function () { it('throws error when calling inside asar archive', function () { var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') - assert.throws((function () { + assert.throws(function () { mkdirp.sync(p) - }), new RegExp('ENOTDIR')) + }, new RegExp('ENOTDIR')) }) }) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 40e46dcb5ea..244f9f77a1e 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -1,3 +1,5 @@ +/* globals xdescribe, Worker, SharedWorker, WebSocket, HTMLElement */ + const assert = require('assert') const http = require('http') const path = require('path') @@ -295,15 +297,15 @@ describe('chromium feature', function () { describe('creating a Uint8Array under browser side', function () { it('does not crash', function () { var RUint8Array = remote.getGlobal('Uint8Array') - new RUint8Array + var arr = new RUint8Array() + assert(arr) }) }) describe('webgl', function () { it('can be get as context in canvas', function () { - if (process.platform === 'linux') { - return - } + if (process.platform === 'linux') return + var webgl = document.createElement('canvas').getContext('webgl') assert.notEqual(webgl, null) }) @@ -387,7 +389,8 @@ describe('chromium feature', function () { done('user agent is empty') } }) - new WebSocket('ws://127.0.0.1:' + port) + var socket = new WebSocket(`ws://127.0.0.1: ${port}`) + assert(socket) }) }) }) diff --git a/spec/fixtures/module/class.js b/spec/fixtures/module/class.js index c961dd8040c..9b971e52335 100644 --- a/spec/fixtures/module/class.js +++ b/spec/fixtures/module/class.js @@ -24,6 +24,6 @@ class DerivedClass extends BaseClass { } module.exports = { - base: new BaseClass, - derived: new DerivedClass, + base: new BaseClass(), + derived: new DerivedClass() } diff --git a/spec/static/main.js b/spec/static/main.js index d48285a5191..2707f6a686d 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -116,7 +116,7 @@ app.on('ready', function () { setImmediate(function () { try { item.getURL() - } catch(err) { + } catch (err) { window.webContents.send('download-error', url, filename, err.message) } }) @@ -132,8 +132,7 @@ app.on('ready', function () { item.getContentDisposition(), item.getFilename()) }) - if (need_cancel) - item.cancel() + if (need_cancel) item.cancel() } }) event.returnValue = 'done' diff --git a/tools/dump-version-info.js b/tools/dump-version-info.js index 1abe2ac1398..b5df69f4e9b 100644 --- a/tools/dump-version-info.js +++ b/tools/dump-version-info.js @@ -45,7 +45,7 @@ function getIndexJsInServer (callback) { request(TARGET_URL, function (e, res, body) { if (e) { callback(e) - } else if (res.statusCode != 200) { + } else if (res.statusCode !== 200) { callback(new Error('Server returned ' + res.statusCode)) } else { callback(null, JSON.parse(body)) @@ -54,9 +54,9 @@ function getIndexJsInServer (callback) { } function findObjectByVersion (all, version) { - for (var i in all) - if (all[i].version == version) - return i + for (var i in all) { + if (all[i].version === version) return i + } return -1 } @@ -69,11 +69,11 @@ app.on('ready', function () { var current = getInfoForCurrentVersion() var found = findObjectByVersion(all, current.version) - if (found == -1) + if (found === -1) { all.unshift(current) - else + } else { all[found] = current - + } fs.writeFileSync(process.argv[2], JSON.stringify(all)) process.exit(0) }) From 5e4696f4a7240106efdca6df28cdc8325745c608 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 16:19:18 -0700 Subject: [PATCH 0320/1265] standardize more --- spec/api-debugger-spec.js | 14 +++++++------- spec/api-native-image-spec.js | 2 +- spec/api-protocol-spec.js | 6 +++--- spec/api-session-spec.js | 4 +++- spec/asar-spec.js | 6 +++--- spec/chromium-spec.js | 10 ++++++---- 6 files changed, 23 insertions(+), 19 deletions(-) diff --git a/spec/api-debugger-spec.js b/spec/api-debugger-spec.js index 1648ac1c3cd..fdad013b8cf 100644 --- a/spec/api-debugger-spec.js +++ b/spec/api-debugger-spec.js @@ -30,7 +30,7 @@ describe('debugger module', function () { w.webContents.openDevTools() try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { assert(w.webContents.debugger.isAttached()) done() } @@ -41,7 +41,7 @@ describe('debugger module', function () { it('fails when protocol version is not supported', function (done) { try { w.webContents.debugger.attach('2.0') - } catch(err) { + } catch (err) { assert(!w.webContents.debugger.isAttached()) done() } @@ -50,7 +50,7 @@ describe('debugger module', function () { it('attaches when no protocol version is specified', function (done) { try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { done('unexpected error : ' + err) } assert(w.webContents.debugger.isAttached()) @@ -67,7 +67,7 @@ describe('debugger module', function () { }) try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { done('unexpected error : ' + err) } w.webContents.debugger.detach() @@ -79,7 +79,7 @@ describe('debugger module', function () { w.webContents.loadURL('about:blank') try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { done('unexpected error : ' + err) } var callback = function (err, res) { @@ -101,7 +101,7 @@ describe('debugger module', function () { w.webContents.loadURL(url) try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { done('unexpected error : ' + err) } w.webContents.debugger.on('message', function (e, method, params) { @@ -120,7 +120,7 @@ describe('debugger module', function () { w.webContents.loadURL('about:blank') try { w.webContents.debugger.attach() - } catch(err) { + } catch (err) { done('unexpected error : ' + err) } w.webContents.debugger.sendCommand('Test', function (err) { diff --git a/spec/api-native-image-spec.js b/spec/api-native-image-spec.js index 6c5092cf7c3..196ed1356d7 100644 --- a/spec/api-native-image-spec.js +++ b/spec/api-native-image-spec.js @@ -45,7 +45,7 @@ describe('nativeImage module', () => { assert.equal(nsimage.length, 8) // If all bytes are null, that's Bad - assert.equal(nsimage.reduce((acc, x) => acc || (x != 0), false), true) + assert.equal(nsimage.reduce((acc, x) => acc || (x !== 0), false), true) }) }) }) diff --git a/spec/api-protocol-spec.js b/spec/api-protocol-spec.js index 001359d3850..9f2a25eb4a5 100644 --- a/spec/api-protocol-spec.js +++ b/spec/api-protocol-spec.js @@ -183,7 +183,7 @@ describe('protocol module', function () { it('fails when sending object other than string', function (done) { var handler = function (request, callback) { - callback(new Date) + callback(new Date()) } protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { @@ -413,7 +413,7 @@ describe('protocol module', function () { it('fails when sending unsupported content', function (done) { var handler = function (request, callback) { - callback(new Date) + callback(new Date()) } protocol.registerBufferProtocol(protocolName, handler, function (error) { if (error) { @@ -491,7 +491,7 @@ describe('protocol module', function () { it('fails when sending unsupported content', function (done) { var handler = function (request, callback) { - callback(new Date) + callback(new Date()) } protocol.registerHttpProtocol(protocolName, handler, function (error) { if (error) { diff --git a/spec/api-session-spec.js b/spec/api-session-spec.js index 2f4a50f69e5..563599f1368 100644 --- a/spec/api-session-spec.js +++ b/spec/api-session-spec.js @@ -1,3 +1,5 @@ +/* globals WebView */ + const assert = require('assert') const http = require('http') const path = require('path') @@ -231,7 +233,7 @@ describe('session module', function () { downloadServer.listen(0, '127.0.0.1', function () { var port = downloadServer.address().port ipcRenderer.sendSync('set-download-option', false, false) - var webview = new WebView + var webview = new WebView() webview.src = 'file://' + fixtures + '/api/blank.html' webview.addEventListener('did-finish-load', function () { webview.downloadURL(url + ':' + port + '/') diff --git a/spec/asar-spec.js b/spec/asar-spec.js index de235eb66ed..508ce8b557b 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -18,7 +18,7 @@ describe('asar package', function () { describe('fs.readFileSync', function () { it('does not leak fd', function () { var readCalls = 1 - while(readCalls <= 10000) { + while (readCalls <= 10000) { fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'ipc.js')) readCalls++ } @@ -530,9 +530,9 @@ describe('asar package', function () { describe('fs.mkdirSync', function () { it('throws error when calling inside asar archive', function () { var p = path.join(fixtures, 'asar', 'a.asar', 'not-exist') - assert.throws((function () { + assert.throws(function () { fs.mkdirSync(p) - }), new RegExp('ENOTDIR')) + }, new RegExp('ENOTDIR')) }) }) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 244f9f77a1e..a27d630b04c 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -103,10 +103,11 @@ describe('chromium feature', function () { navigator.mediaDevices.enumerateDevices().then((devices) => { const labels = devices.map((device) => device.label) const labelFound = labels.some((label) => !!label) - if (labelFound) + if (labelFound) { done() - else + } else { done('No device labels found: ' + JSON.stringify(labels)) + } }).catch(done) }) }) @@ -171,8 +172,9 @@ describe('chromium feature', function () { it('inherit options of parent window', function (done) { var b listener = function (event) { - var height, ref1, width - ref1 = remote.getCurrentWindow().getSize(), width = ref1[0], height = ref1[1] + var ref1 = remote.getCurrentWindow().getSize() + var width = ref1[0] + var height = ref1[1] assert.equal(event.data, 'size: ' + width + ' ' + height) b.close() done() From c5f70c8d9976eae97ca5d41f20a03f5d31c14a47 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 16:31:06 -0700 Subject: [PATCH 0321/1265] dance around error checking with this one weird trick --- spec/api-debugger-spec.js | 16 ++++++++++------ spec/api-ipc-spec.js | 6 +++--- spec/chromium-spec.js | 2 +- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/spec/api-debugger-spec.js b/spec/api-debugger-spec.js index fdad013b8cf..634d965a85f 100644 --- a/spec/api-debugger-spec.js +++ b/spec/api-debugger-spec.js @@ -80,24 +80,28 @@ describe('debugger module', function () { try { w.webContents.debugger.attach() } catch (err) { - done('unexpected error : ' + err) + return done('unexpected error : ' + err) } + /* eslint-disable */ + // standard expects callback errors to be handled, + // but for some reason this err is not actually null.. var callback = function (err, res) { assert(!res.wasThrown) assert.equal(res.result.value, 6) w.webContents.debugger.detach() done() } + /* eslint-enable */ const params = { - 'expression': '4+2', + 'expression': '4+2' } w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback) }) it('fires message event', function (done) { - var url = process.platform != 'win32' ? - 'file://' + path.join(fixtures, 'pages', 'a.html') : - 'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/') + var url = process.platform !== 'win32' + ? 'file://' + path.join(fixtures, 'pages', 'a.html') + : 'file:///' + path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/') w.webContents.loadURL(url) try { w.webContents.debugger.attach() @@ -105,7 +109,7 @@ describe('debugger module', function () { done('unexpected error : ' + err) } w.webContents.debugger.on('message', function (e, method, params) { - if (method == 'Console.messageAdded') { + if (method === 'Console.messageAdded') { assert.equal(params.message.type, 'log') assert.equal(params.message.url, url) assert.equal(params.message.text, 'a') diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 862a6c99c17..0b279ef7266 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -60,7 +60,7 @@ describe('ipc module', function () { it('can construct an object from its member', function () { var call = remote.require(path.join(fixtures, 'module', 'call.js')) - var obj = new call.constructor + var obj = new call.constructor // eslint-disable-line assert.equal(obj.test, 'test') }) @@ -68,7 +68,7 @@ describe('ipc module', function () { var remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js')) assert.equal(remoteFunctions.aFunction(), 1127) - remoteFunctions.aFunction = function () { return 1234; } + remoteFunctions.aFunction = function () { return 1234 } assert.equal(remoteFunctions.aFunction(), 1234) assert.equal(delete remoteFunctions.aFunction, true) @@ -106,7 +106,7 @@ describe('ipc module', function () { it('can return same object with different getters', function () { var contents1 = remote.getCurrentWindow().webContents var contents2 = remote.getCurrentWebContents() - assert(contents1 == contents2) + assert(contents1 === contents2) }) }) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index a27d630b04c..87140be7c80 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -391,7 +391,7 @@ describe('chromium feature', function () { done('user agent is empty') } }) - var socket = new WebSocket(`ws://127.0.0.1: ${port}`) + var socket = new WebSocket(`ws://127.0.0.1:${port}`) assert(socket) }) }) From 14fb3c4598a919d58c641b4ded5d55e2888a962f Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 16:33:16 -0700 Subject: [PATCH 0322/1265] throw error if it exists --- spec/api-crash-reporter-spec.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/spec/api-crash-reporter-spec.js b/spec/api-crash-reporter-spec.js index 708daeab956..2e49fdc36c5 100644 --- a/spec/api-crash-reporter-spec.js +++ b/spec/api-crash-reporter-spec.js @@ -40,9 +40,8 @@ describe('crash-reporter module', function () { server.close() var form = new multiparty.Form() form.parse(req, function (error, fields) { - if (called) { - return - } + if (error) throw error + if (called) return called = true assert.equal(fields['prod'], 'Electron') assert.equal(fields['ver'], process.versions['electron']) From fd0f9519f104438866fc601e63d1ad72abc2f595 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 16:36:08 -0700 Subject: [PATCH 0323/1265] remove useless constructors --- lib/renderer/web-view/guest-view-internal.js | 4 +++- lib/renderer/web-view/web-view-attributes.js | 10 ++-------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index 48ddf5ea10b..6c5a499ca9d 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -1,3 +1,5 @@ +/* globals Event */ + 'use strict' const ipcRenderer = require('electron').ipcRenderer @@ -102,5 +104,5 @@ module.exports = { }, setSize: function (guestInstanceId, params) { return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params) - }, + } } diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index 712973cea85..922aaa8c017 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -1,3 +1,5 @@ +/* globals MutationObserver */ + 'use strict' const WebViewImpl = require('./web-view') @@ -60,10 +62,6 @@ class WebViewAttribute { // An attribute that is treated as a Boolean. class BooleanAttribute extends WebViewAttribute { - constructor (name, webViewImpl) { - super(name, webViewImpl) - } - getValue () { return this.webViewImpl.webviewNode.hasAttribute(this.name) } @@ -79,10 +77,6 @@ class BooleanAttribute extends WebViewAttribute { // Attribute used to define the demension limits of autosizing. class AutosizeDimensionAttribute extends WebViewAttribute { - constructor (name, webViewImpl) { - super(name, webViewImpl) - } - getValue () { return parseInt(this.webViewImpl.webviewNode.getAttribute(this.name)) || 0 } From cfdfdc8cccc753ce16c9fb1b19096d5d5b36227a Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 17:16:08 -0700 Subject: [PATCH 0324/1265] standardize by hand --- lib/renderer/web-view/web-view.js | 10 ++++++---- spec/api-browser-window-spec.js | 24 ++++++++++-------------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index f03427e5b5f..55d94824c24 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -1,3 +1,5 @@ +/* globals Event, HTMLObjectElement */ + 'use strict' const deprecate = require('electron').deprecate @@ -72,7 +74,7 @@ var WebViewImpl = (function () { this.beforeFirstNavigation = true this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true } - return this.internalInstanceId = 0 + this.internalInstanceId = 0 } // Sets the .request property. @@ -267,7 +269,7 @@ var registerBrowserPluginElement = function () { this.setAttribute('id', 'browser-plugin-' + getNextId()) // The node fills in the container. - return this.style.flex = '1 1 auto' + this.style.flex = '1 1 auto' } proto.attributeChangedCallback = function (name, oldValue, newValue) { var internal @@ -374,7 +376,7 @@ var registerWebViewElement = function () { 'downloadURL', 'inspectServiceWorker', 'print', - 'printToPDF', + 'printToPDF' ] nonblockMethods = [ 'insertCSS', @@ -383,7 +385,7 @@ var registerWebViewElement = function () { 'sendInputEvent', 'setZoomFactor', 'setZoomLevel', - 'setZoomLevelLimits', + 'setZoomLevelLimits' ] // Forward proto.foo* method calls to WebViewImpl.foo*. diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 77e8b004bfe..a5b14c17425 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -87,9 +87,9 @@ describe('browser-window module', function () { it('prevents users to access methods of webContents', function () { var webContents = w.webContents w.destroy() - assert.throws((function () { + assert.throws(function () { webContents.getId() - }), /Object has been destroyed/) + }, /Object has been destroyed/) }) }) @@ -522,8 +522,7 @@ describe('browser-window module', function () { w.loadURL('file://' + fixtures + '/api/blank.html') w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. - if (called) - return + if (called) return called = true assert.notEqual(data.length, 0) @@ -595,8 +594,7 @@ describe('browser-window module', function () { describe('window states (excluding Linux)', function () { // Not implemented on Linux. - if (process.platform == 'linux') - return + if (process.platform === 'linux') return describe('movable state', function () { it('can be changed with movable option', function () { @@ -657,8 +655,7 @@ describe('browser-window module', function () { describe('fullscreenable state', function () { // Only implemented on OS X. - if (process.platform != 'darwin') - return + if (process.platform !== 'darwin') return it('can be changed with fullscreenable option', function () { w.destroy() @@ -696,14 +693,13 @@ describe('browser-window module', function () { // dynamically. it('can be changed with hasShadow option', function () { w.destroy() - let hasShadow = process.platform == 'darwin' ? false : true + let hasShadow = process.platform !== 'darwin' w = new BrowserWindow({show: false, hasShadow: hasShadow}) assert.equal(w.hasShadow(), hasShadow) }) it('can be changed with setHasShadow method', function () { - if (process.platform != 'darwin') - return + if (process.platform !== 'darwin') return assert.equal(w.hasShadow(), true) w.setHasShadow(false) @@ -763,19 +759,19 @@ describe('browser-window module', function () { describe('deprecated options', function () { it('throws a deprecation error for option keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({'min-width': 500}) + new BrowserWindow({'min-width': 500}) // eslint-disable-line }, 'min-width is deprecated. Use minWidth instead.') }) it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({webPreferences: {'node-integration': false}}) + new BrowserWindow({webPreferences: {'node-integration': false}}) // eslint-disable-line }, 'node-integration is deprecated. Use nodeIntegration instead.') }) it('throws a deprecation error for option keys that should be set on webPreferences', function () { assert.throws(function () { - new BrowserWindow({zoomFactor: 1}) + new BrowserWindow({zoomFactor: 1}) // eslint-disable-line }, 'options.zoomFactor is deprecated. Use options.webPreferences.zoomFactor instead.') }) }) From e6698102c9588a5bdf4a65dfd75a3e063c95f881 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 17:35:49 -0700 Subject: [PATCH 0325/1265] standardize by hand --- lib/browser/api/navigation-controller.js | 10 +++++----- lib/browser/api/web-contents.js | 13 ++++++++----- lib/browser/init.js | 2 +- lib/common/api/callbacks-registry.js | 2 +- lib/common/api/deprecate.js | 6 +++--- lib/common/asar.js | 2 +- lib/renderer/api/ipc.js | 2 +- lib/renderer/api/remote.js | 17 +++++++---------- lib/renderer/init.js | 2 +- lib/renderer/override.js | 4 +++- lib/renderer/web-view/web-view-attributes.js | 2 +- lib/renderer/web-view/web-view.js | 3 +-- spec/api-app-spec.js | 2 +- 13 files changed, 34 insertions(+), 33 deletions(-) diff --git a/lib/browser/api/navigation-controller.js b/lib/browser/api/navigation-controller.js index 21d885c738c..d9dedc91e34 100644 --- a/lib/browser/api/navigation-controller.js +++ b/lib/browser/api/navigation-controller.js @@ -5,12 +5,12 @@ const ipcMain = require('electron').ipcMain // The history operation in renderer is redirected to browser. ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function (event, method, ...args) { var ref - return (ref = event.sender)[method].apply(ref, args) + (ref = event.sender)[method].apply(ref, args) }) ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function (event, method, ...args) { var ref - return event.returnValue = (ref = event.sender)[method].apply(ref, args) + event.returnValue = (ref = event.sender)[method].apply(ref, args) }) // JavaScript implementation of Chromium's NavigationController. @@ -41,10 +41,10 @@ var NavigationController = (function () { // Go to index. this.currentIndex = this.pendingIndex this.pendingIndex = -1 - return this.history[this.currentIndex] = url + this.history[this.currentIndex] = url } else if (replaceEntry) { // Non-user initialized navigation. - return this.history[this.currentIndex] = url + this.history[this.currentIndex] = url } else { // Normal navigation. Clear history. this.history = this.history.slice(0, this.currentIndex + 1) @@ -111,7 +111,7 @@ var NavigationController = (function () { this.history = [] this.currentIndex = -1 this.pendingIndex = -1 - return this.inPageIndex = -1 + this.inPageIndex = -1 } NavigationController.prototype.goBack = function () { diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index acdd8da7275..9187c87bfcc 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -87,7 +87,7 @@ let wrapWebContents = function (webContents) { method = ref1[name] if (method instanceof Function) { (function (name, method) { - return webContents[name] = function () { + webContents[name] = function () { return method.apply(controller, arguments) } })(name, method) @@ -104,8 +104,7 @@ let wrapWebContents = function (webContents) { const asyncWebFrameMethods = function (requestId, method, callback, ...args) { this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args) ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, result) { - if (callback) - callback(result) + if (callback) callback(result) }) } @@ -117,10 +116,11 @@ let wrapWebContents = function (webContents) { callback = hasUserGesture hasUserGesture = false } - if (this.getURL() && !this.isLoading()) + if (this.getURL() && !this.isLoading()) { return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture) - else + } else { return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)) + } } // Dispatch IPC messages to the ipc module. @@ -128,11 +128,14 @@ let wrapWebContents = function (webContents) { return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) }) webContents.on('ipc-message-sync', function (event, [channel, ...args]) { + /* eslint-disable */ + // standard complains: Getter is not present Object.defineProperty(event, 'returnValue', { set: function (value) { return event.sendReply(JSON.stringify(value)) } }) + /* eslint-enable */ return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) }) diff --git a/lib/browser/init.js b/lib/browser/init.js index ad871cd7153..d04b174adb6 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -46,7 +46,7 @@ if (process.platform === 'win32') { // Always returns EOF for stdin stream. var Readable = require('stream').Readable - var stdin = new Readable + var stdin = new Readable() stdin.push(null) process.__defineGetter__('stdin', function () { return stdin diff --git a/lib/common/api/callbacks-registry.js b/lib/common/api/callbacks-registry.js index c8b8579601d..3e71899df29 100644 --- a/lib/common/api/callbacks-registry.js +++ b/lib/common/api/callbacks-registry.js @@ -20,7 +20,7 @@ class CallbacksRegistry { // Capture the location of the function and put it in the ID string, // so that release errors can be tracked down easily. regexp = /at (.*)/gi - stackString = (new Error).stack + stackString = (new Error()).stack while ((match = regexp.exec(stackString)) !== null) { location = match[1] if (location.indexOf('(native)') !== -1) { diff --git a/lib/common/api/deprecate.js b/lib/common/api/deprecate.js index f272915167f..ff34a2bdfe7 100644 --- a/lib/common/api/deprecate.js +++ b/lib/common/api/deprecate.js @@ -23,9 +23,9 @@ deprecate.rename = function (object, oldName, newName) { return this[newName].apply(this, arguments) } if (typeof object === 'function') { - return object.prototype[oldName] = newMethod + object.prototype[oldName] = newMethod } else { - return object[oldName] = newMethod + object[oldName] = newMethod } } @@ -33,7 +33,7 @@ deprecate.rename = function (object, oldName, newName) { deprecate.member = function (object, method, member) { var warned warned = false - return object.prototype[method] = function () { + object.prototype[method] = function () { if (!(warned || process.noDeprecation)) { warned = true deprecate.warn(method, member + '.' + method) diff --git a/lib/common/asar.js b/lib/common/asar.js index dbf56705025..f79075ce23d 100644 --- a/lib/common/asar.js +++ b/lib/common/asar.js @@ -1,4 +1,4 @@ -/* globals $, xit */ +/* globals $ */ (function () { const asar = process.binding('atom_common_asar') diff --git a/lib/renderer/api/ipc.js b/lib/renderer/api/ipc.js index bda68f7bedb..25519a308da 100644 --- a/lib/renderer/api/ipc.js +++ b/lib/renderer/api/ipc.js @@ -6,7 +6,7 @@ const EventEmitter = require('events').EventEmitter deprecate.warn('ipc module', 'require("electron").ipcRenderer') // Routes events of ipcRenderer. -var ipc = new EventEmitter +var ipc = new EventEmitter() ipcRenderer.emit = function (channel, event, ...args) { ipc.emit.apply(ipc, [channel].concat(args)) diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 0028a6191cd..5f60a970ff3 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -5,11 +5,11 @@ const CallbacksRegistry = require('electron').CallbacksRegistry const v8Util = process.atomBinding('v8_util') const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap -const callbacksRegistry = new CallbacksRegistry +const callbacksRegistry = new CallbacksRegistry() var includes = [].includes -var remoteObjectCache = new IDWeakMap +var remoteObjectCache = new IDWeakMap() // Check for circular reference. var isCircular = function (field, visited) { @@ -48,7 +48,7 @@ var wrapArgs = function (args, visited) { } else if ((value != null ? value.constructor.name : void 0) === 'Promise') { return { type: 'promise', - then: valueToMeta(function (v) { value.then(v); }) + then: valueToMeta(function (v) { value.then(v) }) } } else if ((value != null) && typeof value === 'object' && v8Util.getHiddenValue(value, 'atomId')) { return { @@ -94,8 +94,7 @@ var wrapArgs = function (args, visited) { // This matches |getObjectMemebers| in rpc-server. let setObjectMembers = function (object, metaId, members) { for (let member of members) { - if (object.hasOwnProperty(member.name)) - continue + if (object.hasOwnProperty(member.name)) continue let descriptor = { enumerable: member.enumerable } if (member.type === 'method') { @@ -134,8 +133,7 @@ let setObjectMembers = function (object, metaId, members) { // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. let setObjectPrototype = function (object, metaId, descriptor) { - if (descriptor === null) - return + if (descriptor === null) return let proto = {} setObjectMembers(proto, metaId, descriptor.members) setObjectPrototype(proto, metaId, descriptor.proto) @@ -169,8 +167,7 @@ let metaToValue = function (meta) { case 'exception': throw new Error(meta.message + '\n' + meta.stack) default: - if (remoteObjectCache.has(meta.id)) - return remoteObjectCache.get(meta.id) + if (remoteObjectCache.has(meta.id)) return remoteObjectCache.get(meta.id) if (meta.type === 'function') { // A shadow class to represent the remote function object. @@ -220,7 +217,7 @@ var metaToPlainObject = function (meta) { obj = (function () { switch (meta.type) { case 'error': - return new Error + return new Error() default: return {} } diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 511f9e57e8f..a005261c570 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -26,7 +26,7 @@ globalPaths.push(path.join(__dirname, 'api', 'exports')) // The global variable will be used by ipc for event dispatching var v8Util = process.atomBinding('v8_util') -v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter) +v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter()) // Use electron module after everything is ready. const electron = require('electron') diff --git a/lib/renderer/override.js b/lib/renderer/override.js index ddabf793ff7..e1fa947000f 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -1,3 +1,5 @@ +/* globals Event */ + 'use strict' const ipcRenderer = require('electron').ipcRenderer @@ -199,7 +201,7 @@ if (process.openerId != null) { } ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { - var hasChanged = _isVisible != isVisible || _isMinimized != isMinimized + var hasChanged = _isVisible !== isVisible || _isMinimized !== isMinimized if (hasChanged) { _isVisible = isVisible diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index 922aaa8c017..72395fe4a2c 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -40,7 +40,7 @@ class WebViewAttribute { setValueIgnoreMutation (value) { this.ignoreMutation = true this.setValue(value) - return this.ignoreMutation = false + this.ignoreMutation = false } // Defines this attribute as a property on the webview node. diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 55d94824c24..d5b57c65149 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -423,8 +423,7 @@ var registerWebViewElement = function () { let requestId = getNextId() ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, 'executeJavaScript', code, hasUserGesture) ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function (event, result) { - if (callback) - callback(result) + if (callback) callback(result) }) } diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 2a5417b9c50..c237ef17238 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -18,7 +18,7 @@ describe('electron module', function () { electron.hideInternalModules() try { require('clipboard') - } catch(err) { + } catch (err) { assert.equal(err.message, "Cannot find module 'clipboard'") done() } From 2c3cacdc087e58135818d6a82e5c468b816c3cf6 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 17:40:40 -0700 Subject: [PATCH 0326/1265] standardize by hand --- lib/browser/api/menu.js | 8 ++++---- lib/browser/api/session.js | 2 +- lib/browser/api/tray.js | 2 +- lib/browser/api/web-contents.js | 2 +- lib/browser/chrome-extension.js | 5 +++-- lib/browser/desktop-capturer.js | 2 +- lib/browser/guest-view-manager.js | 4 ++-- lib/browser/guest-window-manager.js | 6 +++--- 8 files changed, 16 insertions(+), 15 deletions(-) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 7330b89dd74..892f7a250fc 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -93,7 +93,7 @@ Menu.prototype._init = function () { this.commandsMap = {} this.groupsMap = {} this.items = [] - return this.delegate = { + this.delegate = { isCommandIdChecked: (commandId) => { var command = this.commandsMap[commandId] return command != null ? command.checked : undefined @@ -142,7 +142,7 @@ Menu.prototype._init = function () { } Menu.prototype.popup = function (window, x, y, positioningItem) { - if (typeof window != 'object' || window.constructor !== BrowserWindow) { + if (typeof window !== 'object' || window.constructor !== BrowserWindow) { // Shift. positioningItem = y y = x @@ -224,7 +224,7 @@ Menu.prototype.insert = function (pos, item) { // Remember the items. this.items.splice(pos, 0, item) - return this.commandsMap[item.commandId] = item + this.commandsMap[item.commandId] = item } // Force menuWillShow to be called @@ -284,7 +284,7 @@ Menu.buildFromTemplate = function (template) { } positionedTemplate.splice(insertIndex, 0, item) } - menu = new Menu + menu = new Menu() for (k = 0, len1 = positionedTemplate.length; k < len1; k++) { item = positionedTemplate[k] if (typeof item !== 'object') { diff --git a/lib/browser/api/session.js b/lib/browser/api/session.js index 01814774fdc..f0ff786cf2b 100644 --- a/lib/browser/api/session.js +++ b/lib/browser/api/session.js @@ -27,7 +27,7 @@ Object.defineProperty(exports, 'defaultSession', { var wrapSession = function (session) { // session is an EventEmitter. - return session.__proto__ = EventEmitter.prototype + session.__proto__ = EventEmitter.prototype } bindings._setWrapSession(wrapSession) diff --git a/lib/browser/api/tray.js b/lib/browser/api/tray.js index 1f9f5881b28..293825200e4 100644 --- a/lib/browser/api/tray.js +++ b/lib/browser/api/tray.js @@ -17,7 +17,7 @@ Tray.prototype.setContextMenu = function (menu) { this._setContextMenu(menu) // Keep a strong reference of menu. - return this.menu = menu + this.menu = menu } module.exports = Tray diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 9187c87bfcc..60c159467ff 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -168,7 +168,7 @@ let wrapWebContents = function (webContents) { deprecate.event(webContents, 'page-title-set', 'page-title-updated', function (...args) { return this.emit.apply(this, ['page-title-set'].concat(args)) }) - return webContents.printToPDF = function (options, callback) { + webContents.printToPDF = function (options, callback) { var printingSetting printingSetting = { pageRage: [], diff --git a/lib/browser/chrome-extension.js b/lib/browser/chrome-extension.js index db3e4e9f9a5..562e77a1150 100644 --- a/lib/browser/chrome-extension.js +++ b/lib/browser/chrome-extension.js @@ -71,7 +71,8 @@ app.on('will-quit', function () { // We can not use protocol or BrowserWindow until app is ready. app.once('ready', function () { var BrowserWindow, chromeExtensionHandler, i, init, len, protocol, srcDirectory - protocol = electron.protocol, BrowserWindow = electron.BrowserWindow + protocol = electron.protocol + BrowserWindow = electron.BrowserWindow // Load persisted extensions. loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions') @@ -133,7 +134,7 @@ app.once('ready', function () { // Load persisted extensions when devtools is opened. init = BrowserWindow.prototype._init - return BrowserWindow.prototype._init = function () { + BrowserWindow.prototype._init = function () { init.call(this) return this.on('devtools-opened', function () { return this._loadDevToolsExtensions(Object.keys(extensionInfoMap).map(function (key) { diff --git a/lib/browser/desktop-capturer.js b/lib/browser/desktop-capturer.js index fd234437ff5..5ba64fcddb1 100644 --- a/lib/browser/desktop-capturer.js +++ b/lib/browser/desktop-capturer.js @@ -29,7 +29,7 @@ ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function (event, capture // If the WebContents is destroyed before receiving result, just remove the // reference from requestsQueue to make the module not send the result to it. return event.sender.once('destroyed', function () { - return request.webContents = null + request.webContents = null }) }) diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index 0526e6a1361..ee633cf2901 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -131,7 +131,7 @@ var createGuest = function (embedder, params) { } this.loadURL(params.src, opts) } - return guest.allowPopups = params.allowpopups + guest.allowPopups = params.allowpopups }) // Dispatch events to embedder. @@ -188,7 +188,7 @@ var attachGuest = function (embedder, elementInstanceId, guestInstanceId, params webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences) guest.attachParams = params embedderElementsMap[key] = guestInstanceId - return reverseEmbedderElementsMap[guestInstanceId] = key + reverseEmbedderElementsMap[guestInstanceId] = key } // Destroy an existing guest instance. diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 94805a4c1fb..bc88337eb06 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -84,9 +84,9 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, options = mergeBrowserWindowOptions(event.sender, options) event.sender.emit('new-window', event, url, frameName, 'new-window', options) if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { - return event.returnValue = null + event.returnValue = null } else { - return event.returnValue = createGuest(event.sender, url, frameName, options) + event.returnValue = createGuest(event.sender, url, frameName, options) } }) @@ -97,7 +97,7 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function (event, gues ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function (event, guestId, method, ...args) { var ref1 - return event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0 + event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0 }) ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event, guestId, message, targetOrigin, sourceOrigin) { From 4e2f1311e099aa977589c2e620c702f8777a8cab Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 17:51:11 -0700 Subject: [PATCH 0327/1265] replace __proto__ with Object.setPrototype --- lib/browser/api/app.js | 4 ++-- lib/browser/api/auto-updater/auto-updater-native.js | 2 +- lib/browser/api/browser-window.js | 2 +- lib/browser/api/menu.js | 2 +- lib/browser/api/power-monitor.js | 2 +- lib/browser/api/screen.js | 2 +- lib/browser/api/session.js | 2 +- lib/browser/api/tray.js | 2 +- lib/browser/api/web-contents.js | 4 ++-- lib/renderer/api/web-frame.js | 2 +- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index ac2cf608414..c2e2899e77c 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -9,7 +9,7 @@ const bindings = process.atomBinding('app') const downloadItemBindings = process.atomBinding('download_item') const app = bindings.app -app.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(app, EventEmitter.prototype) app.setApplicationMenu = function (menu) { return Menu.setApplicationMenu(menu) @@ -102,7 +102,7 @@ deprecate.event(app, 'select-certificate', 'select-client-certificate') // Wrappers for native classes. var wrapDownloadItem = function (downloadItem) { // downloadItem is an EventEmitter. - downloadItem.__proto__ = EventEmitter.prototype + Object.setPrototypeOf(downloadItem, EventEmitter.prototype) // Deprecated. deprecate.property(downloadItem, 'url', 'getURL') diff --git a/lib/browser/api/auto-updater/auto-updater-native.js b/lib/browser/api/auto-updater/auto-updater-native.js index 86a1e63503c..1fff05dbd65 100644 --- a/lib/browser/api/auto-updater/auto-updater-native.js +++ b/lib/browser/api/auto-updater/auto-updater-native.js @@ -1,6 +1,6 @@ const EventEmitter = require('events').EventEmitter const autoUpdater = process.atomBinding('auto_updater').autoUpdater -autoUpdater.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(autoUpdater, EventEmitter.prototype) module.exports = autoUpdater diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index d29f4c74314..a00fef3b453 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -5,7 +5,7 @@ const deprecate = require('electron').deprecate const EventEmitter = require('events').EventEmitter const {BrowserWindow, _setDeprecatedOptionsCheck} = process.atomBinding('window') -BrowserWindow.prototype.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(BrowserWindow.prototype, EventEmitter.prototype) BrowserWindow.prototype._init = function () { // avoid recursive require. diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index 892f7a250fc..e05637e79e7 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -87,7 +87,7 @@ var indexToInsertByPosition = function (items, position) { const Menu = bindings.Menu -Menu.prototype.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype) Menu.prototype._init = function () { this.commandsMap = {} diff --git a/lib/browser/api/power-monitor.js b/lib/browser/api/power-monitor.js index e09a36e6608..02afeb5ba11 100644 --- a/lib/browser/api/power-monitor.js +++ b/lib/browser/api/power-monitor.js @@ -1,6 +1,6 @@ const EventEmitter = require('events').EventEmitter const powerMonitor = process.atomBinding('power_monitor').powerMonitor -powerMonitor.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(powerMonitor, EventEmitter.prototype) module.exports = powerMonitor diff --git a/lib/browser/api/screen.js b/lib/browser/api/screen.js index 42f6ad1a51a..9326ace2c4f 100644 --- a/lib/browser/api/screen.js +++ b/lib/browser/api/screen.js @@ -1,6 +1,6 @@ const EventEmitter = require('events').EventEmitter const screen = process.atomBinding('screen').screen -screen.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(screen, EventEmitter.prototype) module.exports = screen diff --git a/lib/browser/api/session.js b/lib/browser/api/session.js index f0ff786cf2b..47e00bd0462 100644 --- a/lib/browser/api/session.js +++ b/lib/browser/api/session.js @@ -27,7 +27,7 @@ Object.defineProperty(exports, 'defaultSession', { var wrapSession = function (session) { // session is an EventEmitter. - session.__proto__ = EventEmitter.prototype + Object.setPrototypeOf(session, EventEmitter.prototype) } bindings._setWrapSession(wrapSession) diff --git a/lib/browser/api/tray.js b/lib/browser/api/tray.js index 293825200e4..ce67dbe117a 100644 --- a/lib/browser/api/tray.js +++ b/lib/browser/api/tray.js @@ -2,7 +2,7 @@ const deprecate = require('electron').deprecate const EventEmitter = require('events').EventEmitter const Tray = process.atomBinding('tray').Tray -Tray.prototype.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(Tray.prototype, EventEmitter.prototype) Tray.prototype._init = function () { // Deprecated. diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 60c159467ff..ef3d703dee7 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -66,7 +66,7 @@ const webFrameMethods = [ let wrapWebContents = function (webContents) { // webContents is an EventEmitter. var controller, method, name, ref1 - webContents.__proto__ = EventEmitter.prototype + Object.setPrototypeOf(webContents, EventEmitter.prototype) // Every remote callback from renderer process would add a listenter to the // render-view-deleted event, so ignore the listenters warning. @@ -217,7 +217,7 @@ let wrapWebContents = function (webContents) { // Wrapper for native class. let wrapDebugger = function (webContentsDebugger) { // debugger is an EventEmitter. - webContentsDebugger.__proto__ = EventEmitter.prototype + Object.setPrototypeOf(webContentsDebugger, EventEmitter.prototype) } binding._setWrapWebContents(wrapWebContents) diff --git a/lib/renderer/api/web-frame.js b/lib/renderer/api/web-frame.js index 7f48f1eabbd..4a152d4f364 100644 --- a/lib/renderer/api/web-frame.js +++ b/lib/renderer/api/web-frame.js @@ -6,7 +6,7 @@ const EventEmitter = require('events').EventEmitter const webFrame = process.atomBinding('web_frame').webFrame // webFrame is an EventEmitter. -webFrame.__proto__ = EventEmitter.prototype +Object.setPrototypeOf(webFrame, EventEmitter.prototype) // Lots of webview would subscribe to webFrame's events. webFrame.setMaxListeners(0) From 42e7ee2b4aef6de396927d16e6429a6ec44dd681 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 18:00:30 -0700 Subject: [PATCH 0328/1265] finish standardizing! --- default_app/main.js | 7 ++++--- lib/browser/api/app.js | 2 +- lib/browser/api/auto-updater/squirrel-update-win.js | 4 ++-- lib/browser/api/browser-window.js | 7 +++---- lib/browser/api/menu-item.js | 13 ++++++++++++- lib/common/asar.js | 2 -- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/default_app/main.js b/default_app/main.js index dcbe2ca0c65..43c8d729804 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -243,7 +243,7 @@ function loadApplicationPackage (packagePath) { } else if (packageJson.name) { app.setName(packageJson.name) } - + app.setPath('userData', path.join(app.getPath('appData'), app.getName())) app.setPath('userCache', path.join(app.getPath('cache'), app.getName())) app.setAppPath(packagePath) @@ -251,7 +251,7 @@ function loadApplicationPackage (packagePath) { // Run the app. require('module')._load(packagePath, module, true) - } catch(e) { + } catch (e) { if (e.code === 'MODULE_NOT_FOUND') { app.focus() dialog.showErrorBox( @@ -319,5 +319,6 @@ if (option.file && !option.webdriver) { } else if (option.interactive) { startRepl() } else { - loadApplicationByUrl('file://' + __dirname + '/index.html') + var indexPath = path.join(__dirname, '/index.html') + loadApplicationByUrl(`file://${indexPath}`) } diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index c2e2899e77c..48a27cfc648 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -45,7 +45,7 @@ if (process.platform === 'darwin') { var appPath = null app.setAppPath = function (path) { - return appPath = path + appPath = path } app.getAppPath = function () { diff --git a/lib/browser/api/auto-updater/squirrel-update-win.js b/lib/browser/api/auto-updater/squirrel-update-win.js index d4f2d98ca50..da27e02aab6 100644 --- a/lib/browser/api/auto-updater/squirrel-update-win.js +++ b/lib/browser/api/auto-updater/squirrel-update-win.js @@ -30,10 +30,10 @@ var spawnUpdate = function (args, detached, callback) { stdout = '' stderr = '' spawnedProcess.stdout.on('data', function (data) { - return stdout += data + stdout += data }) spawnedProcess.stderr.on('data', function (data) { - return stderr += data + stderr += data }) errorEmitted = false spawnedProcess.on('error', function (error) { diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index a00fef3b453..7bbf898dafb 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -53,12 +53,11 @@ BrowserWindow.prototype._init = function () { this.webContents.on('page-title-updated', (event, title) => { // The page-title-updated event is not emitted immediately (see #3645), so // when the callback is called the BrowserWindow might have been closed. - if (this.isDestroyed()) - return + if (this.isDestroyed()) return + // Route the event to BrowserWindow. this.emit('page-title-updated', event, title) - if (!event.defaultPrevented) - this.setTitle(title) + if (!event.defaultPrevented) this.setTitle(title) }) // Sometimes the webContents doesn't get focus when window is shown, so we have diff --git a/lib/browser/api/menu-item.js b/lib/browser/api/menu-item.js index 62622317bbb..20666b0f36e 100644 --- a/lib/browser/api/menu-item.js +++ b/lib/browser/api/menu-item.js @@ -29,7 +29,18 @@ MenuItem = (function () { function MenuItem (options) { var click, ref const Menu = require('electron').Menu - click = options.click, this.selector = options.selector, this.type = options.type, this.role = options.role, this.label = options.label, this.sublabel = options.sublabel, this.accelerator = options.accelerator, this.icon = options.icon, this.enabled = options.enabled, this.visible = options.visible, this.checked = options.checked, this.submenu = options.submenu + click = options.click + this.selector = options.selector + this.type = options.type + this.role = options.role + this.label = options.label + this.sublabel = options.sublabel + this.accelerator = options.accelerator + this.icon = options.icon + this.enabled = options.enabled + this.visible = options.visible + this.checked = options.checked + this.submenu = options.submenu if ((this.submenu != null) && this.submenu.constructor !== Menu) { this.submenu = Menu.buildFromTemplate(this.submenu) } diff --git a/lib/common/asar.js b/lib/common/asar.js index f79075ce23d..26241281322 100644 --- a/lib/common/asar.js +++ b/lib/common/asar.js @@ -1,5 +1,3 @@ -/* globals $ */ - (function () { const asar = process.binding('atom_common_asar') const child_process = require('child_process') From 98b4353ef80f2dd55d7fe907d2cbb066d832f3e8 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 28 Mar 2016 22:10:27 -0700 Subject: [PATCH 0329/1265] replace snazzy with standard; autoformat package.json --- package.json | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 2d5c61f494f..efdaaa9163e 100644 --- a/package.json +++ b/package.json @@ -5,15 +5,25 @@ "asar": "^0.10.0", "eslint": "^2.1.0", "request": "*", - "snazzy": "^3.0.0" + "standard": "^6.0.8" }, "optionalDependencies": { "runas": "^3.0.0" }, "standard": { - "ignore": ["/vendor"], - "globals": ["$", "after", "afterEach", "before", - "beforeEach", "describe", "it", "location"] + "ignore": [ + "/vendor" + ], + "globals": [ + "$", + "after", + "afterEach", + "before", + "beforeEach", + "describe", + "it", + "location" + ] }, "private": true, "scripts": { From 6f845373a7cdb95e6de51aa07661a1fc674725d3 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Tue, 29 Mar 2016 10:33:17 -0700 Subject: [PATCH 0330/1265] do not return and assign --- lib/common/asar_init.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/asar_init.js b/lib/common/asar_init.js index 1b24cd57aa4..0f728200880 100644 --- a/lib/common/asar_init.js +++ b/lib/common/asar_init.js @@ -9,7 +9,7 @@ // Make graceful-fs work with asar. var source = process.binding('natives') source['original-fs'] = source.fs - return source['fs'] = ` + source['fs'] = ` var nativeModule = new process.NativeModule('original-fs') nativeModule.cache() nativeModule.compile() From e156faea5c6d076d91c8d81bc82f1c022e247527 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Tue, 29 Mar 2016 10:43:41 -0700 Subject: [PATCH 0331/1265] replace eslint with standard --- package.json | 2 +- script/eslint.py | 36 ------------------------------------ script/eslintrc-base.json | 36 ------------------------------------ script/eslintrc-spec.json | 7 ------- 4 files changed, 1 insertion(+), 80 deletions(-) delete mode 100755 script/eslint.py delete mode 100644 script/eslintrc-base.json delete mode 100644 script/eslintrc-spec.json diff --git a/package.json b/package.json index efdaaa9163e..332578e6ce5 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "scripts": { "bootstrap": "python ./script/bootstrap.py", "build": "python ./script/build.py -c D", - "lint": "python ./script/eslint.py && python ./script/cpplint.py", + "lint": "standard && python ./script/cpplint.py", "preinstall": "node -e 'process.exit(0)'", "repl": "python ./script/start.py --interactive", "start": "python ./script/start.py", diff --git a/script/eslint.py b/script/eslint.py deleted file mode 100755 index 4fbc5788570..00000000000 --- a/script/eslint.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -import glob -import os -import sys - -from lib.config import PLATFORM -from lib.util import execute - - -SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) - - -def main(): - os.chdir(SOURCE_ROOT) - - # Skip eslint on our Windows build machine for now. - if PLATFORM == 'win32' and os.getenv('JANKY_SHA1'): - return - - eslint = os.path.join(SOURCE_ROOT, 'node_modules', '.bin', 'eslint') - if sys.platform in ['win32', 'cygwin']: - eslint += '.cmd' - settings = ['--quiet', '--config'] - - sourceConfig = os.path.join('script', 'eslintrc-base.json') - sourceFiles = ['lib'] - execute([eslint] + settings + [sourceConfig] + sourceFiles) - - specConfig = os.path.join('script', 'eslintrc-spec.json') - specFiles = glob.glob('spec/*.js') - execute([eslint] + settings + [specConfig] + specFiles) - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/script/eslintrc-base.json b/script/eslintrc-base.json deleted file mode 100644 index f968a2d20c7..00000000000 --- a/script/eslintrc-base.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "rules": { - "indent": [ - 2, - 2, - { - "SwitchCase": 1 - } - ], - "quotes": [ - 0, - "single" - ], - "semi": [ - 2, - "always" - ], - "comma-dangle": 0, - "linebreak-style": 0, - "no-console": 0, - "no-undef": 2, - "no-unused-vars": 2 - }, - "env": { - "es6": true, - "node": true, - "browser": true - }, - "extends": "eslint:recommended", - "globals": { - "DevToolsAPI": false, - "InspectorFrontendHost": false, - "WebInspector": false, - "WebView": false - } -} diff --git a/script/eslintrc-spec.json b/script/eslintrc-spec.json deleted file mode 100644 index 5aa9df265d6..00000000000 --- a/script/eslintrc-spec.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "env": { - "jquery": true, - "mocha": true - }, - "extends": "./eslintrc-base.json" -} From 71f8ba6f7aa714fc1850162b0ff1e20b7947a7d2 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Tue, 29 Mar 2016 10:44:01 -0700 Subject: [PATCH 0332/1265] update CONTRIBUTING doc --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 67c1323205e..c7c221863dc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ possible with your report. If you can, please include: ## Submitting Pull Requests * 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). +* Follow the 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). From 0fd0887407744e89f7945c4c988c73557531cc3f Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 13:17:04 -0700 Subject: [PATCH 0333/1265] use standard.env.mocha instead of a list of globals --- package.json | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 332578e6ce5..c4b49cd3c7a 100644 --- a/package.json +++ b/package.json @@ -14,14 +14,11 @@ "ignore": [ "/vendor" ], + "env": { + "mocha": true + }, "globals": [ "$", - "after", - "afterEach", - "before", - "beforeEach", - "describe", - "it", "location" ] }, From 1a18151effcc2a6a0925585fdc1666fa71b60baa Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 13:30:30 -0700 Subject: [PATCH 0334/1265] remove eslint from devDependencies --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index c4b49cd3c7a..29085205956 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,6 @@ "version": "0.37.3", "devDependencies": { "asar": "^0.10.0", - "eslint": "^2.1.0", "request": "*", "standard": "^6.0.8" }, From b5afad9da707b7ba597b72d067d4ffbeb86cf4f5 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:06:50 -0700 Subject: [PATCH 0335/1265] avoid using eslint comment exceptions --- lib/browser/api/web-contents.js | 6 +++--- lib/browser/rpc-server.js | 4 ++-- spec/api-browser-window-spec.js | 6 +++--- spec/api-debugger-spec.js | 5 +---- spec/api-ipc-spec.js | 2 +- 5 files changed, 10 insertions(+), 13 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index ef3d703dee7..2ec7c14bae1 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -128,14 +128,14 @@ let wrapWebContents = function (webContents) { return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) }) webContents.on('ipc-message-sync', function (event, [channel, ...args]) { - /* eslint-disable */ - // standard complains: Getter is not present Object.defineProperty(event, 'returnValue', { set: function (value) { return event.sendReply(JSON.stringify(value)) + }, + get: function () { + return undefined } }) - /* eslint-enable */ return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) }) diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index eb1d0385fa1..79a52b13262 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -281,7 +281,7 @@ ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) { // Call new with array of arguments. // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible - let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) // eslint-disable-line + let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) event.returnValue = valueToMeta(event.sender, obj) } catch (error) { event.returnValue = exceptionToMeta(error) @@ -304,7 +304,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) let constructor = objectsRegistry.get(id)[method] // Call new with array of arguments. - let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) // eslint-disable-line + let obj = new (Function.prototype.bind.apply(constructor, [null].concat(args))) event.returnValue = valueToMeta(event.sender, obj) } catch (error) { event.returnValue = exceptionToMeta(error) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index a5b14c17425..468586eb7bb 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -759,19 +759,19 @@ describe('browser-window module', function () { describe('deprecated options', function () { it('throws a deprecation error for option keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({'min-width': 500}) // eslint-disable-line + return new BrowserWindow({'min-width': 500}) }, 'min-width is deprecated. Use minWidth instead.') }) it('throws a deprecation error for webPreference keys using hyphens instead of camel case', function () { assert.throws(function () { - new BrowserWindow({webPreferences: {'node-integration': false}}) // eslint-disable-line + return new BrowserWindow({webPreferences: {'node-integration': false}}) }, 'node-integration is deprecated. Use nodeIntegration instead.') }) it('throws a deprecation error for option keys that should be set on webPreferences', function () { assert.throws(function () { - new BrowserWindow({zoomFactor: 1}) // eslint-disable-line + return new BrowserWindow({zoomFactor: 1}) }, 'options.zoomFactor is deprecated. Use options.webPreferences.zoomFactor instead.') }) }) diff --git a/spec/api-debugger-spec.js b/spec/api-debugger-spec.js index 634d965a85f..27aacc7671c 100644 --- a/spec/api-debugger-spec.js +++ b/spec/api-debugger-spec.js @@ -82,16 +82,13 @@ describe('debugger module', function () { } catch (err) { return done('unexpected error : ' + err) } - /* eslint-disable */ - // standard expects callback errors to be handled, - // but for some reason this err is not actually null.. var callback = function (err, res) { + assert(!err.message) assert(!res.wasThrown) assert.equal(res.result.value, 6) w.webContents.debugger.detach() done() } - /* eslint-enable */ const params = { 'expression': '4+2' } diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 0b279ef7266..be4f788fb0d 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -60,7 +60,7 @@ describe('ipc module', function () { it('can construct an object from its member', function () { var call = remote.require(path.join(fixtures, 'module', 'call.js')) - var obj = new call.constructor // eslint-disable-line + var obj = new call.constructor() assert.equal(obj.test, 'test') }) From 6425ef42610bd8a1476cdeb041ab0f042d655cb9 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:07:16 -0700 Subject: [PATCH 0336/1265] restrict mocha scope to /spec; break out link tasks --- package.json | 13 +++++-------- spec/package.json | 5 +++++ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 29085205956..4b4691abb3b 100644 --- a/package.json +++ b/package.json @@ -11,21 +11,18 @@ }, "standard": { "ignore": [ + "/out", + "/spec", "/vendor" - ], - "env": { - "mocha": true - }, - "globals": [ - "$", - "location" ] }, "private": true, "scripts": { "bootstrap": "python ./script/bootstrap.py", "build": "python ./script/build.py -c D", - "lint": "standard && python ./script/cpplint.py", + "lint": "npm run lint-js && npm run lint-cpp", + "lint-js": "standard && standard spec", + "lint-cpp": "python ./script/cpplint.py", "preinstall": "node -e 'process.exit(0)'", "repl": "python ./script/start.py --interactive", "start": "python ./script/start.py", diff --git a/spec/package.json b/spec/package.json index 6d49f0da8b8..a6ca81c5ee9 100644 --- a/spec/package.json +++ b/spec/package.json @@ -18,5 +18,10 @@ "optionalDependencies": { "ffi": "2.0.0", "runas": "3.x" + }, + "standard": { + "env": { + "mocha": true + } } } From 47a61e9f2705b0e346117a26d375781029b7ed93 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:07:27 -0700 Subject: [PATCH 0337/1265] use window.location instead of location --- lib/renderer/chrome-api.js | 4 ++-- lib/renderer/init.js | 4 ++-- lib/renderer/override.js | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/renderer/chrome-api.js b/lib/renderer/chrome-api.js index eca791057c3..719066a6fae 100644 --- a/lib/renderer/chrome-api.js +++ b/lib/renderer/chrome-api.js @@ -4,9 +4,9 @@ const chrome = window.chrome = window.chrome || {} chrome.extension = { getURL: function (path) { return url.format({ - protocol: location.protocol, + protocol: window.location.protocol, slashes: true, - hostname: location.hostname, + hostname: window.location.hostname, pathname: path }) } diff --git a/lib/renderer/init.js b/lib/renderer/init.js index a005261c570..85b3a627fd3 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -65,11 +65,11 @@ for (i = 0, len = ref.length; i < len; i++) { } } -if (location.protocol === 'chrome-devtools:') { +if (window.location.protocol === 'chrome-devtools:') { // Override some inspector APIs. require('./inspector') nodeIntegration = 'true' -} else if (location.protocol === 'chrome-extension:') { +} else if (window.location.protocol === 'chrome-extension:') { // Add implementations of chrome API. require('./chrome-api') nodeIntegration = 'true' diff --git a/lib/renderer/override.js b/lib/renderer/override.js index e1fa947000f..a0177b70f84 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -70,7 +70,7 @@ var BrowserWindowProxy = (function () { if (targetOrigin == null) { targetOrigin = '*' } - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, location.origin) + return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, window.location.origin) } BrowserWindowProxy.prototype['eval'] = function (...args) { From afbc914f8b97f326b9027b98ccb23ba6be012d3d Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:12:59 -0700 Subject: [PATCH 0338/1265] try to fix CI linting --- script/cibuild | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/script/cibuild b/script/cibuild index 391b859a3d2..2ecc417eaf5 100755 --- a/script/cibuild +++ b/script/cibuild @@ -62,8 +62,8 @@ def main(): args += ['--dev'] run_script('bootstrap.py', args) - run_script('cpplint.py') - run_script('eslint.py') + execute([npm, 'run', 'lint']) + if PLATFORM != 'win32': run_script('pylint.py') if is_release: From 0d11b755db474a053b5945e8b82733caec0b06a2 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:16:16 -0700 Subject: [PATCH 0339/1265] say we are linting --- script/cibuild | 2 ++ 1 file changed, 2 insertions(+) diff --git a/script/cibuild b/script/cibuild index 2ecc417eaf5..437f4e27c66 100755 --- a/script/cibuild +++ b/script/cibuild @@ -62,6 +62,8 @@ def main(): args += ['--dev'] run_script('bootstrap.py', args) + sys.stderr.write('\nRunning `npm run lint`\n') + sys.stderr.flush() execute([npm, 'run', 'lint']) if PLATFORM != 'win32': From aadc0bee2547bc60444b9a8c29474b9b72442804 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:21:07 -0700 Subject: [PATCH 0340/1265] do not lint on windows CI --- script/cibuild | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/script/cibuild b/script/cibuild index 437f4e27c66..54cfa508910 100755 --- a/script/cibuild +++ b/script/cibuild @@ -62,11 +62,10 @@ def main(): args += ['--dev'] run_script('bootstrap.py', args) - sys.stderr.write('\nRunning `npm run lint`\n') - sys.stderr.flush() - execute([npm, 'run', 'lint']) - if PLATFORM != 'win32': + sys.stderr.write('\nRunning `npm run lint`\n') + sys.stderr.flush() + execute([npm, 'run', 'lint']) run_script('pylint.py') if is_release: run_script('build.py', ['-c', 'R']) From 7c58f7fb0294e5109af3a2ed310eddd5eae998f2 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:56:30 -0700 Subject: [PATCH 0341/1265] eradicate all per-file eslint globals --- lib/renderer/inspector.js | 11 +++++------ lib/renderer/override.js | 2 -- lib/renderer/web-view/guest-view-internal.js | 2 -- lib/renderer/web-view/web-view-attributes.js | 2 -- lib/renderer/web-view/web-view.js | 2 -- package.json | 5 ++++- spec/api-session-spec.js | 2 -- spec/api-web-frame-spec.js | 4 +--- spec/api-web-request-spec.js | 2 -- spec/asar-spec.js | 2 -- spec/chromium-spec.js | 1 - spec/fixtures/pages/service-worker/service-worker.js | 2 -- spec/node-spec.js | 2 -- spec/package.json | 9 +++++++-- spec/webview-spec.js | 2 -- 15 files changed, 17 insertions(+), 33 deletions(-) diff --git a/lib/renderer/inspector.js b/lib/renderer/inspector.js index 2b0fcbc80c1..d7ef7e1a935 100644 --- a/lib/renderer/inspector.js +++ b/lib/renderer/inspector.js @@ -1,11 +1,10 @@ -/* globals InspectorFrontendHost, WebInspector, DevToolsAPI, DevToolsAPI, Blob */ - window.onload = function () { + // Use menu API to show context menu. - InspectorFrontendHost.showContextMenuAtPoint = createMenu + window.InspectorFrontendHost.showContextMenuAtPoint = createMenu // Use dialog API to override file chooser dialog. - return (WebInspector.createFileSelectorElement = createFileSelectorElement) + return (window.WebInspector.createFileSelectorElement = createFileSelectorElement) } var convertToMenuTemplate = function (items) { @@ -32,8 +31,8 @@ var convertToMenuTemplate = function (items) { } if (item.id != null) { transformed.click = function () { - DevToolsAPI.contextMenuItemSelected(item.id) - return DevToolsAPI.contextMenuCleared() + window.DevToolsAPI.contextMenuItemSelected(item.id) + return window.DevToolsAPI.contextMenuCleared() } } return template.push(transformed) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index a0177b70f84..4bce0c6b770 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -1,5 +1,3 @@ -/* globals Event */ - 'use strict' const ipcRenderer = require('electron').ipcRenderer diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index 6c5a499ca9d..f4023d22701 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -1,5 +1,3 @@ -/* globals Event */ - 'use strict' const ipcRenderer = require('electron').ipcRenderer diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index 72395fe4a2c..c76e0d26f95 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -1,5 +1,3 @@ -/* globals MutationObserver */ - 'use strict' const WebViewImpl = require('./web-view') diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index d5b57c65149..0e96d0c0643 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -1,5 +1,3 @@ -/* globals Event, HTMLObjectElement */ - 'use strict' const deprecate = require('electron').deprecate diff --git a/package.json b/package.json index 4b4691abb3b..c12f3d37c42 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,10 @@ "/out", "/spec", "/vendor" - ] + ], + "env": { + "browser": true + } }, "private": true, "scripts": { diff --git a/spec/api-session-spec.js b/spec/api-session-spec.js index 563599f1368..d655788c79b 100644 --- a/spec/api-session-spec.js +++ b/spec/api-session-spec.js @@ -1,5 +1,3 @@ -/* globals WebView */ - const assert = require('assert') const http = require('http') const path = require('path') diff --git a/spec/api-web-frame-spec.js b/spec/api-web-frame-spec.js index 83fb4a560c5..450bf1c33ec 100644 --- a/spec/api-web-frame-spec.js +++ b/spec/api-web-frame-spec.js @@ -1,5 +1,3 @@ -/* globals fetch */ - const assert = require('assert') const path = require('path') const webFrame = require('electron').webFrame @@ -10,7 +8,7 @@ describe('webFrame module', function () { it('supports fetch api', function (done) { webFrame.registerURLSchemeAsPrivileged('file') var url = 'file://' + fixtures + '/assets/logo.png' - fetch(url).then(function (response) { + window.fetch(url).then(function (response) { assert(response.ok) done() }).catch(function (err) { diff --git a/spec/api-web-request-spec.js b/spec/api-web-request-spec.js index 8ce4bca8db1..abc4f9568cd 100644 --- a/spec/api-web-request-spec.js +++ b/spec/api-web-request-spec.js @@ -1,5 +1,3 @@ -/* globals $ */ - const assert = require('assert') const http = require('http') const qs = require('querystring') diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 508ce8b557b..45c4c119ca9 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -1,5 +1,3 @@ -/* globals xit */ - const assert = require('assert') const child_process = require('child_process') const fs = require('fs') diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 87140be7c80..b6e9a775ed0 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -1,4 +1,3 @@ -/* globals xdescribe, Worker, SharedWorker, WebSocket, HTMLElement */ const assert = require('assert') const http = require('http') diff --git a/spec/fixtures/pages/service-worker/service-worker.js b/spec/fixtures/pages/service-worker/service-worker.js index be5ecefd570..7d80f45e2df 100644 --- a/spec/fixtures/pages/service-worker/service-worker.js +++ b/spec/fixtures/pages/service-worker/service-worker.js @@ -1,5 +1,3 @@ -/* globals self, URL, Response */ - self.addEventListener('fetch', function (event) { var requestUrl = new URL(event.request.url) diff --git a/spec/node-spec.js b/spec/node-spec.js index 68b328b2ab9..286c4d6f916 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -1,5 +1,3 @@ -/* globals xit */ - const assert = require('assert') const child_process = require('child_process') const fs = require('fs') diff --git a/spec/package.json b/spec/package.json index a6ca81c5ee9..0439f4b0ec0 100644 --- a/spec/package.json +++ b/spec/package.json @@ -21,7 +21,12 @@ }, "standard": { "env": { - "mocha": true - } + "mocha": true, + "jquery": true, + "serviceworker": true + }, + "globals": [ + "WebView" + ] } } diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 4fdba97249a..e5116293563 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -1,5 +1,3 @@ -/* globals btoa, WebView, xdescribe */ - const assert = require('assert') const path = require('path') const http = require('http') From d5e8bb7f120c55374bd06927b7359e1412dcc4db Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 14:59:39 -0700 Subject: [PATCH 0342/1265] derp --- lib/renderer/inspector.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/renderer/inspector.js b/lib/renderer/inspector.js index d7ef7e1a935..df151cf1b5e 100644 --- a/lib/renderer/inspector.js +++ b/lib/renderer/inspector.js @@ -1,5 +1,4 @@ window.onload = function () { - // Use menu API to show context menu. window.InspectorFrontendHost.showContextMenuAtPoint = createMenu From 9efd29d059d30ae7b4d6cbccc9bdf6229b51a391 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 15:15:33 -0700 Subject: [PATCH 0343/1265] fix a minor style issue --- lib/renderer/override.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 4bce0c6b770..896103b6c1f 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -154,7 +154,7 @@ window.open = function (url, frameName, features) { } // Use the dialog API to implement alert(). -window.alert = function(message, title) { +window.alert = function (message, title) { var buttons if (arguments.length === 0) { message = '' From 252121ac7022136ca842b3088476495ac3858725 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Wed, 30 Mar 2016 16:29:30 -0700 Subject: [PATCH 0344/1265] give anonymous function a name --- lib/renderer/override.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 896103b6c1f..07f02566bcc 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -6,12 +6,13 @@ const remote = require('electron').remote // Cache browser window visibility var _isVisible = true var _isMinimized = false -;(function () { +var initWindow = function initWindow () { var currentWindow currentWindow = remote.getCurrentWindow() _isVisible = currentWindow.isVisible() _isMinimized = currentWindow.isMinimized() -})() +} +initWindow() // Helper function to resolve relative url. var a = window.top.document.createElement('a') From afb82fcc1fca8712b9228327fb0c98e8c3ed7655 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 31 Mar 2016 10:21:21 +0900 Subject: [PATCH 0345/1265] Update native-mate for #4892 --- vendor/native_mate | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/native_mate b/vendor/native_mate index 38834cb9974..553326b0069 160000 --- a/vendor/native_mate +++ b/vendor/native_mate @@ -1 +1 @@ -Subproject commit 38834cb9974da9ddbc06c36f9ff23d7fa1918b03 +Subproject commit 553326b00696fcda106a8866872a8f2ad6caff0d From cfd2cdb9c4f1b5d6094a56de6be7789a96e2004b Mon Sep 17 00:00:00 2001 From: Andrew Plotkin Date: Wed, 30 Mar 2016 23:57:28 -0400 Subject: [PATCH 0346/1265] Added information about the enabled, visible, and checked properties -- when they can be set and what they mean. Also tidied up the grammar and clarified wording. --- docs/api/menu-item.md | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index af945e8aca4..fb12e251153 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -14,7 +14,7 @@ Create a new `MenuItem` with the following method: * `options` Object * `click` Function - Will be called with `click(menuItem, browserWindow)` when the menu item is clicked - * `role` String - Define the action of the menu item, when specified the + * `role` String - Define the action of the menu item; when specified the `click` property will be ignored * `type` String - Can be `normal`, `separator`, `submenu`, `checkbox` or `radio` @@ -22,21 +22,22 @@ Create a new `MenuItem` with the following method: * `sublabel` String * `accelerator` [Accelerator](accelerator.md) * `icon` [NativeImage](native-image.md) - * `enabled` Boolean - * `visible` Boolean - * `checked` Boolean - * `submenu` Menu - Should be specified for `submenu` type menu item, when - it's specified the `type: 'submenu'` can be omitted for the menu item. - If the value is not a `Menu` then it will be automatically converted to one - using `Menu.buildFromTemplate`. + * `enabled` Boolean - If false, the menu item will be greyed out and unclickable. + * `visible` Boolean - If false, the menu item will be entirely hidden. + * `checked` Boolean - Should only be specified for `checkbox` or `radio` type + menu items. + * `submenu` Menu - Should be specified for `submenu` type menu items. If + `submenu` is specified, the `type: 'submenu'` can be omitted. If the value + is not a `Menu` then it will be automatically converted to one using + `Menu.buildFromTemplate`. * `id` String - Unique within a single menu. If defined then it can be used as a reference to this item by the position attribute. * `position` String - This field allows fine-grained definition of the specific location within a given menu. -When creating menu items, it is recommended to specify `role` instead of -manually implementing the behavior if there is matching action, so menu can have -best native experience. +It is best to specify `role` for any menu item that matches a standard role, +rather than trying to manually implement the behavior in a `click` function. +The built-in `role` behavior will give the best native experience. The `role` property can have following values: @@ -59,3 +60,21 @@ On OS X `role` can also have following additional values: * `window` - The submenu is a "Window" menu * `help` - The submenu is a "Help" menu * `services` - The submenu is a "Services" menu + +## Instance Properties + +The following properties (and no others) can be updated on an existing `MenuItem`: + + * `enabled` Boolean + * `visible` Boolean + * `checked` Boolean + +Their meanings are as described above. + +A `checkbox` menu item will toggle its `checked` property on and off when +selected. You can add a `click` function to do additional work. + +A `radio` menu item will turn on its `checked` property when clicked, and +will turn off that property for all adjacent items in the same menu. Again, +you can add a `click` function for additional behavior. + From f7e5c65802248127faf779a80ed46e0b72494c92 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 31 Mar 2016 14:03:35 +0900 Subject: [PATCH 0347/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/app.md | 27 +++++++++++++++++++ docs-translations/ko-KR/api/auto-updater.md | 3 +++ docs-translations/ko-KR/api/browser-window.md | 10 +++++++ 3 files changed, 40 insertions(+) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 0924e284c31..ff4269ea829 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -366,6 +366,32 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 최근 문서 목록을 모두 비웁니다. +### `app.setAsDefaultProtocolClient(protocol)` _OS X_ _Windows_ + +* `protocol` String - 프로토콜의 이름, `://` 제외. 만약 앱을 통해 `electron://`과 + 같은 링크를 처리하고 싶다면, 이 메서드에 `electron` 인수를 담아 호출하면 됩니다. + +이 메서드는 지정한 프로토콜(URI scheme)에 대해 현재 실행파일을 기본 핸들러로 +등록합니다. 이를 통해 운영체제와 더 가깝게 통합할 수 있습니다. 한 번 등록되면, +`your-protocol://`과 같은 모든 링크에 대해 호출시 현재 실행 파일이 실행됩니다. +모든 링크, 프로토콜을 포함하여 어플리케이션의 인수로 전달됩니다. + +**참고:** OS X에선, 어플리케이션의 `info.plist`에 등록해둔 프로토콜만 사용할 수 +있습니다. 이는 런타임에서 변경될 수 없습니다. 이 파일은 간단히 텍스트 에디터를 +사용하거나, 어플리케이션을 빌드할 때 스크립트가 생성되도록 할 수 있습니다. 자세한 +내용은 [Apple의 참조 문서를][CFBundleURLTypes] 확인하세요. + +이 API는 내부적으로 Windows 레지스트리와 LSSetDefaultHandlerForURLScheme를 사용합니다. + +### `app.removeAsDefaultProtocolClient(protocol)` _Windows_ + +* `protocol` String - 프로토콜의 이름, `://` 제외. + +이 메서드는 현재 실행파일이 지정한 프로토콜(URI scheme)에 대해 기본 핸들러인지를 +확인합니다. 만약 그렇다면, 이 메서드는 앱을 기본 핸들러에서 제거합니다. + +**참고:** OS X에서는 앱을 제거하면 자동으로 기본 프로토콜 핸들러에서 제거됩니다. + ### `app.setUserTasks(tasks)` _Windows_ * `tasks` Array - `Task` 객체의 배열 @@ -556,3 +582,4 @@ dock 아이콘의 `image`를 설정합니다. [dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103 [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx +[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 diff --git a/docs-translations/ko-KR/api/auto-updater.md b/docs-translations/ko-KR/api/auto-updater.md index 04593ee5760..e5121d0f9b1 100644 --- a/docs-translations/ko-KR/api/auto-updater.md +++ b/docs-translations/ko-KR/api/auto-updater.md @@ -2,6 +2,9 @@ 이 모듈은 `Squirrel` 자동 업데이트 프레임워크의 인터페이스를 제공합니다. +[electron-release-server](https://github.com/ArekSredzki/electron-release-server)를 +포크하면 어플리케이션을 배포하기 위한 멀티 플랫폼 릴리즈 서버를 손쉽게 구축할 수 있습니다. + ## 플랫폼별 참고 사항 `autoUpdater`는 기본적으로 모든 플랫폼에 대해 같은 API를 제공하지만, 여전히 플랫폼별로 diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 1ebf7743c2f..06e31e9fba5 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -318,6 +318,16 @@ someWindow.on('app-command', function(e, cmd) { 스크롤 휠 이벤트가 동작을 멈췄을 때 발생하는 이벤트입니다. +### Event: 'swipe' _OS X_ + +Returns: + +* `event` Event +* `direction` String + +3-손가락 스와이프가 작동할 때 발생하는 이벤트입니다. 방향은 `up`, `right`, `down`, +`left`가 될 수 있습니다. + ## Methods `BrowserWindow` 객체는 다음과 같은 메서드를 가지고 있습니다: From 346ef9df0c202dba181ff7099053b09c8013b4e5 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 31 Mar 2016 14:16:14 +0900 Subject: [PATCH 0348/1265] :memo: Update docs styles * Adjust line length to `80` * Normalize whitespaces [ci skip] --- docs/api/app.md | 18 +++++++++--------- docs/api/auto-updater.md | 4 +++- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index 903668c7f2b..8a7cdace3ea 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -356,16 +356,16 @@ Clears the recent documents list. ### `app.setAsDefaultProtocolClient(protocol)` _OS X_ _Windows_ - * `protocol` String - The name of your protocol, without `://`. If you want your - app to handle `electron://` links, call this method with `electron` as the - parameter. - +* `protocol` String - The name of your protocol, without `://`. If you want your + app to handle `electron://` links, call this method with `electron` as the + parameter. + This method sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with `your-protocol://` will be openend with the current executable. The whole link, including protocol, will be passed to your application as a parameter. - + **Note:** On OS X, you can only register protocols that have been added to your app's `info.plist`, which can not be modified at runtime. You can however change the file with a simple text editor or script during build time. @@ -375,11 +375,11 @@ The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally ### `app.removeAsDefaultProtocolClient(protocol)` _Windows_ - * `protocol` String - The name of your protocol, without `://`. - +* `protocol` String - The name of your protocol, without `://`. + This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. - + **Note:** On OS X, removing the app will automatically remove the app as the default protocol handler. @@ -576,4 +576,4 @@ Sets the `image` associated with this dock icon. [dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103 [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx -[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 \ No newline at end of file +[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index f82520518c8..5987f1a215e 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -2,7 +2,8 @@ This module provides an interface for the `Squirrel` auto-updater framework. -You can quickly launch a multi-platform release server for distributing your application by forking [electron-release-server](https://github.com/ArekSredzki/electron-release-server). +You can quickly launch a multi-platform release server for distributing your +application by forking [electron-release-server][electron-release-server]. ## Platform notices @@ -101,3 +102,4 @@ should only be called after `update-downloaded` has been emitted. [squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows [installer]: https://github.com/atom/grunt-electron-installer [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx +[electron-release-server]: https://github.com/ArekSredzki/electron-release-server From a648528f43b1923e6a91753e5b0017b3c645c05d Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 31 Mar 2016 14:17:50 +0900 Subject: [PATCH 0349/1265] :memo: Normailze note markers * Normalize note markers syntax `__` to `**` [ci skip] --- docs/api/tray.md | 2 +- docs/development/setting-up-symbol-server.md | 2 +- docs/tutorial/debugging-main-process.md | 2 +- docs/tutorial/desktop-environment-integration.md | 2 +- docs/tutorial/mac-app-store-submission-guide.md | 4 ++-- docs/tutorial/using-widevine-cdm-plugin.md | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/api/tray.md b/docs/api/tray.md index 22ab9aea5b7..aa972c57cd9 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -75,7 +75,7 @@ labeled as such. Emitted when the tray icon is clicked. -__Note:__ The `bounds` payload is only implemented on OS X and Windows. +**Note:** The `bounds` payload is only implemented on OS X and Windows. ### Event: 'right-click' _OS X_ _Windows_ diff --git a/docs/development/setting-up-symbol-server.md b/docs/development/setting-up-symbol-server.md index 1dc31f7056d..073c752cbf4 100644 --- a/docs/development/setting-up-symbol-server.md +++ b/docs/development/setting-up-symbol-server.md @@ -25,7 +25,7 @@ appropriate cache directory on your machine. The Windbg symbol path is configured with a string value delimited with asterisk characters. To use only the Electron symbol server, add the following entry to -your symbol path (__Note:__ you can replace `c:\code\symbols` with any writable +your symbol path (**Note:** you can replace `c:\code\symbols` with any writable directory on your computer, if you'd prefer a different location for downloaded symbols): diff --git a/docs/tutorial/debugging-main-process.md b/docs/tutorial/debugging-main-process.md index 67f349d9f27..ee7fc4c5fa4 100644 --- a/docs/tutorial/debugging-main-process.md +++ b/docs/tutorial/debugging-main-process.md @@ -19,7 +19,7 @@ Like `--debug` but pauses the script on the first line. ## Use node-inspector for Debugging -__Note:__ Electron doesn't currently work very well +**Note:** Electron doesn't currently work very well with node-inspector, and the main process will crash if you inspect the `process` object under node-inspector's console. diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index 04e8066ef72..1186918799b 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -15,7 +15,7 @@ to the user. Electron conveniently allows developers to send notifications with the [HTML5 Notification API](https://notifications.spec.whatwg.org/), using the currently running operating system's native notification APIs to display it. -__Note:__ Since this is an HTML5 API it is only available in the renderer process. +**Note:** Since this is an HTML5 API it is only available in the renderer process. ```javascript var myNotification = new Notification('Title', { diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index e94a4310618..91a10d40eb1 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -4,11 +4,11 @@ Since v0.34.0, Electron allows submitting packaged apps to the Mac App Store (MAS). This guide provides information on: how to submit your app and the limitations of the MAS build. -__Note:__ From v0.36.0 there was a bug preventing GPU process to start after +**Note:** From v0.36.0 there was a bug preventing GPU process to start after the app being sandboxed, so it is recommended to use v0.35.x before this bug gets fixed. You can find more about this in [issue #3871][issue-3871]. -__Note:__ Submitting an app to Mac App Store requires enrolling [Apple Developer +**Note:** Submitting an app to Mac App Store requires enrolling [Apple Developer Program][developer-program], which costs money. ## How to Submit Your App diff --git a/docs/tutorial/using-widevine-cdm-plugin.md b/docs/tutorial/using-widevine-cdm-plugin.md index 630c18ab8e5..fa288bab0ff 100644 --- a/docs/tutorial/using-widevine-cdm-plugin.md +++ b/docs/tutorial/using-widevine-cdm-plugin.md @@ -8,7 +8,7 @@ Electron doesn't ship with the Widevine CDM plugin for license reasons, to get it, you need to install the official Chrome browser first, which should match the architecture and Chrome version of the Electron build you use. -__Note:__ The major version of Chrome browser has to be the same with the Chrome +**Note:** The major version of Chrome browser has to be the same with the Chrome version used by Electron, otherwise the plugin will not work even though `navigator.plugins` would show it has been loaded. @@ -41,7 +41,7 @@ After getting the plugin files, you should pass the `widevinecdmadapter`'s path to Electron with `--widevine-cdm-path` command line switch, and the plugin's version with `--widevine-cdm-version` switch. -__Note:__ Though only the `widevinecdmadapter` binary is passed to Electron, the +**Note:** Though only the `widevinecdmadapter` binary is passed to Electron, the `widevinecdm` binary has to be put aside it. The command line switches have to be passed before the `ready` event of `app` From 546ad643e4cefb9465b0ba41f1b998179d53fd58 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 31 Mar 2016 14:30:14 +0900 Subject: [PATCH 0350/1265] :memo: Add missing docs [ci skip] --- docs/api/ipc-renderer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/ipc-renderer.md b/docs/api/ipc-renderer.md index f17843702b5..46a2331af43 100644 --- a/docs/api/ipc-renderer.md +++ b/docs/api/ipc-renderer.md @@ -69,7 +69,7 @@ hence no functions or prototype chain will be included. The main process handles it by listening for `channel` with `ipcMain` module, and replies by setting `event.returnValue`. -__Note:__ Sending a synchronous message will block the whole renderer process, +**Note:** Sending a synchronous message will block the whole renderer process, unless you know what you are doing you should never use it. ### `ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...])` From d4a14bc215340c1a82c405d30ba643cba028e452 Mon Sep 17 00:00:00 2001 From: James Wheare Date: Thu, 31 Mar 2016 08:56:49 +0100 Subject: [PATCH 0351/1265] Improve app-command docs, list arguments and explain command string --- docs/api/browser-window.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 76343f967b1..e42b2d9bd09 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -301,10 +301,18 @@ Emitted when the window leaves full screen state triggered by html api. ### Event: 'app-command' _Windows_ +Returns: + +* `event` Event +* `command` String + Emitted when an [App Command](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. +Commands are lowercased with underscores replaced with hyphens and the `APPCOMMAND_` prefix stripped off. +e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. + ```js someWindow.on('app-command', function(e, cmd) { // Navigate the window back when the user hits their mouse back button From e23faceba05db7dfa82c06d8ee6185ca779d88c9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 31 Mar 2016 17:22:09 +0900 Subject: [PATCH 0352/1265] docs: Add notes on app.getLocale --- docs/api/app.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/api/app.md b/docs/api/app.md index 903668c7f2b..5df9e83b27a 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -341,6 +341,11 @@ Overrides the current application's name. Returns the current application locale. +**Note:** When distributing your packaged app, you have to also ship the +`locales` folder. + +**Note:** On Windows you have to call it after the `ready` events gets emitted. + ### `app.addRecentDocument(path)` _OS X_ _Windows_ * `path` String @@ -576,4 +581,4 @@ Sets the `image` associated with this dock icon. [dock-menu]:https://developer.apple.com/library/mac/documentation/Carbon/Conceptual/customizing_docktile/concepts/dockconcepts.html#//apple_ref/doc/uid/TP30000986-CH2-TPXREF103 [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx -[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 \ No newline at end of file +[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 From 6e467534997704b3167e61ff874e4d81b3ee5dc2 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Thu, 31 Mar 2016 10:12:03 -0400 Subject: [PATCH 0353/1265] Don't emit 'will-quit' when 'app.exit()' is called. Fixes #4643 --- atom/browser/browser.cc | 10 ++++++++-- atom/browser/browser.h | 5 ++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index e89f52283b3..b60df0dd44a 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -15,6 +15,7 @@ namespace atom { Browser::Browser() : is_quiting_(false), + is_exiting_(false), is_ready_(false), is_shutdown_(false) { WindowList::AddObserver(this); @@ -49,9 +50,12 @@ void Browser::Exit(int code) { // Message loop is not ready, quit directly. exit(code); } else { - // Prepare to quit when all windows have been closed.. + // Prepare to quit when all windows have been closed. is_quiting_ = true; + // Remember this caller so that we don't emit unrelated events. + is_exiting_ = true; + // Must destroy windows before quitting, otherwise bad things can happen. atom::WindowList* window_list = atom::WindowList::GetInstance(); if (window_list->size() == 0) { @@ -175,7 +179,9 @@ void Browser::OnWindowCloseCancelled(NativeWindow* window) { } void Browser::OnWindowAllClosed() { - if (is_quiting_) + if (is_exiting_) + Shutdown(); + else if (is_quiting_) NotifyAndShutdown(); else FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed()); diff --git a/atom/browser/browser.h b/atom/browser/browser.h index d976fae675c..bb65f5f0509 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -183,10 +183,13 @@ class Browser : public WindowListObserver { // Observers of the browser. base::ObserverList observers_; + // Whether `app.exit()` has been called + bool is_exiting_; + // Whether "ready" event has been emitted. bool is_ready_; - // The browse is being shutdown. + // The browser is being shutdown. bool is_shutdown_; std::string version_override_; From daa09ea9e7d4f8c4a7f52ceaa7eb63f6aaeb2279 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 11:10:43 -0700 Subject: [PATCH 0354/1265] Remove path for nodeIntgration value of 'disable' --- atom/browser/web_contents_preferences.cc | 5 ----- 1 file changed, 5 deletions(-) diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 3939c59b8cd..bcdbd736676 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -97,11 +97,6 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // Check if we have node integration specified. bool node_integration = true; web_preferences.GetBoolean(options::kNodeIntegration, &node_integration); - // Be compatible with old API of "node-integration" option. - std::string old_token; - if (web_preferences.GetString(options::kNodeIntegration, &old_token) && - old_token != "disable") - node_integration = true; command_line->AppendSwitchASCII(switches::kNodeIntegration, node_integration ? "true" : "false"); From f033f259b4dda91679be0221933a49c011db1f50 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 08:26:11 -0700 Subject: [PATCH 0355/1265] Only check for nodeIntegration being true --- lib/renderer/init.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 45ea2d45654..128963a63cb 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -84,7 +84,7 @@ if (location.protocol === 'chrome-devtools:') { } } -if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration === 'except-iframe' || nodeIntegration === 'manual-enable-iframe') { +if (nodeIntegration === 'true') { // Export node bindings to global. global.require = require; global.module = module; From ae5a6e61c503c0d68715096fff401b07ee4b9447 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Thu, 31 Mar 2016 09:54:01 -0700 Subject: [PATCH 0356/1265] :memo: Add "remote" note to dialog docs Ref #4943 --- docs/api/dialog.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 84a22ef692b..9fbc20dd830 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -12,6 +12,12 @@ const dialog = require('electron').dialog; console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]})); ``` +The Dialog is opened from Electron's main thread. If you want to use the dialog object from a renderer process, remember to access it using the remote: + +```javascript +const dialog = require('electron').remote.dialog; +``` + **Note for OS X**: If you want to present dialogs as sheets, the only thing you have to do is provide a `BrowserWindow` reference in the `browserWindow` parameter. From 7016fbe258cd4b94b64b4ca3a023632f4e08a865 Mon Sep 17 00:00:00 2001 From: Robo Date: Fri, 25 Mar 2016 08:47:33 +0530 Subject: [PATCH 0357/1265] browser: fix disposition value for new-window event --- atom/browser/api/atom_api_web_contents.cc | 6 ++++-- lib/browser/api/browser-window.js | 4 ++-- lib/browser/guest-window-manager.js | 4 ++-- lib/renderer/override.js | 3 ++- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index db561708086..bd48cac0157 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -326,10 +326,12 @@ bool WebContents::ShouldCreateWebContents( const GURL& target_url, const std::string& partition_id, content::SessionStorageNamespace* session_storage_namespace) { + auto disposition = (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) + ? "background-tab" : "new-window"; if (type_ == BROWSER_WINDOW) - Emit("-new-window", target_url, frame_name, NEW_FOREGROUND_TAB); + Emit("-new-window", target_url, frame_name, disposition); else - Emit("new-window", target_url, frame_name, NEW_FOREGROUND_TAB); + Emit("new-window", target_url, frame_name, disposition); return false; } diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 7bbf898dafb..33aea5da4d0 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -21,14 +21,14 @@ BrowserWindow.prototype._init = function () { } // Make new windows requested by links behave like "window.open" - this.webContents.on('-new-window', (event, url, frameName) => { + this.webContents.on('-new-window', (event, url, frameName, disposition) => { var options options = { show: true, width: 800, height: 600 } - return ipcMain.emit('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, options) + return ipcMain.emit('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, disposition, options) }) // window.resizeTo(...) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index bc88337eb06..0426ea51583 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -80,9 +80,9 @@ var createGuest = function (embedder, url, frameName, options) { } // Routed window.open messages. -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, frameName, options) { +ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, frameName, disposition, options) { options = mergeBrowserWindowOptions(event.sender, options) - event.sender.emit('new-window', event, url, frameName, 'new-window', options) + event.sender.emit('new-window', event, url, frameName, disposition, options) if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { event.returnValue = null } else { diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 07f02566bcc..20c993d0bc5 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -100,6 +100,7 @@ window.open = function (url, frameName, features) { // TODO remove hyphenated options in both of the following arrays for 1.0 const ints = ['x', 'y', 'width', 'height', 'min-width', 'minWidth', 'max-width', 'maxWidth', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor'] const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload'] + const disposition = 'new-window' // Make sure to get rid of excessive whitespace in the property name ref1 = features.split(/,\s*/) @@ -146,7 +147,7 @@ window.open = function (url, frameName, features) { options[name] = parseInt(options[name], 10) } } - guestId = ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, options) + guestId = ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, disposition, options) if (guestId) { return BrowserWindowProxy.getOrCreate(guestId) } else { From e0fe478ae701c09b0124ff39c525f34b92d6446f Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 31 Mar 2016 06:28:23 +0530 Subject: [PATCH 0358/1265] decide early on render initiated window creations --- atom/browser/api/atom_api_app.cc | 48 +++++++++++++++++++++++ atom/browser/api/atom_api_app.h | 21 ++++++++++ atom/browser/api/atom_api_web_contents.cc | 16 ++------ atom/browser/api/atom_api_web_contents.h | 15 +++---- atom/browser/atom_browser_client.cc | 39 ++++++++++++++++++ atom/browser/atom_browser_client.h | 16 ++++++++ 6 files changed, 132 insertions(+), 23 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index ad5b7214ccd..03f2437edd5 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -27,6 +27,7 @@ #include "base/path_service.h" #include "brightray/browser/brightray_paths.h" #include "chrome/common/chrome_paths.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_frame_host.h" @@ -275,6 +276,53 @@ void App::SelectClientCertificate( cert_request_info->client_certs[0].get()); } +bool App::CanCreateWindow(const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const std::string& frame_name, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_render_view_id, + int opener_render_frame_id, + bool* no_javascript_access) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, + base::Bind(&App::OnCreateWindow, + base::Unretained(this), + target_url, + frame_name, + disposition, + render_process_id, + opener_render_frame_id)); + + return false; +} + +void App::OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition, + int render_process_id, + int render_frame_id) { + v8::Locker locker(isolate()); + v8::HandleScope handle_scope(isolate()); + content::RenderFrameHost* rfh = + content::RenderFrameHost::FromID(render_process_id, render_frame_id); + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + if (web_contents) { + auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents); + api_web_contents->CreateWindow(target_url, frame_name, disposition); + } +} + void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) { Emit("gpu-process-crashed"); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 5faf8ebb10e..3cf442c9e6e 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -66,6 +66,22 @@ class App : public AtomBrowserClient::Delegate, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, scoped_ptr delegate) override; + bool CanCreateWindow(const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const std::string& frame_name, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_render_view_id, + int opener_render_frame_id, + bool* no_javascript_access) override; // content::GpuDataManagerObserver: void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; @@ -90,6 +106,11 @@ class App : public AtomBrowserClient::Delegate, bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); std::string GetLocale(); + void OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition, + int render_process_id, + int render_frame_id); #if defined(OS_WIN) bool IsAeroGlassEnabled(); diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index bd48cac0157..115926c8a93 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -316,23 +316,13 @@ bool WebContents::AddMessageToConsole(content::WebContents* source, } } -bool WebContents::ShouldCreateWebContents( - content::WebContents* web_contents, - int32_t route_id, - int32_t main_frame_route_id, - int32_t main_frame_widget_route_id, - WindowContainerType window_container_type, - const std::string& frame_name, - const GURL& target_url, - const std::string& partition_id, - content::SessionStorageNamespace* session_storage_namespace) { - auto disposition = (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) - ? "background-tab" : "new-window"; +void WebContents::CreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition) { if (type_ == BROWSER_WINDOW) Emit("-new-window", target_url, frame_name, disposition); else Emit("new-window", target_url, frame_name, disposition); - return false; } content::WebContents* WebContents::OpenURLFromTab( diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index b734dc304df..d305172c33d 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -138,6 +138,11 @@ class WebContents : public mate::TrackableObject, const GURL& origin, bool allowed); + // Create window with the given disposition. + void CreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition); + // Returns the web preferences of current WebContents. v8::Local GetWebPreferences(v8::Isolate* isolate); @@ -165,16 +170,6 @@ class WebContents : public mate::TrackableObject, const base::string16& message, int32_t line_no, const base::string16& source_id) override; - bool ShouldCreateWebContents( - content::WebContents* web_contents, - int32_t route_id, - int32_t main_frame_route_id, - int32_t main_frame_widget_route_id, - WindowContainerType window_container_type, - const std::string& frame_name, - const GURL& target_url, - const std::string& partition_id, - content::SessionStorageNamespace* session_storage_namespace) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index 63a1ea46b16..ec58777d9c9 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -264,6 +264,45 @@ void AtomBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.get()); } +bool AtomBrowserClient::CanCreateWindow( + const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const std::string& frame_name, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_render_view_id, + int opener_render_frame_id, + bool* no_javascript_access) { + if (delegate_) { + return delegate_->CanCreateWindow(opener_url, + opener_top_level_frame_url, + source_origin, + container_type, + frame_name, + target_url, + referrer, + disposition, + features, + user_gesture, + opener_suppressed, + context, + render_process_id, + opener_render_view_id, + opener_render_frame_id, + no_javascript_access); + } else { + return false; + } +} + brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { v8::V8::Initialize(); // Init V8 before creating main parts. diff --git a/atom/browser/atom_browser_client.h b/atom/browser/atom_browser_client.h index 8f62887ff68..5354e14cc61 100644 --- a/atom/browser/atom_browser_client.h +++ b/atom/browser/atom_browser_client.h @@ -76,6 +76,22 @@ class AtomBrowserClient : public brightray::BrowserClient, net::SSLCertRequestInfo* cert_request_info, scoped_ptr delegate) override; void ResourceDispatcherHostCreated() override; + bool CanCreateWindow(const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const std::string& frame_name, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_render_view_id, + int opener_render_frame_id, + bool* no_javascript_access) override; // brightray::BrowserClient: brightray::BrowserMainParts* OverrideCreateBrowserMainParts( From 7e366dd5c8efa75efc29e383f5c6dc726a399ae5 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 31 Mar 2016 18:37:47 +0530 Subject: [PATCH 0359/1265] Update libchromiumcontent --- script/lib/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/lib/config.py b/script/lib/config.py index fb1a4b89f27..83960e68e2c 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'b06d4c307b861cdb091f4ba26b1a185333889033' +LIBCHROMIUMCONTENT_COMMIT = 'd41c1e48f428257d99abcf29fd9f26928e9fc53e' PLATFORM = { 'cygwin': 'win32', From e14c91771becf66c5598f108f9f1c3851235a977 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 31 Mar 2016 19:51:18 +0530 Subject: [PATCH 0360/1265] removed redundant delegation --- atom/browser/api/atom_api_app.cc | 65 ++++++++--------------------- atom/browser/api/atom_api_app.h | 28 ++++--------- atom/browser/atom_browser_client.cc | 31 ++++++-------- 3 files changed, 37 insertions(+), 87 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 03f2437edd5..de1272e03e8 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -27,7 +27,6 @@ #include "base/path_service.h" #include "brightray/browser/brightray_paths.h" #include "chrome/common/chrome_paths.h" -#include "content/public/browser/browser_thread.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_frame_host.h" @@ -230,6 +229,23 @@ void App::OnLogin(LoginHandler* login_handler) { login_handler->CancelAuth(); } +void App::OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition, + int render_process_id, + int render_frame_id) { + v8::Locker locker(isolate()); + v8::HandleScope handle_scope(isolate()); + content::RenderFrameHost* rfh = + content::RenderFrameHost::FromID(render_process_id, render_frame_id); + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + if (web_contents) { + auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents); + api_web_contents->CreateWindow(target_url, frame_name, disposition); + } +} + void App::AllowCertificateError( content::WebContents* web_contents, int cert_error, @@ -276,53 +292,6 @@ void App::SelectClientCertificate( cert_request_info->client_certs[0].get()); } -bool App::CanCreateWindow(const GURL& opener_url, - const GURL& opener_top_level_frame_url, - const GURL& source_origin, - WindowContainerType container_type, - const std::string& frame_name, - const GURL& target_url, - const content::Referrer& referrer, - WindowOpenDisposition disposition, - const blink::WebWindowFeatures& features, - bool user_gesture, - bool opener_suppressed, - content::ResourceContext* context, - int render_process_id, - int opener_render_view_id, - int opener_render_frame_id, - bool* no_javascript_access) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - - content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, - base::Bind(&App::OnCreateWindow, - base::Unretained(this), - target_url, - frame_name, - disposition, - render_process_id, - opener_render_frame_id)); - - return false; -} - -void App::OnCreateWindow(const GURL& target_url, - const std::string& frame_name, - WindowOpenDisposition disposition, - int render_process_id, - int render_frame_id) { - v8::Locker locker(isolate()); - v8::HandleScope handle_scope(isolate()); - content::RenderFrameHost* rfh = - content::RenderFrameHost::FromID(render_process_id, render_frame_id); - content::WebContents* web_contents = - content::WebContents::FromRenderFrameHost(rfh); - if (web_contents) { - auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents); - api_web_contents->CreateWindow(target_url, frame_name, disposition); - } -} - void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) { Emit("gpu-process-crashed"); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 3cf442c9e6e..5025a3869dd 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -34,6 +34,13 @@ class App : public AtomBrowserClient::Delegate, public: static mate::Handle Create(v8::Isolate* isolate); + // Called when window with disposition needs to be created. + void OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition, + int render_process_id, + int render_frame_id); + protected: App(); virtual ~App(); @@ -66,22 +73,6 @@ class App : public AtomBrowserClient::Delegate, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, scoped_ptr delegate) override; - bool CanCreateWindow(const GURL& opener_url, - const GURL& opener_top_level_frame_url, - const GURL& source_origin, - WindowContainerType container_type, - const std::string& frame_name, - const GURL& target_url, - const content::Referrer& referrer, - WindowOpenDisposition disposition, - const blink::WebWindowFeatures& features, - bool user_gesture, - bool opener_suppressed, - content::ResourceContext* context, - int render_process_id, - int opener_render_view_id, - int opener_render_frame_id, - bool* no_javascript_access) override; // content::GpuDataManagerObserver: void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; @@ -106,11 +97,6 @@ class App : public AtomBrowserClient::Delegate, bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); std::string GetLocale(); - void OnCreateWindow(const GURL& target_url, - const std::string& frame_name, - WindowOpenDisposition disposition, - int render_process_id, - int render_frame_id); #if defined(OS_WIN) bool IsAeroGlassEnabled(); diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index ec58777d9c9..9a59c3f9d41 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -8,6 +8,7 @@ #include #endif +#include "atom/browser/api/atom_api_app.h" #include "atom/browser/atom_access_token_store.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" @@ -281,26 +282,20 @@ bool AtomBrowserClient::CanCreateWindow( int opener_render_view_id, int opener_render_frame_id, bool* no_javascript_access) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + if (delegate_) { - return delegate_->CanCreateWindow(opener_url, - opener_top_level_frame_url, - source_origin, - container_type, - frame_name, - target_url, - referrer, - disposition, - features, - user_gesture, - opener_suppressed, - context, - render_process_id, - opener_render_view_id, - opener_render_frame_id, - no_javascript_access); - } else { - return false; + content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, + base::Bind(&api::App::OnCreateWindow, + base::Unretained(static_cast(delegate_)), + target_url, + frame_name, + disposition, + render_process_id, + opener_render_frame_id)); } + + return false; } brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( From f36851fcffc5cf2e0415f618961ec2e740a830bc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 14:50:33 +0900 Subject: [PATCH 0361/1265] spec: Remote object should be referenced by its members --- spec/api-ipc-spec.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index be4f788fb0d..da4acf887e4 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -73,6 +73,12 @@ describe('ipc module', function () { assert.equal(delete remoteFunctions.aFunction, true) }) + + it('is referenced by its members', function () { + let stringify = remote.getGlobal('JSON').stringify + gc(); + stringify({}) + }); }) describe('remote value in browser', function () { From 4ebb01f8c9642103276d7e88bb81fcabc0a656f8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 15:26:30 +0900 Subject: [PATCH 0362/1265] Remote object's members should reference itself --- lib/renderer/api/remote.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 5f60a970ff3..30341c0f77b 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -109,9 +109,16 @@ let setObjectMembers = function (object, metaId, members) { return metaToValue(ret) } } - descriptor.writable = true + descriptor.get = function () { + remoteMemberFunction.ref = object // The member should reference its object. + return remoteMemberFunction + } + // Enable monkey-patch the method + descriptor.set = function (value) { + remoteMemberFunction = value + return value + } descriptor.configurable = true - descriptor.value = remoteMemberFunction } else if (member.type === 'get') { descriptor.get = function () { return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, member.name)) From b9ead472a55719c3e6fd295df9b165450c44642d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 15:35:34 +0900 Subject: [PATCH 0363/1265] spec: Remote object should be referenced by methods in its prototype chain --- spec/api-ipc-spec.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index da4acf887e4..c98689287ce 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -149,6 +149,13 @@ describe('ipc module', function () { assert(!proto.hasOwnProperty('method')) assert(Object.getPrototypeOf(proto).hasOwnProperty('method')) }) + + it('is referenced by methods in prototype chain', function () { + let method = derived.method + derived = null + gc() + assert.equal(method(), 'method') + }); }) describe('ipc.sender.send', function () { From 39d2b95a33c72321bd5418030daa9392366df527 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 15:45:36 +0900 Subject: [PATCH 0364/1265] Reference the remote object in its prototype chain's methods --- lib/renderer/api/remote.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 30341c0f77b..30b66983a7d 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -91,8 +91,9 @@ var wrapArgs = function (args, visited) { } // Populate object's members from descriptors. +// The |ref| will be kept referenced by |members|. // This matches |getObjectMemebers| in rpc-server. -let setObjectMembers = function (object, metaId, members) { +let setObjectMembers = function (ref, object, metaId, members) { for (let member of members) { if (object.hasOwnProperty(member.name)) continue @@ -110,7 +111,7 @@ let setObjectMembers = function (object, metaId, members) { } } descriptor.get = function () { - remoteMemberFunction.ref = object // The member should reference its object. + remoteMemberFunction.ref = ref // The member should reference its object. return remoteMemberFunction } // Enable monkey-patch the method @@ -139,11 +140,11 @@ let setObjectMembers = function (object, metaId, members) { // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. -let setObjectPrototype = function (object, metaId, descriptor) { +let setObjectPrototype = function (ref, object, metaId, descriptor) { if (descriptor === null) return let proto = {} - setObjectMembers(proto, metaId, descriptor.members) - setObjectPrototype(proto, metaId, descriptor.proto) + setObjectMembers(ref, proto, metaId, descriptor.members) + setObjectPrototype(ref, proto, metaId, descriptor.proto) Object.setPrototypeOf(object, proto) } @@ -198,9 +199,9 @@ let metaToValue = function (meta) { } // Populate delegate members. - setObjectMembers(ret, meta.id, meta.members) + setObjectMembers(ret, ret, meta.id, meta.members) // Populate delegate prototype. - setObjectPrototype(ret, meta.id, meta.proto) + setObjectPrototype(ret, ret, meta.id, meta.proto) // Set constructor.name to object's name. Object.defineProperty(ret.constructor, 'name', { value: meta.name }) From 576b54320a1baa202f8d0f448dd7e18ecd216144 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 16:34:20 +0900 Subject: [PATCH 0365/1265] Fix compilation errors on Windows --- atom/browser/api/atom_api_app.cc | 2 +- atom/browser/api/atom_api_web_contents.cc | 6 +++--- atom/browser/api/atom_api_web_contents.h | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index de1272e03e8..52d6ec3d338 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -242,7 +242,7 @@ void App::OnCreateWindow(const GURL& target_url, content::WebContents::FromRenderFrameHost(rfh); if (web_contents) { auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents); - api_web_contents->CreateWindow(target_url, frame_name, disposition); + api_web_contents->OnCreateWindow(target_url, frame_name, disposition); } } diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 115926c8a93..8c0f7d571f3 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -316,9 +316,9 @@ bool WebContents::AddMessageToConsole(content::WebContents* source, } } -void WebContents::CreateWindow(const GURL& target_url, - const std::string& frame_name, - WindowOpenDisposition disposition) { +void WebContents::OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition) { if (type_ == BROWSER_WINDOW) Emit("-new-window", target_url, frame_name, disposition); else diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index d305172c33d..5fb1947f579 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -139,9 +139,9 @@ class WebContents : public mate::TrackableObject, bool allowed); // Create window with the given disposition. - void CreateWindow(const GURL& target_url, - const std::string& frame_name, - WindowOpenDisposition disposition); + void OnCreateWindow(const GURL& target_url, + const std::string& frame_name, + WindowOpenDisposition disposition); // Returns the web preferences of current WebContents. v8::Local GetWebPreferences(v8::Isolate* isolate); From 247b3f36057ed3465bac646b607a5205ce94914f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 16:35:19 +0900 Subject: [PATCH 0366/1265] Fix the background color in test app --- spec/static/index.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spec/static/index.html b/spec/static/index.html index e31fcffebb8..3c57f94d144 100644 --- a/spec/static/index.html +++ b/spec/static/index.html @@ -3,6 +3,11 @@ + From b35f4c1805db66f5add4fb6a35bf90285cf80a2f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 1 Apr 2016 16:42:44 +0900 Subject: [PATCH 0367/1265] spec: Fix failing test due to path delimiter --- spec/chromium-spec.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index b6e9a775ed0..27660156e32 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -199,7 +199,10 @@ describe('chromium feature', function () { it('defines a window.location getter', function (done) { var b, targetURL - targetURL = 'file://' + fixtures + '/pages/base-page.html' + if (process.platform == 'win32') + targetURL = 'file:///' + fixtures.replace(/\\/g, '/') + '/pages/base-page.html' + else + targetURL = 'file://' + fixtures + '/pages/base-page.html' b = window.open(targetURL) BrowserWindow.fromId(b.guestId).webContents.once('did-finish-load', function () { assert.equal(b.location, targetURL) From ff7bb1e6cb5a5e9260d83d91ca8c9972836b5b4f Mon Sep 17 00:00:00 2001 From: Alexandru Rosianu Date: Fri, 1 Apr 2016 14:28:52 +0300 Subject: [PATCH 0368/1265] Add squirrel-updates-server link in the docs Add link to Aluxian/squirrel-updates-server in the docs page for autoUpdater --- docs/api/auto-updater.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 5987f1a215e..58584d73800 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -3,7 +3,10 @@ This module provides an interface for the `Squirrel` auto-updater framework. You can quickly launch a multi-platform release server for distributing your -application by forking [electron-release-server][electron-release-server]. +application by using one of these projects: + +- [electron-release-server][electron-release-server]: *A fully featured, self-hosted release server for electron applications, compatible with auto-updater* +- [squirrel-updates-server][squirrel-updates-server]: *A simple node.js server for Squirrel.Mac and Squirrel.Windows which uses GitHub releases* ## Platform notices @@ -103,3 +106,4 @@ should only be called after `update-downloaded` has been emitted. [installer]: https://github.com/atom/grunt-electron-installer [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-release-server]: https://github.com/ArekSredzki/electron-release-server +[squirrel-updates-server]: https://github.com/Aluxian/squirrel-updates-server From 464dad31354cb633c77f085bf0ebb7910eaa11bf Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 11:50:17 -0700 Subject: [PATCH 0369/1265] Store default_app in .asar archive --- atom.gyp | 51 +++++++++++++++++++++++++++++---------------- filenames.gypi | 6 ++++++ lib/browser/init.js | 2 +- tools/js2asar.py | 18 ++++++++-------- 4 files changed, 49 insertions(+), 28 deletions(-) diff --git a/atom.gyp b/atom.gyp index bfcfb39bab1..501cc3ab777 100644 --- a/atom.gyp +++ b/atom.gyp @@ -29,6 +29,7 @@ 'type': 'executable', 'dependencies': [ 'js2asar', + 'app2asar', '<(project_name)_lib', ], 'sources': [ @@ -66,12 +67,6 @@ '<(PRODUCT_DIR)/<(product_name) Framework.framework', ], }, - { - 'destination': '<(PRODUCT_DIR)/<(product_name).app/Contents/Resources', - 'files': [ - 'default_app', - ], - }, ], 'postbuilds': [ { @@ -167,12 +162,6 @@ 'external_binaries/vccorlib120.dll', ], }, - { - 'destination': '<(PRODUCT_DIR)/resources', - 'files': [ - 'default_app', - ] - }, ], }, { 'dependencies': [ @@ -208,12 +197,6 @@ '<(libchromiumcontent_dir)/snapshot_blob.bin', ], }, - { - 'destination': '<(PRODUCT_DIR)/resources', - 'files': [ - 'default_app', - ] - }, ], }], # OS=="linux" ], @@ -376,11 +359,43 @@ 'python', 'tools/js2asar.py', '<@(_outputs)', + 'lib', '<@(_inputs)', ], } ], }, # target js2asar + { + 'target_name': 'app2asar', + 'type': 'none', + 'actions': [ + { + 'action_name': 'app2asar', + 'variables': { + 'conditions': [ + ['OS=="mac"', { + 'resources_path': '<(PRODUCT_DIR)/<(product_name).app/Contents/Resources', + },{ + 'resources_path': '<(PRODUCT_DIR)/resources', + }], + ], + }, + 'inputs': [ + '<@(default_app_sources)', + ], + 'outputs': [ + '<(resources_path)/default_app.asar', + ], + 'action': [ + 'python', + 'tools/js2asar.py', + '<@(_outputs)', + 'default_app', + '<@(_inputs)', + ], + } + ], + }, # target app2asar { 'target_name': 'atom_js2c', 'type': 'none', diff --git a/filenames.gypi b/filenames.gypi index baf0202f3ec..97c2c0e6c52 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -67,6 +67,12 @@ 'lib/common/asar.js', 'lib/common/asar_init.js', ], + 'default_app_sources': [ + 'default_app/default_app.js', + 'default_app/index.html', + 'default_app/main.js', + 'default_app/package.json', + ], 'lib_sources': [ 'atom/app/atom_content_client.cc', 'atom/app/atom_content_client.h', diff --git a/lib/browser/init.js b/lib/browser/init.js index d04b174adb6..fc4f90c399b 100644 --- a/lib/browser/init.js +++ b/lib/browser/init.js @@ -117,7 +117,7 @@ require('./guest-window-manager') // Now we try to load app's package.json. var packageJson = null -var searchPaths = ['app', 'app.asar', 'default_app'] +var searchPaths = ['app', 'app.asar', 'default_app.asar'] var i, len, packagePath for (i = 0, len = searchPaths.length; i < len; i++) { packagePath = searchPaths[i] diff --git a/tools/js2asar.py b/tools/js2asar.py index cb02e33de65..fe33edbba74 100755 --- a/tools/js2asar.py +++ b/tools/js2asar.py @@ -12,26 +12,26 @@ SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__)) def main(): archive = sys.argv[1] - js_source_files = sys.argv[2:] + folder_name = sys.argv[2] + source_files = sys.argv[3:] output_dir = tempfile.mkdtemp() - copy_js(js_source_files, output_dir) - call_asar(archive, output_dir) + copy_files(source_files, output_dir) + call_asar(archive, os.path.join(output_dir, folder_name)) shutil.rmtree(output_dir) -def copy_js(js_source_files, output_dir): - for source_file in js_source_files: - output_filename = os.path.splitext(source_file)[0] + '.js' - output_path = os.path.join(output_dir, output_filename) +def copy_files(source_files, output_dir): + for source_file in source_files: + output_path = os.path.join(output_dir, source_file) safe_mkdir(os.path.dirname(output_path)) shutil.copy2(source_file, output_path) def call_asar(archive, output_dir): - js_dir = os.path.join(output_dir, 'lib') + print(output_dir) asar = os.path.join(SOURCE_ROOT, 'node_modules', 'asar', 'bin', 'asar') - subprocess.check_call([find_node(), asar, 'pack', js_dir, archive]) + subprocess.check_call([find_node(), asar, 'pack', output_dir, archive]) def find_node(): From 5221154653eaee8f0ff573dcb502235af3b02455 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 11:53:14 -0700 Subject: [PATCH 0370/1265] Remove logging --- tools/js2asar.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/js2asar.py b/tools/js2asar.py index fe33edbba74..7860176c93c 100755 --- a/tools/js2asar.py +++ b/tools/js2asar.py @@ -29,7 +29,6 @@ def copy_files(source_files, output_dir): def call_asar(archive, output_dir): - print(output_dir) asar = os.path.join(SOURCE_ROOT, 'node_modules', 'asar', 'bin', 'asar') subprocess.check_call([find_node(), asar, 'pack', output_dir, archive]) From 400efa1b7dc6f44ce8252d1603ca8a9405454269 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 09:07:56 -0700 Subject: [PATCH 0371/1265] Fallback to using the last argument as the callback --- lib/browser/api/dialog.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/browser/api/dialog.js b/lib/browser/api/dialog.js index 378822c6fb3..6669d8cab89 100644 --- a/lib/browser/api/dialog.js +++ b/lib/browser/api/dialog.js @@ -20,18 +20,25 @@ var messageBoxOptions = { noLink: 1 << 0 } -var parseArgs = function (window, options, callback) { +var parseArgs = function (window, options, callback, ...args) { if (!(window === null || (window != null ? window.constructor : void 0) === BrowserWindow)) { // Shift. callback = options options = window window = null } + if ((callback == null) && typeof options === 'function') { // Shift. callback = options options = null } + + // Fallback to using very last argument as the callback function + if ((callback == null) && typeof args[args.length - 1] === 'function') { + callback = args[args.length - 1] + } + return [window, options, callback] } From ac419038c62a830211744341ed969b3477aff60c Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 1 Apr 2016 14:09:01 -0700 Subject: [PATCH 0372/1265] use example accelerators that align with best practices --- docs/api/accelerator.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/accelerator.md b/docs/api/accelerator.md index 93d1f244c6b..0bb073c21c1 100644 --- a/docs/api/accelerator.md +++ b/docs/api/accelerator.md @@ -5,8 +5,8 @@ multiple modifiers and key codes, combined by the `+` character. Examples: -* `Command+A` -* `Ctrl+Shift+Z` +* `CommandOrControl+A` +* `CommandOrControl+Shift+Z` ## Platform notice From b92e86301af7abed4f090b82c760455113529ad4 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 1 Apr 2016 14:54:25 -0700 Subject: [PATCH 0373/1265] use cross-platform accelerator in globalShorcut documentation --- docs/api/global-shortcut.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/api/global-shortcut.md b/docs/api/global-shortcut.md index 1ec0503bd9d..f20758406b7 100644 --- a/docs/api/global-shortcut.md +++ b/docs/api/global-shortcut.md @@ -14,9 +14,9 @@ const app = electron.app; const globalShortcut = electron.globalShortcut; app.on('ready', function() { - // Register a 'ctrl+x' shortcut listener. - var ret = globalShortcut.register('ctrl+x', function() { - console.log('ctrl+x is pressed'); + // Register a 'CommandOrControl+X' shortcut listener. + var ret = globalShortcut.register('CommandOrControl+X', function() { + console.log('CommandOrControl+X is pressed'); }); if (!ret) { @@ -24,12 +24,12 @@ app.on('ready', function() { } // Check whether a shortcut is registered. - console.log(globalShortcut.isRegistered('ctrl+x')); + console.log(globalShortcut.isRegistered('CommandOrControl+X')); }); app.on('will-quit', function() { // Unregister a shortcut. - globalShortcut.unregister('ctrl+x'); + globalShortcut.unregister('CommandOrControl+X'); // Unregister all shortcuts. globalShortcut.unregisterAll(); From 2853356b10f0d6946c330eabe5cf26e4be04113e Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 1 Apr 2016 15:48:12 -0700 Subject: [PATCH 0374/1265] use alt, not option --- docs/api/accelerator.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/api/accelerator.md b/docs/api/accelerator.md index 93d1f244c6b..f952d0b1ba8 100644 --- a/docs/api/accelerator.md +++ b/docs/api/accelerator.md @@ -14,6 +14,9 @@ On Linux and Windows, the `Command` key does not have any effect so use `CommandOrControl` which represents `Command` on OS X and `Control` on Linux and Windows to define some accelerators. +Use `Alt` instead of `Option`. The `Option` key only exists on OS X, whereas +the `Alt` key is available on all platforms. + The `Super` key is mapped to the `Windows` key on Windows and Linux and `Cmd` on OS X. From c036986cc49c5dc79b3651881ffc1f53eeff09e6 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 09:23:04 -0700 Subject: [PATCH 0375/1265] atom.gyp -> electron.gyp --- atom.gyp => electron.gyp | 0 script/bump-version.py | 4 ++-- script/lib/util.py | 2 +- script/update.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename atom.gyp => electron.gyp (100%) diff --git a/atom.gyp b/electron.gyp similarity index 100% rename from atom.gyp rename to electron.gyp diff --git a/script/bump-version.py b/script/bump-version.py index e2c22e8cd9d..5c70d4494e8 100755 --- a/script/bump-version.py +++ b/script/bump-version.py @@ -44,13 +44,13 @@ def increase_version(versions, index): def update_atom_gyp(version): pattern = re.compile(" *'version%' *: *'[0-9.]+'") - with open('atom.gyp', 'r') as f: + with open('electron.gyp', 'r') as f: lines = f.readlines() for i in range(0, len(lines)): if pattern.match(lines[i]): lines[i] = " 'version%': '{0}',\n".format(version) - with open('atom.gyp', 'w') as f: + with open('electron.gyp', 'w') as f: f.write(''.join(lines)) return diff --git a/script/lib/util.py b/script/lib/util.py index fc52d316d30..4e5fb90988d 100644 --- a/script/lib/util.py +++ b/script/lib/util.py @@ -180,7 +180,7 @@ def execute_stdout(argv, env=os.environ): def atom_gyp(): SOURCE_ROOT = os.path.abspath(os.path.join(__file__, '..', '..', '..')) - gyp = os.path.join(SOURCE_ROOT, 'atom.gyp') + gyp = os.path.join(SOURCE_ROOT, 'electron.gyp') with open(gyp) as f: obj = eval(f.read()); return obj['variables'] diff --git a/script/update.py b/script/update.py index e91e8401cbf..33a4cff50f6 100755 --- a/script/update.py +++ b/script/update.py @@ -68,7 +68,7 @@ def run_gyp(target_arch, component): '-Dmas_build={0}'.format(mas_build), ] return subprocess.call([python, gyp, '-f', 'ninja', '--depth', '.', - 'atom.gyp', '-Icommon.gypi'] + defines, env=env) + 'electron.gyp', '-Icommon.gypi'] + defines, env=env) if __name__ == '__main__': From ce95747a255775574e6bbabdfd45ca343e35081e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 09:26:11 -0700 Subject: [PATCH 0376/1265] atom.asar -> electron.asar --- atom/common/node_bindings.cc | 2 +- electron.gyp | 4 ++-- lib/common/api/callbacks-registry.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index b0b4148c7ba..ce3b9a70815 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -161,7 +161,7 @@ node::Environment* NodeBindings::CreateEnvironment( FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer"); base::FilePath resources_path = GetResourcesPath(is_browser_); base::FilePath script_path = - resources_path.Append(FILE_PATH_LITERAL("atom.asar")) + resources_path.Append(FILE_PATH_LITERAL("electron.asar")) .Append(process_type) .Append(FILE_PATH_LITERAL("init.js")); std::string script_path_str = script_path.AsUTF8Unsafe(); diff --git a/electron.gyp b/electron.gyp index 501cc3ab777..9652bd662c7 100644 --- a/electron.gyp +++ b/electron.gyp @@ -87,7 +87,7 @@ }, # The application doesn't have real localizations, it just has # empty .lproj directories, which is enough to convince Cocoa - # atom-shell supports those languages. + # that Electron supports those languages. { 'postbuild_name': 'Make Empty Localizations', 'variables': { @@ -353,7 +353,7 @@ '<@(js_sources)', ], 'outputs': [ - '<(resources_path)/atom.asar', + '<(resources_path)/electron.asar', ], 'action': [ 'python', diff --git a/lib/common/api/callbacks-registry.js b/lib/common/api/callbacks-registry.js index 3e71899df29..7a9bf534f72 100644 --- a/lib/common/api/callbacks-registry.js +++ b/lib/common/api/callbacks-registry.js @@ -26,7 +26,7 @@ class CallbacksRegistry { if (location.indexOf('(native)') !== -1) { continue } - if (location.indexOf('atom.asar') !== -1) { + if (location.indexOf('electron.asar') !== -1) { continue } ref = /([^\/^\)]*)\)?$/gi.exec(location) From ee9128268eb1a83d457146d214dd4d7cb436604d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 14:07:28 -0700 Subject: [PATCH 0377/1265] Rename atom.icns to electron.icns --- atom/browser/resources/mac/Info.plist | 2 +- .../resources/mac/{atom.icns => electron.icns} | Bin filenames.gypi | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename atom/browser/resources/mac/{atom.icns => electron.icns} (100%) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index f7bd068e8f4..e2afa33f7df 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType APPL CFBundleIconFile - atom.icns + electron.icns CFBundleVersion 0.37.3 CFBundleShortVersionString diff --git a/atom/browser/resources/mac/atom.icns b/atom/browser/resources/mac/electron.icns similarity index 100% rename from atom/browser/resources/mac/atom.icns rename to atom/browser/resources/mac/electron.icns diff --git a/filenames.gypi b/filenames.gypi index 97c2c0e6c52..2c39a8dccef 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -5,7 +5,7 @@ 'atom/app/atom_main.h', ], 'bundle_sources': [ - 'atom/browser/resources/mac/atom.icns', + 'atom/browser/resources/mac/electron.icns', ], 'js_sources': [ 'lib/browser/api/app.js', From 3c96d7b72651d21dccd43c70bdf2bb70d50a2650 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 15:46:41 -0700 Subject: [PATCH 0378/1265] Rename atom.asar to electron.asar in specs --- spec/asar-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/asar-spec.js b/spec/asar-spec.js index 45c4c119ca9..a0cb7b4aabd 100644 --- a/spec/asar-spec.js +++ b/spec/asar-spec.js @@ -17,7 +17,7 @@ describe('asar package', function () { it('does not leak fd', function () { var readCalls = 1 while (readCalls <= 10000) { - fs.readFileSync(path.join(process.resourcesPath, 'atom.asar', 'renderer', 'api', 'ipc.js')) + fs.readFileSync(path.join(process.resourcesPath, 'electron.asar', 'renderer', 'api', 'ipc.js')) readCalls++ } }) From 777704e6593e9fca4b34fc1d3d405eda5df07167 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 23 Mar 2016 16:53:20 -0700 Subject: [PATCH 0379/1265] Add failing spec for nodeIntegration inheritance --- spec/chromium-spec.js | 21 +++++++++++++++++++ .../window-opener-no-node-integration.html | 15 +++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 spec/fixtures/pages/window-opener-no-node-integration.html diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 27660156e32..bb76cfb2a8e 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -182,6 +182,27 @@ describe('chromium feature', function () { b = window.open('file://' + fixtures + '/pages/window-open-size.html', '', 'show=no') }) + it('disables node integration when it is disabled on the parent window', function (done) { + var b + listener = function (event) { + assert.equal(event.data, 'undefined') + b.close() + done() + } + window.addEventListener('message', listener) + + var windowUrl = require('url').format({ + pathname: fixtures + "/pages/window-opener-no-node-integration.html", + protocol: 'file', + query: { + p: fixtures + "/pages/window-opener-node.html" + }, + slashes: true + }) + console.log(windowUrl) + b = window.open(windowUrl, 'nodeIntegration=no,show=no') + }) + it('does not override child options', function (done) { var b, size size = { diff --git a/spec/fixtures/pages/window-opener-no-node-integration.html b/spec/fixtures/pages/window-opener-no-node-integration.html new file mode 100644 index 00000000000..e146a2804ae --- /dev/null +++ b/spec/fixtures/pages/window-opener-no-node-integration.html @@ -0,0 +1,15 @@ + + + + + From 463e077c3af77f47312ec736206d886e9089a47c Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 23 Mar 2016 17:36:26 -0700 Subject: [PATCH 0380/1265] Disable node on child when disabled on parent --- lib/browser/guest-window-manager.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 0426ea51583..467e819fa82 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -28,6 +28,11 @@ var mergeBrowserWindowOptions = function (embedder, options) { if (embedder.browserWindowOptions != null) { // Inherit the original options if it is a BrowserWindow. mergeOptions(options, embedder.browserWindowOptions) + + // Disable node integration on child window if disabled on parent window + if (!embedder.browserWindowOptions.webPreferences.nodeIntegration) { + options.webPreferences.nodeIntegration = false + } } else { // Or only inherit web-preferences if it is a webview. if (options.webPreferences == null) { From 2713580d09aacee4fa352dbab26ee55781bdee01 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 23 Mar 2016 17:38:30 -0700 Subject: [PATCH 0381/1265] Remove stray log --- spec/chromium-spec.js | 1 - 1 file changed, 1 deletion(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index bb76cfb2a8e..9a2ba80fb07 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -199,7 +199,6 @@ describe('chromium feature', function () { }, slashes: true }) - console.log(windowUrl) b = window.open(windowUrl, 'nodeIntegration=no,show=no') }) From d7b1792503753fde417f47772e6d21ebd97f512f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 23 Mar 2016 17:40:25 -0700 Subject: [PATCH 0382/1265] Use template strings --- spec/chromium-spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 9a2ba80fb07..507101dc93b 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -192,10 +192,10 @@ describe('chromium feature', function () { window.addEventListener('message', listener) var windowUrl = require('url').format({ - pathname: fixtures + "/pages/window-opener-no-node-integration.html", + pathname: `${fixtures}/pages/window-opener-no-node-integration.html`, protocol: 'file', query: { - p: fixtures + "/pages/window-opener-node.html" + p: `${fixtures}/pages/window-opener-node.html` }, slashes: true }) From 9e66df23d0bbee093d7b32327cb6bf5e044d394c Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 12:29:54 -0700 Subject: [PATCH 0383/1265] Add clearer assertion of process being undefined --- spec/chromium-spec.js | 4 ++-- spec/fixtures/pages/window-opener-node.html | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 507101dc93b..aa4e5c5fdaf 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -160,7 +160,7 @@ describe('chromium feature', function () { it('accepts "nodeIntegration" as feature', function (done) { var b listener = function (event) { - assert.equal(event.data, 'undefined') + assert.equal(event.data.isProcessGlobalUndefined, true) b.close() done() } @@ -185,7 +185,7 @@ describe('chromium feature', function () { it('disables node integration when it is disabled on the parent window', function (done) { var b listener = function (event) { - assert.equal(event.data, 'undefined') + assert.equal(event.data.isProcessGlobalUndefined, true) b.close() done() } diff --git a/spec/fixtures/pages/window-opener-node.html b/spec/fixtures/pages/window-opener-node.html index 118603c82d3..13036072876 100644 --- a/spec/fixtures/pages/window-opener-node.html +++ b/spec/fixtures/pages/window-opener-node.html @@ -1,7 +1,7 @@ From dbe1c1d4e42ef87bd87090db05eb42ad2499fd71 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 13:22:13 -0700 Subject: [PATCH 0384/1265] Check nodeIntegration on embedder's webPreferences --- lib/browser/guest-window-manager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 467e819fa82..f27bb8329fa 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -30,7 +30,7 @@ var mergeBrowserWindowOptions = function (embedder, options) { mergeOptions(options, embedder.browserWindowOptions) // Disable node integration on child window if disabled on parent window - if (!embedder.browserWindowOptions.webPreferences.nodeIntegration) { + if (!embedder.getWebPreferences().nodeIntegration) { options.webPreferences.nodeIntegration = false } } else { From e5164d2255d82cd8a33e7ce91a28d5e2f5df96e3 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 13:27:03 -0700 Subject: [PATCH 0385/1265] Check of nodeIntegration is strictly equal to false --- lib/browser/guest-window-manager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index f27bb8329fa..5782670ac63 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -30,7 +30,7 @@ var mergeBrowserWindowOptions = function (embedder, options) { mergeOptions(options, embedder.browserWindowOptions) // Disable node integration on child window if disabled on parent window - if (!embedder.getWebPreferences().nodeIntegration) { + if (embedder.getWebPreferences().nodeIntegration === false) { options.webPreferences.nodeIntegration = false } } else { From 4890734f66fc358c004a719d39ac247ae2327b33 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 24 Mar 2016 14:12:46 -0700 Subject: [PATCH 0386/1265] Add missing title param --- spec/chromium-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index aa4e5c5fdaf..1d37d0fe051 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -199,7 +199,7 @@ describe('chromium feature', function () { }, slashes: true }) - b = window.open(windowUrl, 'nodeIntegration=no,show=no') + b = window.open(windowUrl, '', 'nodeIntegration=no,show=no') }) it('does not override child options', function (done) { From fd12e1f50653df17eb6fd6d5918c2bca1138eb1f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 10:33:15 -0700 Subject: [PATCH 0387/1265] Add failing spec for webview nodeIntegration inheritance --- .../webview-opener-no-node-integration.html | 9 ++++++ spec/webview-spec.js | 29 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 spec/fixtures/pages/webview-opener-no-node-integration.html diff --git a/spec/fixtures/pages/webview-opener-no-node-integration.html b/spec/fixtures/pages/webview-opener-no-node-integration.html new file mode 100644 index 00000000000..cd95f9bb9fb --- /dev/null +++ b/spec/fixtures/pages/webview-opener-no-node-integration.html @@ -0,0 +1,9 @@ + + + + + diff --git a/spec/webview-spec.js b/spec/webview-spec.js index e5116293563..3d45d51e6ac 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -3,6 +3,9 @@ const path = require('path') const http = require('http') const url = require('url') +const {remote} = require('electron') +const {BrowserWindow} = remote + describe(' tag', function () { this.timeout(10000) @@ -74,6 +77,32 @@ describe(' tag', function () { document.body.appendChild(webview) }) + + it('disables node integration on child windows when it is disabled on the webview', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'window opened') + const sourceId = remote.getCurrentWindow().id + const windows = BrowserWindow.getAllWindows().filter(function (window) { + return window.id !== sourceId + }) + assert.equal(windows.length, 1) + assert.equal(windows[0].webContents.getWebPreferences().nodeIntegration, false) + done() + }) + + webview.setAttribute('allowpopups', 'on') + + webview.src = require('url').format({ + pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`, + protocol: 'file', + query: { + p: `${fixtures}/pages/window-opener-node.html` + }, + slashes: true + }) + document.body.appendChild(webview) + }) + if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) { it('loads native modules when navigation happens', function (done) { var listener = function () { From eafe9c245b6b8c74fb1e49b0a458f546696176d3 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 10:51:56 -0700 Subject: [PATCH 0388/1265] Disable guest node integration when embedder has it disabled --- lib/browser/guest-window-manager.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 5782670ac63..7508b6f16a2 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -28,11 +28,6 @@ var mergeBrowserWindowOptions = function (embedder, options) { if (embedder.browserWindowOptions != null) { // Inherit the original options if it is a BrowserWindow. mergeOptions(options, embedder.browserWindowOptions) - - // Disable node integration on child window if disabled on parent window - if (embedder.getWebPreferences().nodeIntegration === false) { - options.webPreferences.nodeIntegration = false - } } else { // Or only inherit web-preferences if it is a webview. if (options.webPreferences == null) { @@ -40,6 +35,12 @@ var mergeBrowserWindowOptions = function (embedder, options) { } mergeOptions(options.webPreferences, embedder.getWebPreferences()) } + + // Disable node integration on child window if disabled on parent window + if (embedder.getWebPreferences().nodeIntegration === false) { + options.webPreferences.nodeIntegration = false + } + return options } From 55b12c184b1c3c4b2d5d32a8944d7234d88e709a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 10:55:16 -0700 Subject: [PATCH 0389/1265] Doc node integration inheritance --- docs/api/web-view-tag.md | 3 +++ docs/api/window-open.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index ff9013023c1..47e23dc9943 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -84,6 +84,9 @@ than the minimum values or greater than the maximum. If "on", the guest page in `webview` will have node integration and can use node APIs like `require` and `process` to access low level system resources. +**Note:** Node integration will always be disabled in the `webview` if it is +disabled on the parent window. + ### `plugins` ```html diff --git a/docs/api/window-open.md b/docs/api/window-open.md index 5d298e61e75..46e74327741 100644 --- a/docs/api/window-open.md +++ b/docs/api/window-open.md @@ -23,6 +23,9 @@ Creates a new window and returns an instance of `BrowserWindowProxy` class. The `features` string follows the format of standard browser, but each feature has to be a field of `BrowserWindow`'s options. +**Note:** Node integration will always be disabled in the opened `window` if it +is disabled on the parent window. + ### `window.opener.postMessage(message, targetOrigin)` * `message` String From ef2a28ca8643a88546f42fb39d4851f7a421f90d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 11:17:24 -0700 Subject: [PATCH 0390/1265] Listen for browser-window-created event for asserts --- spec/webview-spec.js | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 3d45d51e6ac..122c22ad289 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -4,7 +4,7 @@ const http = require('http') const url = require('url') const {remote} = require('electron') -const {BrowserWindow} = remote +const {app} = remote describe(' tag', function () { this.timeout(10000) @@ -79,14 +79,8 @@ describe(' tag', function () { it('disables node integration on child windows when it is disabled on the webview', function (done) { - webview.addEventListener('console-message', function (e) { - assert.equal(e.message, 'window opened') - const sourceId = remote.getCurrentWindow().id - const windows = BrowserWindow.getAllWindows().filter(function (window) { - return window.id !== sourceId - }) - assert.equal(windows.length, 1) - assert.equal(windows[0].webContents.getWebPreferences().nodeIntegration, false) + app.once('browser-window-created', function (event, window) { + assert.equal(window.webContents.getWebPreferences().nodeIntegration, false) done() }) From 230ed78dd677204d03c5b278690ab23825f2e1b9 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 30 Mar 2016 11:56:31 -0700 Subject: [PATCH 0391/1265] Remove lint warnings --- spec/webview-spec.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 122c22ad289..e47c7182883 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -2,9 +2,7 @@ const assert = require('assert') const path = require('path') const http = require('http') const url = require('url') - -const {remote} = require('electron') -const {app} = remote +const {app, session} = require('electron') describe(' tag', function () { this.timeout(10000) @@ -704,7 +702,6 @@ describe(' tag', function () { describe('permission-request event', function () { function setUpRequestHandler (webview, requested_permission) { - const session = require('electron').remote.session var listener = function (webContents, permission, callback) { if (webContents.getId() === webview.getId()) { assert.equal(permission, requested_permission) From 909ed54befd25e8b070d283467c7a90c3d4c121d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 1 Apr 2016 16:52:28 -0700 Subject: [PATCH 0392/1265] Remove stray log --- spec/fixtures/pages/webview-opener-no-node-integration.html | 1 - 1 file changed, 1 deletion(-) diff --git a/spec/fixtures/pages/webview-opener-no-node-integration.html b/spec/fixtures/pages/webview-opener-no-node-integration.html index cd95f9bb9fb..1275a99b0bf 100644 --- a/spec/fixtures/pages/webview-opener-no-node-integration.html +++ b/spec/fixtures/pages/webview-opener-no-node-integration.html @@ -3,7 +3,6 @@ From 7734f6af621a56993f0698b3165316552c83dd16 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 1 Apr 2016 16:52:55 -0700 Subject: [PATCH 0393/1265] Remove semicolons --- spec/fixtures/pages/window-opener-no-node-integration.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/fixtures/pages/window-opener-no-node-integration.html b/spec/fixtures/pages/window-opener-no-node-integration.html index e146a2804ae..b587e979227 100644 --- a/spec/fixtures/pages/window-opener-no-node-integration.html +++ b/spec/fixtures/pages/window-opener-no-node-integration.html @@ -5,11 +5,11 @@ var opened = window.open('file://' + windowUrl, '', 'nodeIntegration=yes,show=no') window.addEventListener('message', function (event) { try { - opened.close(); + opened.close() } finally { - window.opener.postMessage(event.data, '*'); + window.opener.postMessage(event.data, '*') } - }); + }) From 3695e3871930a2be17e106511b2beedf48f6f5a9 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 1 Apr 2016 16:53:44 -0700 Subject: [PATCH 0394/1265] Remove duplicate require --- spec/webview-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index e47c7182883..583d98131d4 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -84,7 +84,7 @@ describe(' tag', function () { webview.setAttribute('allowpopups', 'on') - webview.src = require('url').format({ + webview.src = url.format({ pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`, protocol: 'file', query: { From 527ff66115dcbab596067593fe436457d1cd62c2 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 1 Apr 2016 16:59:13 -0700 Subject: [PATCH 0395/1265] Pull app/session from remote --- spec/webview-spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 583d98131d4..0d32138906e 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -2,7 +2,7 @@ const assert = require('assert') const path = require('path') const http = require('http') const url = require('url') -const {app, session} = require('electron') +const {app, session} = require('electron').remote describe(' tag', function () { this.timeout(10000) From cb470cb94ba6034e4fbac6a70d0cf4345af31c90 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 2 Apr 2016 20:35:57 +0900 Subject: [PATCH 0396/1265] Use BrowserWindow's backgroundColor as renderer view's background color --- atom/browser/api/atom_api_window.cc | 4 +++ atom/browser/native_window.cc | 23 ---------------- atom/browser/native_window.h | 3 --- atom/browser/native_window_mac.mm | 3 ++- atom/browser/native_window_views.cc | 3 ++- atom/browser/web_contents_preferences.cc | 5 ++++ atom/common/color_util.cc | 34 ++++++++++++++++++++++++ atom/common/color_util.h | 19 +++++++++++++ atom/common/options_switches.cc | 13 ++++----- atom/common/options_switches.h | 1 + atom/renderer/atom_renderer_client.cc | 14 ++++++++-- filenames.gypi | 2 ++ 12 files changed, 88 insertions(+), 36 deletions(-) create mode 100644 atom/common/color_util.cc create mode 100644 atom/common/color_util.h diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index a10f46fe75e..fd9dd94458c 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -141,6 +141,10 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { if (options.Get(options::kZoomFactor, &value)) web_preferences.Set(options::kZoomFactor, value); + // Copy the backgroundColor to webContents. + if (options.Get(options::kBackgroundColor, &value)) + web_preferences.Set(options::kBackgroundColor, value); + // Creates the WebContents used by BrowserWindow. auto web_contents = WebContents::Create(isolate, web_preferences); web_contents_.Reset(isolate, web_contents.ToV8()); diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 2627c704d21..575ac8c579f 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -594,27 +594,4 @@ void NativeWindow::OnCapturePageDone(const CapturePageCallback& callback, callback.Run(bitmap); } -SkColor NativeWindow::ParseHexColor(const std::string& name) { - auto color = name.substr(1); - unsigned length = color.size(); - SkColor result = (length != 8 ? 0xFF000000 : 0x00000000); - unsigned value = 0; - if (length != 3 && length != 6 && length != 8) - return result; - for (unsigned i = 0; i < length; ++i) { - if (!base::IsHexDigit(color[i])) - return result; - value <<= 4; - value |= (color[i] < 'A' ? color[i] - '0' : (color[i] - 'A' + 10) & 0xF); - } - if (length == 6 || length == 8) { - result |= value; - return result; - } - result |= (value & 0xF00) << 12 | (value & 0xF00) << 8 - | (value & 0xF0) << 8 | (value & 0xF0) << 4 - | (value & 0xF) << 4 | (value & 0xF); - return result; -} - } // namespace atom diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index 49e1e71d5df..f91d041c057 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -282,9 +282,6 @@ class NativeWindow : public base::SupportsUserData, void BeforeUnloadDialogCancelled() override; bool OnMessageReceived(const IPC::Message& message) override; - // Parse hex color like "#FFF" or "#EFEFEF" - SkColor ParseHexColor(const std::string& name); - private: // Schedule a notification unresponsive event. void ScheduleUnresponsiveEvent(int ms); diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 2044ee7d718..456d175f236 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -6,6 +6,7 @@ #include +#include "atom/common/color_util.h" #include "atom/common/draggable_region.h" #include "atom/common/options_switches.h" #include "base/mac/mac_util.h" @@ -804,7 +805,7 @@ bool NativeWindowMac::IsKiosk() { } void NativeWindowMac::SetBackgroundColor(const std::string& color_name) { - SkColor background_color = NativeWindow::ParseHexColor(color_name); + SkColor background_color = ParseHexColor(color_name); NSColor *color = [NSColor colorWithCalibratedRed:SkColorGetR(background_color) green:SkColorGetG(background_color) blue:SkColorGetB(background_color) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 15f2046364b..59d3556d05e 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -9,6 +9,7 @@ #include "atom/browser/ui/views/menu_bar.h" #include "atom/browser/ui/views/menu_layout.h" +#include "atom/common/color_util.h" #include "atom/common/draggable_region.h" #include "atom/common/options_switches.h" #include "base/strings/utf_string_conversions.h" @@ -614,7 +615,7 @@ bool NativeWindowViews::IsKiosk() { void NativeWindowViews::SetBackgroundColor(const std::string& color_name) { // web views' background color. - SkColor background_color = NativeWindow::ParseHexColor(color_name); + SkColor background_color = ParseHexColor(color_name); set_background(views::Background::CreateSolidBackground(background_color)); #if defined(OS_WIN) diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index bcdbd736676..f36e7c076dc 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -116,6 +116,11 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( LOG(ERROR) << "preload url must be file:// protocol."; } + // --background-color. + std::string color; + if (web_preferences.GetString(options::kBackgroundColor, &color)) + command_line->AppendSwitchASCII(switches::kBackgroundColor, color); + // The zoom factor. double zoom_factor = 1.0; if (web_preferences.GetDouble(options::kZoomFactor, &zoom_factor) && diff --git a/atom/common/color_util.cc b/atom/common/color_util.cc new file mode 100644 index 00000000000..fed050cd717 --- /dev/null +++ b/atom/common/color_util.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/common/color_util.h" + +#include "base/strings/string_util.h" + +namespace atom { + +SkColor ParseHexColor(const std::string& name) { + auto color = name.substr(1); + unsigned length = color.size(); + SkColor result = (length != 8 ? 0xFF000000 : 0x00000000); + unsigned value = 0; + if (length != 3 && length != 6 && length != 8) + return result; + for (unsigned i = 0; i < length; ++i) { + if (!base::IsHexDigit(color[i])) + return result; + value <<= 4; + value |= (color[i] < 'A' ? color[i] - '0' : (color[i] - 'A' + 10) & 0xF); + } + if (length == 6 || length == 8) { + result |= value; + return result; + } + result |= (value & 0xF00) << 12 | (value & 0xF00) << 8 + | (value & 0xF0) << 8 | (value & 0xF0) << 4 + | (value & 0xF) << 4 | (value & 0xF); + return result; +} + +} // namespace atom diff --git a/atom/common/color_util.h b/atom/common/color_util.h new file mode 100644 index 00000000000..0f2bb9633a7 --- /dev/null +++ b/atom/common/color_util.h @@ -0,0 +1,19 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_COMMON_COLOR_UTIL_H_ +#define ATOM_COMMON_COLOR_UTIL_H_ + +#include + +#include "third_party/skia/include/core/SkColor.h" + +namespace atom { + +// Parse hex color like "#FFF" or "#EFEFEF" +SkColor ParseHexColor(const std::string& name); + +} // namespace atom + +#endif // ATOM_COMMON_COLOR_UTIL_H_ diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index ac63ea1b727..ce28cc98fac 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -142,12 +142,13 @@ const char kCipherSuiteBlacklist[] = "cipher-suite-blacklist"; const char kAppUserModelId[] = "app-user-model-id"; // The command line switch versions of the options. -const char kZoomFactor[] = "zoom-factor"; -const char kPreloadScript[] = "preload"; -const char kPreloadURL[] = "preload-url"; -const char kNodeIntegration[] = "node-integration"; -const char kGuestInstanceID[] = "guest-instance-id"; -const char kOpenerID[] = "opener-id"; +const char kBackgroundColor[] = "background-color"; +const char kZoomFactor[] = "zoom-factor"; +const char kPreloadScript[] = "preload"; +const char kPreloadURL[] = "preload-url"; +const char kNodeIntegration[] = "node-integration"; +const char kGuestInstanceID[] = "guest-instance-id"; +const char kOpenerID[] = "opener-id"; // Widevine options // Path to Widevine CDM binaries. diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 3c198555a5c..52d64c00d51 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -76,6 +76,7 @@ extern const char kSSLVersionFallbackMin[]; extern const char kCipherSuiteBlacklist[]; extern const char kAppUserModelId[]; +extern const char kBackgroundColor[]; extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadURL[]; diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index 7746ce123e4..4bb3cd2168c 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -10,6 +10,7 @@ #include "atom/common/api/api_messages.h" #include "atom/common/api/atom_bindings.h" #include "atom/common/api/event_emitter_caller.h" +#include "atom/common/color_util.h" #include "atom/common/node_bindings.h" #include "atom/common/node_includes.h" #include "atom/common/options_switches.h" @@ -120,8 +121,17 @@ void AtomRendererClient::RenderFrameCreated( } void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) { - // Set default UA-dependent background as transparent. - render_view->GetWebView()->setBaseBackgroundColor(SK_ColorTRANSPARENT); + base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); + if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview. + // Set transparent background. + render_view->GetWebView()->setBaseBackgroundColor(SK_ColorTRANSPARENT); + } else { // normal window. + // If backgroundColor is specified then use it. + std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor); + // Otherwise use white background. + SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name); + render_view->GetWebView()->setBaseBackgroundColor(color); + } new printing::PrintWebViewHelper(render_view); new AtomRenderViewObserver(render_view, this); diff --git a/filenames.gypi b/filenames.gypi index 2c39a8dccef..688886b5b9c 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -307,6 +307,8 @@ 'atom/common/atom_command_line.h', 'atom/common/atom_constants.cc', 'atom/common/atom_constants.h', + 'atom/common/color_util.cc', + 'atom/common/color_util.h', 'atom/common/common_message_generator.cc', 'atom/common/common_message_generator.h', 'atom/common/crash_reporter/crash_reporter.cc', From 1980d85f3eb02ed662c35cf58426fb56283b5429 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 2 Apr 2016 21:17:38 +0900 Subject: [PATCH 0397/1265] Fix converting SkColor to NSColor Close #4992. --- atom/browser/native_window_mac.mm | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 456d175f236..bb8bd938761 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -19,6 +19,7 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "native_mate/dictionary.h" +#include "skia/ext/skia_utils_mac.h" #include "ui/gfx/skia_util.h" namespace { @@ -805,12 +806,8 @@ bool NativeWindowMac::IsKiosk() { } void NativeWindowMac::SetBackgroundColor(const std::string& color_name) { - SkColor background_color = ParseHexColor(color_name); - NSColor *color = [NSColor colorWithCalibratedRed:SkColorGetR(background_color) - green:SkColorGetG(background_color) - blue:SkColorGetB(background_color) - alpha:SkColorGetA(background_color)/255.0f]; - [window_ setBackgroundColor:color]; + SkColor color = ParseHexColor(color_name); + [window_ setBackgroundColor:skia::SkColorToCalibratedNSColor(color)]; } void NativeWindowMac::SetHasShadow(bool has_shadow) { From 19a172f2f589e9702bdc7813372a9f72ca094e3d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 2 Apr 2016 21:21:30 +0900 Subject: [PATCH 0398/1265] Remove the hacks because of transparent background --- docs/faq/electron-faq.md | 13 ------------- spec/static/index.html | 5 ----- 2 files changed, 18 deletions(-) diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index 1782d387310..41b301d7198 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -144,19 +144,6 @@ is very likely you are using the module in the wrong process. For example `electron.app` can only be used in the main process, while `electron.webFrame` is only available in renderer processes. -## Why is my app's background transparent? - -Since Electron `0.37.3`, the default user-agent background color is `transparent`. -Simply specify a background color in HTML: - -```html - -``` - [memory-management]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management [variable-scope]: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx [electron-module]: https://www.npmjs.com/package/electron diff --git a/spec/static/index.html b/spec/static/index.html index 3c57f94d144..e31fcffebb8 100644 --- a/spec/static/index.html +++ b/spec/static/index.html @@ -3,11 +3,6 @@ - From 8c3ff97ba4439723d7958222d8639ddcaedace1f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 2 Apr 2016 21:11:02 +0900 Subject: [PATCH 0399/1265] Make the logic of ParseHexColor more easy to understand This also fixes the #FFFF style of color hex. --- atom/common/color_util.cc | 54 ++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/atom/common/color_util.cc b/atom/common/color_util.cc index fed050cd717..a6640d9e08b 100644 --- a/atom/common/color_util.cc +++ b/atom/common/color_util.cc @@ -4,31 +4,45 @@ #include "atom/common/color_util.h" +#include + +#include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" namespace atom { -SkColor ParseHexColor(const std::string& name) { - auto color = name.substr(1); - unsigned length = color.size(); - SkColor result = (length != 8 ? 0xFF000000 : 0x00000000); - unsigned value = 0; - if (length != 3 && length != 6 && length != 8) - return result; - for (unsigned i = 0; i < length; ++i) { - if (!base::IsHexDigit(color[i])) - return result; - value <<= 4; - value |= (color[i] < 'A' ? color[i] - '0' : (color[i] - 'A' + 10) & 0xF); +SkColor ParseHexColor(const std::string& color_string) { + // Check the string for incorrect formatting. + if (color_string.empty() || color_string[0] != '#') + return SK_ColorWHITE; + + // Prepend FF if alpha channel is not specified. + std::string source = color_string.substr(1); + if (source.size() == 3) + source.insert(0, "F"); + else if (source.size() == 6) + source.insert(0, "FF"); + + // Convert the string from #FFF format to #FFFFFF format. + std::string formatted_color; + if (source.size() == 4) { + for (size_t i = 0; i < 4; ++i) { + formatted_color += source[i]; + formatted_color += source[i]; + } + } else if (source.size() == 8) { + formatted_color = source; + } else { + return SK_ColorWHITE; } - if (length == 6 || length == 8) { - result |= value; - return result; - } - result |= (value & 0xF00) << 12 | (value & 0xF00) << 8 - | (value & 0xF0) << 8 | (value & 0xF0) << 4 - | (value & 0xF) << 4 | (value & 0xF); - return result; + + // Convert the string to an integer and make sure it is in the correct value + // range. + std::vector bytes; + if (!base::HexStringToBytes(formatted_color, &bytes)) + return SK_ColorWHITE; + + return SkColorSetARGB(bytes[0], bytes[1], bytes[2], bytes[3]); } } // namespace atom From 9828875ebc5c172b7f9d85a606b7f016f7572a4d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 10:37:48 +0900 Subject: [PATCH 0400/1265] Set the background color of RenderViewHost to transparent --- atom/browser/api/atom_api_web_contents.cc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 8c0f7d571f3..5156600bb73 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -728,6 +728,13 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) { params.should_clear_history_list = true; params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; web_contents()->GetController().LoadURLWithParams(params); + + // Set the background color of RenderViewHost to transparent so it doesn't + // override the background color set by the user. + // We have to call it right after LoadURL because the RenderViewHost is only + // created after loading a page. + web_contents()->GetRenderViewHost()->GetWidget()->GetView() + ->SetBackgroundColor(SK_ColorTRANSPARENT); } void WebContents::DownloadURL(const GURL& url) { From 4a724e91e01cdb108ccfd84599e2fe765c28ba60 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 11:17:57 +0900 Subject: [PATCH 0401/1265] Update libchromiumcontent: remove white background on OS X --- script/lib/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/lib/config.py b/script/lib/config.py index 83960e68e2c..707917f6f10 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'd41c1e48f428257d99abcf29fd9f26928e9fc53e' +LIBCHROMIUMCONTENT_COMMIT = '9229f39b44ca1dde25db9c648547861286b61935' PLATFORM = { 'cygwin': 'win32', From f94661547c2123f443638c9004b23940239b6058 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 11:59:21 +0900 Subject: [PATCH 0402/1265] mac: backgroundColor should not change titlebar color --- atom/browser/native_window_mac.mm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index bb8bd938761..3c76cbe25a5 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -10,6 +10,7 @@ #include "atom/common/draggable_region.h" #include "atom/common/options_switches.h" #include "base/mac/mac_util.h" +#include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents_view.h" @@ -806,8 +807,9 @@ bool NativeWindowMac::IsKiosk() { } void NativeWindowMac::SetBackgroundColor(const std::string& color_name) { - SkColor color = ParseHexColor(color_name); - [window_ setBackgroundColor:skia::SkColorToCalibratedNSColor(color)]; + base::ScopedCFTypeRef color = + skia::CGColorCreateFromSkColor(ParseHexColor(color_name)); + [[[window_ contentView] layer] setBackgroundColor:color]; } void NativeWindowMac::SetHasShadow(bool has_shadow) { From 491bf30a1595f135e612fdc7901bd6f6e736609d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 12:04:58 +0900 Subject: [PATCH 0403/1265] Window with frame should have white background by default --- atom/browser/native_window.cc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 575ac8c579f..9762351de22 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -162,6 +162,9 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(color); + } else if (has_frame()) { + // For window with frame, use white as default background. + SetBackgroundColor("#FFFF"); } std::string title("Electron"); options.Get(options::kTitle, &title); From 769ba02b2ae168fff0e5c1dea0c75f7f92102741 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Sun, 3 Apr 2016 10:01:47 +0530 Subject: [PATCH 0404/1265] browser: create cert verifier when browser context is created --- atom/browser/atom_browser_context.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index d6724ff5338..b06c6278f53 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -65,7 +65,7 @@ std::string RemoveWhitespace(const std::string& str) { AtomBrowserContext::AtomBrowserContext(const std::string& partition, bool in_memory) : brightray::BrowserContext(partition, in_memory), - cert_verifier_(nullptr), + cert_verifier_(new AtomCertVerifier), job_factory_(new AtomURLRequestJobFactory), network_delegate_(new AtomNetworkDelegate), allow_ntlm_everywhere_(false) { @@ -178,8 +178,6 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() { } scoped_ptr AtomBrowserContext::CreateCertVerifier() { - DCHECK(!cert_verifier_); - cert_verifier_ = new AtomCertVerifier; return make_scoped_ptr(cert_verifier_); } From 165009681bedf4737a160da775d7f38900b985b5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 13:53:09 +0900 Subject: [PATCH 0405/1265] Set backgroundColor for the default app --- default_app/default_app.js | 1 + 1 file changed, 1 insertion(+) diff --git a/default_app/default_app.js b/default_app/default_app.js index eda1300f007..200e8c585af 100644 --- a/default_app/default_app.js +++ b/default_app/default_app.js @@ -15,6 +15,7 @@ exports.load = function (appUrl) { width: 800, height: 600, autoHideMenuBar: true, + backgroundColor: '#A5ECFA', useContentSize: true }) mainWindow.loadURL(appUrl) From eb82f7cea9c341bb495e794200647e0f5c515481 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 13:55:33 +0900 Subject: [PATCH 0406/1265] Update docs for backgroundColor --- docs/api/browser-window.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index e42b2d9bd09..0e79659854a 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -83,8 +83,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`. than screen. Default is `false`. * `backgroundColor` String - Window's background color as Hexadecimal value, like `#66CD00` or `#FFF` or `#80FFFFFF` (alpha is supported). Default is - `#000` (black) for Linux and Windows, `#FFF` for Mac (or clear if - transparent). + `#FFF` (white). * `hasShadow` Boolean - Whether window should have a shadow. This is only implemented on OS X. Default is `true`. * `darkTheme` Boolean - Forces using dark theme for the window, only works on From 39a20ea4fbd592c8903ee9e93a2245889b6f3fac Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 15:05:47 +0900 Subject: [PATCH 0407/1265] Upgrade Node to v5.10.0 --- atom/common/api/atom_bindings.cc | 11 ++++++++++- atom/common/node_bindings.cc | 3 +++ vendor/node | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/atom/common/api/atom_bindings.cc b/atom/common/api/atom_bindings.cc index fe53d8793f2..f518caf5c50 100644 --- a/atom/common/api/atom_bindings.cc +++ b/atom/common/api/atom_bindings.cc @@ -98,8 +98,17 @@ void AtomBindings::OnCallNextTick(uv_async_t* handle) { self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; + // KickNextTick, copied from node.cc: node::Environment::AsyncCallbackScope callback_scope(env); - env->KickNextTick(&callback_scope); + if (callback_scope.in_makecallback()) + continue; + node::Environment::TickInfo* tick_info = env->tick_info(); + if (tick_info->length() == 0) + env->isolate()->RunMicrotasks(); + v8::Local process = env->process_object(); + if (tick_info->length() == 0) + tick_info->set_index(0); + env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty(); } self->pending_next_ticks_.clear(); diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index ce3b9a70815..86fb3a6d03a 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -175,6 +175,9 @@ node::Environment* NodeBindings::CreateEnvironment( mate::Dictionary process(context->GetIsolate(), env->process_object()); process.Set("type", process_type); process.Set("resourcesPath", resources_path); + // Do not set DOM globals for renderer process. + if (!is_browser_) + process.Set("_noBrowserGlobals", resources_path); // The path to helper app. base::FilePath helper_exec_path; PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); diff --git a/vendor/node b/vendor/node index d8e7d3e76cb..95e76436b3a 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit d8e7d3e76cb3c6e709449d181ddc2af8c4859303 +Subproject commit 95e76436b3aceff54ebf8b32282cdbf8c74c4a5a From fdb138f79cfaed6d5843710bfa88a2b4cf019da0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 3 Apr 2016 18:31:23 +0900 Subject: [PATCH 0408/1265] Bump v0.37.4 --- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- electron.gyp | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index e2afa33f7df..7827a50d9fa 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 0.37.3 + 0.37.4 CFBundleShortVersionString - 0.37.3 + 0.37.4 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 15252346669..95f34256345 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,3,0 - PRODUCTVERSION 0,37,3,0 + FILEVERSION 0,37,4,0 + PRODUCTVERSION 0,37,4,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.3" + VALUE "FileVersion", "0.37.4" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.3" + VALUE "ProductVersion", "0.37.4" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index cb470529340..73662b177c9 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 3 +#define ATOM_PATCH_VERSION 4 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/electron.gyp b/electron.gyp index 9652bd662c7..bcea9365b23 100644 --- a/electron.gyp +++ b/electron.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.3', + 'version%': '0.37.4', }, 'includes': [ 'filenames.gypi', diff --git a/package.json b/package.json index c12f3d37c42..2d1f7ec8b46 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.3", + "version": "0.37.4", "devDependencies": { "asar": "^0.10.0", "request": "*", From 6e9c27fdaaa0e64df9b23694ed9c4e3b401fbe54 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 4 Apr 2016 00:56:07 +0900 Subject: [PATCH 0409/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/accelerator.md | 7 +++- docs-translations/ko-KR/api/app.md | 4 ++ docs-translations/ko-KR/api/browser-window.md | 12 +++++- docs-translations/ko-KR/api/dialog.md | 7 ++++ .../ko-KR/api/global-shortcut.md | 10 ++--- docs-translations/ko-KR/api/ipc-renderer.md | 2 +- docs-translations/ko-KR/api/menu-item.md | 38 +++++++++++++++---- docs-translations/ko-KR/api/tray.md | 2 +- docs-translations/ko-KR/api/web-view-tag.md | 8 +++- docs-translations/ko-KR/api/window-open.md | 3 ++ .../ko-KR/development/coding-style.md | 3 +- .../development/setting-up-symbol-server.md | 2 +- .../ko-KR/tutorial/debugging-main-process.md | 2 +- .../desktop-environment-integration.md | 2 +- .../mac-app-store-submission-guide.md | 4 +- .../tutorial/using-widevine-cdm-plugin.md | 4 +- 16 files changed, 81 insertions(+), 29 deletions(-) diff --git a/docs-translations/ko-KR/api/accelerator.md b/docs-translations/ko-KR/api/accelerator.md index 90adf414dc3..a0eb55e8702 100644 --- a/docs-translations/ko-KR/api/accelerator.md +++ b/docs-translations/ko-KR/api/accelerator.md @@ -5,8 +5,8 @@ Accelerator는 키보드 단축키를 표현하는 문자열입니다, 여러 예제: -* `Command+A` -* `Ctrl+Shift+Z` +* `CommandOrControl+A` +* `CommandOrControl+Shift+Z` ## 플랫폼에 관련하여 주의할 점 @@ -14,6 +14,9 @@ Linux와 Windows에서는 `Command`키가 없으므로 작동하지 않습니다 `CommandOrControl`을 사용하면 OS X의 `Command`와 Linux, Windows의 `Control` 모두 지원할 수 있습니다. +`Option` 대신 `Alt`을 사용하는게 좋습니다. `Option` 키는 OS X에만 있으므로 +모든 플랫폼에서 사용할 수 있는 `Alt` 키를 권장합니다. + `Super`키는 Windows와 Linux 에서는 `윈도우`키를, OS X에서는 `Cmd`키로 맵핑됩니다. ## 사용 가능한 혼합키 diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index ff4269ea829..8e734f2f415 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -353,6 +353,10 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 현재 어플리케이션의 [로케일](https://ko.wikipedia.org/wiki/%EB%A1%9C%EC%BC%80%EC%9D%BC)을 반환합니다. +**참고:** 패키징된 앱을 배포할 때, `locales` 폴더도 같이 배포해야 합니다. + +**참고:** Windows에선 `ready` 이벤트가 발생한 이후에 이 메서드를 사용해야 합니다. + ### `app.addRecentDocument(path)` _OS X_ _Windows_ * `path` String diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 06e31e9fba5..e93956b6fd8 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -81,8 +81,7 @@ win.show(); * `enableLargerThanScreen` Boolean - 윈도우 크기가 화면 크기보다 크게 재조정 될 수 있는지 여부. 기본값은 `false`입니다. * `backgroundColor` String - `#66CD00` 와 `#FFF`, `#80FFFFFF` (알파 지원됨) 같이 - 16진수로 표현된 윈도우의 배경 색. 기본값은 Linux와 Windows에선 `#000` (검정)이며, - Mac에선 `#FFF` (또는, transparent(투명)일 경우 clear(색 없음)로 설정) + 16진수로 표현된 윈도우의 배경 색. 기본값은 `#FFF` (white). * `hasShadow` Boolean - 윈도우가 그림자를 가질지 여부를 지정합니다. 이 속성은 OS X에서만 구현되어 있습니다. 기본값은 `true`입니다. * `darkTheme` Boolean - 설정에 상관 없이 무조건 어두운 윈도우 테마를 사용합니다. @@ -296,11 +295,20 @@ __참고__: OS X에선 이 이벤트가 그저 `moved` 이벤트의 별칭(alias ### Event: 'app-command' _Windows_ +Returns: + +* `event` Event +* `command` String + [App Command](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx)가 호출됐을 때 발생하는 이벤트입니다. 이 이벤트는 일반적으로 키보드 미디어 키 또는 브라우저 커맨드(기본 동작 키)에 관련되어 있습니다. 예를 들어 Windows에서 작동하는 몇몇 마우스는 "뒤로가기" 같은 동작을 포함하고 있습니다. +반환되는 커맨드들은 모두 소문자화되며 언더스코어(`_`)는 하이픈(`-`)으로 변경되며 +`APPCOMMAND_` 접두어는 제거됩니다. +e.g. `APPCOMMAND_BROWSER_BACKWARD` 는 `browser-backward`와 같이 반환됩니다. + ```javascript someWindow.on('app-command', function(e, cmd) { // 마우스의 뒤로가기 버튼을 눌렀을 때 뒤로가기 탐색을 실행합니다 diff --git a/docs-translations/ko-KR/api/dialog.md b/docs-translations/ko-KR/api/dialog.md index 9147f1c5bdc..2a223a45754 100644 --- a/docs-translations/ko-KR/api/dialog.md +++ b/docs-translations/ko-KR/api/dialog.md @@ -12,6 +12,13 @@ const dialog = require('electron').dialog; console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]})); ``` +대화 상자는 Electron의 메인 스레드에서 열립니다. 만약 랜더러 프로세스에서 대화 상자 +객체를 사용하고 싶다면, `remote`를 통해 접근하는 방법을 고려해야 합니다: + +```javascript +const dialog = require('electron').remote.dialog; +``` + **OS X 참고**: 대화 상자를 시트처럼 보여지게 하려면 `browserWindow` 인자에 `BrowserWindow` 객체의 참조를 제공하면 됩니다. diff --git a/docs-translations/ko-KR/api/global-shortcut.md b/docs-translations/ko-KR/api/global-shortcut.md index 658f723692a..6c01368a392 100644 --- a/docs-translations/ko-KR/api/global-shortcut.md +++ b/docs-translations/ko-KR/api/global-shortcut.md @@ -14,9 +14,9 @@ const app = electron.app; const globalShortcut = electron.globalShortcut; app.on('ready', function() { - // 'ctrl+x' 단축키를 리스너에 등록합니다. - var ret = globalShortcut.register('ctrl+x', function() { - console.log('ctrl+x is pressed'); + // 'CommandOrControl+X' 단축키를 리스너에 등록합니다. + var ret = globalShortcut.register('CommandOrControl+X', function() { + console.log('CommandOrControl+X is pressed'); }); if (!ret) { @@ -24,12 +24,12 @@ app.on('ready', function() { } // 단축키가 등록되었는지 확인합니다. - console.log(globalShortcut.isRegistered('ctrl+x')); + console.log(globalShortcut.isRegistered('CommandOrControl+X')); }); app.on('will-quit', function() { // 단축키의 등록을 해제합니다. - globalShortcut.unregister('ctrl+x'); + globalShortcut.unregister('CommandOrControl+X'); // 모든 단축키의 등록을 해제합니다. globalShortcut.unregisterAll(); diff --git a/docs-translations/ko-KR/api/ipc-renderer.md b/docs-translations/ko-KR/api/ipc-renderer.md index 0d43b157d16..786b03b41c8 100644 --- a/docs-translations/ko-KR/api/ipc-renderer.md +++ b/docs-translations/ko-KR/api/ipc-renderer.md @@ -71,7 +71,7 @@ 메인 프로세스는 `ipcMain` 모듈을 통해 `channel` 이벤트를 리스닝 할 수 있고, `event.returnValue`로 회신 할 수 있습니다. -__참고:__ 동기 메서드는 모든 랜더러 프로세스의 작업을 일시 중단시킵니다. 사용 목적이 +**참고:** 동기 메서드는 모든 랜더러 프로세스의 작업을 일시 중단시킵니다. 사용 목적이 확실하지 않다면 사용하지 않는 것이 좋습니다. ### `ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...])` diff --git a/docs-translations/ko-KR/api/menu-item.md b/docs-translations/ko-KR/api/menu-item.md index 0e723fc657d..f2f495a7e59 100644 --- a/docs-translations/ko-KR/api/menu-item.md +++ b/docs-translations/ko-KR/api/menu-item.md @@ -14,7 +14,7 @@ * `options` Object * `click` Function - 메뉴 아이템이 클릭될 때 `click(menuItem, browserWindow)` 형태로 호출 되는 콜백 함수 - * `role` String - 메뉴 아이템의 액션을 정의합니다. 이 속성을 지정하면 `click` + * `role` String - 메뉴 아이템의 액션을 정의합니다; 이 속성을 지정하면 `click` 속성이 무시됩니다. * `type` String - `MenuItem`의 타입 `normal`, `separator`, `submenu`, `checkbox` 또는 `radio`를 사용할 수 있습니다. 만약 값이 `Menu`가 아니면 @@ -23,18 +23,22 @@ * `sublabel` String * `accelerator` [Accelerator](accelerator.md) * `icon` [NativeImage](native-image.md) - * `enabled` Boolean - * `visible` Boolean - * `checked` Boolean - * `submenu` Menu - 보조메뉴를 설정합니다. `type`이 `submenu`일 경우 반드시 - 설정해야 합니다. 일반 메뉴 아이템일 경우 생략할 수 있습니다. + * `enabled` Boolean - 만약 `false`로 설정되면, 메뉴 아이템이 회색으로 변하며 + 클릭할 수 없게 됩니다. + * `visible` Boolean - 만약 `false`로 설정되면, 메뉴 아이템이 완전히 숨겨집니다. + * `checked` Boolean - 반드시 `checkbox` 또는 `radio` 타입의 메뉴 아이템에만 + 지정해야 합니다. + * `submenu` Menu - 반드시 `submenu` 타입의 메뉴 아이템에만 지정해야 합니다. 만약 + `submenu`가 지정되면 `type: 'submenu'`는 생략될 수 있습니다. 만약 값이 `Menu`가 + 아닐 경우 `Menu.buildFromTemplate`을 통해 자동적으로 변환됩니다. * `id` String - 현재 메뉴 아이템에 대해 유일키를 지정합니다. 이 키는 이후 `position` 옵션에서 사용할 수 있습니다. * `position` String - 미리 지정한 `id`를 이용하여 메뉴 아이템의 위치를 세밀하게 조정합니다. -메뉴 아이템을 생성할 때, 다음 목록과 일치하는 표준 동작은 수동으로 직접 구현하는 대신 -`role` 속성을 지정하여 고유 OS 경험을 최대한 살릴 수 있습니다. +어떠한 메뉴 아이템이 표준 롤에 일치한다면, `role`을 지정하는 것이 동작을 `click` +함수로 일일이 구현하려 시도하는 것 보다 더 좋을 수 있습니다. 빌트-인 `role` 동작은 +더 좋은 네이티브 경험을 제공할 것입니다. `role` 속성은 다음 값을 가질 수 있습니다: @@ -57,3 +61,21 @@ OS X에서의 `role`은 다음 값을 추가로 가질 수 있습니다: * `window` - 부 메뉴를 가지는 "Window" 메뉴 * `help` - 부 메뉴를 가지는 "Help" 메뉴 * `services` - 부 메뉴를 가지는 "Services" 메뉴 + +## Instance Properties + +다음 속성들은 존재하는 `MenuItem`에서 계속 변경될 수 있습니다: + + * `enabled` Boolean + * `visible` Boolean + * `checked` Boolean + +이 속성들의 의미는 위 옵션에서 설명한 것과 같습니다. + +`checkbox` 메뉴 아이템은 선택될 때 해당 아이템의 `checked` 속성을 통해 활성화 그리고 +비활성화 상태인지를 표시합니다. 또한 `click` 함수를 지정하여 추가적인 작업을 할 수도 +있습니다. + +`radio` 메뉴 아이템은 클릭되었을 때 `checked` 속성을 활성화 합니다. 그리고 같은 +메뉴의 인접한 모든 다른 아이템은 비활성화됩니다. 또한 `click` 함수를 지정하여 추가적인 +작업을 할 수도 있습니다. diff --git a/docs-translations/ko-KR/api/tray.md b/docs-translations/ko-KR/api/tray.md index d82b0a9d7e4..28a44199c00 100644 --- a/docs-translations/ko-KR/api/tray.md +++ b/docs-translations/ko-KR/api/tray.md @@ -74,7 +74,7 @@ appIcon.setContextMenu(contextMenu); 트레이 아이콘이 클릭될 때 발생하는 이벤트입니다. -__주의:__ `bounds`는 OS X 와 Windows에서만 작동합니다. +**참고:** `bounds`는 OS X 와 Windows에서만 작동합니다. ### Event: 'right-click' _OS X_ _Windows_ diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index 69fa0c5a767..a40a22070f3 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -80,6 +80,9 @@ "on"으로 지정하면 `webview` 페이지 내에서 `require`와 `process 객체`같은 node.js API를 사용할 수 있습니다. 이를 지정하면 내부에서 로우레벨 리소스에 접근할 수 있습니다. +**참고:** Node 통합 기능은 `webview`에서 부모 윈도우가 해당 옵션이 비활성화되어있는 +경우 항상 비활성화됩니다. + ### `plugins` ```html @@ -595,7 +598,10 @@ Returns: ```javascript webview.addEventListener('new-window', function(e) { - require('electron').shell.openExternal(e.url); + var protocol = require('url').parse(e.url).protocol; + if (protocol === 'http:' || protocol === 'https:') { + require('electron').shell.openExternal(e.url); + } }); ``` diff --git a/docs-translations/ko-KR/api/window-open.md b/docs-translations/ko-KR/api/window-open.md index f81c6b65be8..8969160c9ac 100644 --- a/docs-translations/ko-KR/api/window-open.md +++ b/docs-translations/ko-KR/api/window-open.md @@ -22,6 +22,9 @@ `features` 문자열은 표준 브라우저의 포맷을 따르고 있지만, 각 기능은 `BrowserWindow`의 옵션이어야 합니다. +**참고:** Node 통합 기능은 열린 `window`에서 부모 윈도우가 해당 옵션이 +비활성화되어있는 경우 항상 비활성화됩니다. + ### `window.opener.postMessage(message, targetOrigin)` * `message` String diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index dd64e724517..e07832d62cd 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -23,8 +23,7 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 ## JavaScript -* 하드 탭(hard tabs) 대신 소프트 탭(2 spaces) 들여쓰기를 사용합니다. -* 항상 구문의 끝은 `;`으로 마쳐야 합니다. +* [표준](http://npm.im/standard) JavaScript 코딩 스타일을 사용합니다. * Google의 코딩 스타일에도 맞추기 위해 파일의 끝에는 **절대** 개행을 삽입해선 안됩니다. * 파일 이름의 공백은 `_`대신에 `-`을 사용하여야 합니다. 예를 들어 `file_name.js`를 `file-name.js`로 고쳐야합니다. 왜냐하면 diff --git a/docs-translations/ko-KR/development/setting-up-symbol-server.md b/docs-translations/ko-KR/development/setting-up-symbol-server.md index 014f383ab29..e2bcd173a4b 100644 --- a/docs-translations/ko-KR/development/setting-up-symbol-server.md +++ b/docs-translations/ko-KR/development/setting-up-symbol-server.md @@ -21,7 +21,7 @@ http://54.249.141.255:8086/atom-shell/symbols 입니다. 일단 이 URL에 직 ## Windbg에서 심볼 서버 사용하기 Windbg 심볼 경로는 구분자와 `*` 문자로 설정되어 있습니다. Electron 심볼 서버만 -사용하려면 심볼 경로의 엔트리를 추가해야 합니다. (__참고:__ `c:\code\symbols` +사용하려면 심볼 경로의 엔트리를 추가해야 합니다. (**참고:** `c:\code\symbols` 디렉터리 경로를 PC가 원하는 경로로 수정할 수 있습니다): ``` diff --git a/docs-translations/ko-KR/tutorial/debugging-main-process.md b/docs-translations/ko-KR/tutorial/debugging-main-process.md index 43b24c79b3a..58c671f132e 100644 --- a/docs-translations/ko-KR/tutorial/debugging-main-process.md +++ b/docs-translations/ko-KR/tutorial/debugging-main-process.md @@ -19,7 +19,7 @@ ## node-inspector로 디버깅 하기 -__참고:__ Electron은 현재 node-inspector 유틸리티와 호환성 문제가 있습니다. 따라서 +**참고:** Electron은 현재 node-inspector 유틸리티와 호환성 문제가 있습니다. 따라서 node-inspector 콘솔 내에서 메인 프로세스의 `process` 객체를 탐색할 경우 크래시가 발생할 수 있습니다. diff --git a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md index ddeadc04e91..91b906c0a19 100644 --- a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md +++ b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md @@ -14,7 +14,7 @@ Windows, Linux, OS X 운영체제 모두 기본적으로 어플리케이션에 통해 개발자가 편리하게 데스크톱 알림을 사용할 수 있는 기능을 제공합니다. 데스크톱 알림은 운영체제의 네이티브 알림 API를 사용하여 표시합니다. -__참고:__ 이 API는 HTML5 API이기 때문에 랜더러 프로세스에서만 사용할 수 있습니다. +**참고:** 이 API는 HTML5 API이기 때문에 랜더러 프로세스에서만 사용할 수 있습니다. ```javascript var myNotification = new Notification('Title', { diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index c319f344b63..fefe6751303 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -4,11 +4,11 @@ Electron은 v0.34.0 버전부터 앱 패키지를 Mac App Store(MAS)에 제출 되었습니다. 이 가이드는 어플리케이션을 앱 스토어에 등록하는 방법과 빌드의 한계에 대한 설명을 제공합니다. -__참고:__ v0.36.0 버전부터 어플리케이션이 샌드박스화 된 상태로 실행되면 GPU 작동을 +**참고:** v0.36.0 버전부터 어플리케이션이 샌드박스화 된 상태로 실행되면 GPU 작동을 방지하는 버그가 있었습니다. 따라서 이 버그가 고쳐지기 전까진 v0.35.x 버전을 사용하는 것을 권장합니다. 이 버그에 관한 자세한 사항은 [issue #3871][issue-3871]를 참고하세요. -__참고:__ Mac App Store에 어플리케이션을 등록하려면 +**참고:** Mac App Store에 어플리케이션을 등록하려면 [Apple Developer Program][developer-program]에 등록되어 있어야 하며 비용이 발생할 수 있습니다. diff --git a/docs-translations/ko-KR/tutorial/using-widevine-cdm-plugin.md b/docs-translations/ko-KR/tutorial/using-widevine-cdm-plugin.md index b9fec886769..698503df484 100644 --- a/docs-translations/ko-KR/tutorial/using-widevine-cdm-plugin.md +++ b/docs-translations/ko-KR/tutorial/using-widevine-cdm-plugin.md @@ -8,7 +8,7 @@ Electron은 라이센스상의 문제로 Widevine CDM 플러그인을 직접 제 따라서 플러그인을 얻으려면 먼저 사용할 Electron 빌드의 아키텍쳐와 버전에 맞춰 공식 Chrome 브라우저를 설치해야 합니다. -__참고:__ Chrome 브라우저의 메이저 버전은 Electron에서 사용하는 Chrome 버전과 +**참고:** Chrome 브라우저의 메이저 버전은 Electron에서 사용하는 Chrome 버전과 같습니다, 만약 그렇지 않다면 `navigator.plugins`가 로드됐더라도 정상적으로 작동하지 않습니다. @@ -42,7 +42,7 @@ Linux에선 플러그인 바이너리들이 Chrome 브라우저와 함께 제공 `widevinecdmadapter`의 위치를 전달하고 플러그인의 버전을 `--widevine-cdm-version` 스위치에 전달해야 합니다. -__참고:__ `widevinecdmadapter` 바이너리가 Electron으로 전달되어도, `widevinecdm` +**참고:** `widevinecdmadapter` 바이너리가 Electron으로 전달되어도, `widevinecdm` 바이너리는 옆에 같이 두어야 합니다. 커맨드 라인 스위치들은 `app` 모듈의 `ready` 이벤트가 발생하기 전에 전달되어야 합니다. From 492a7d0ffe847f9fe2a5daf258c542c6b6f63a66 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 4 Apr 2016 01:01:01 +0900 Subject: [PATCH 0410/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/faq/electron-faq.md | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/docs-translations/ko-KR/faq/electron-faq.md b/docs-translations/ko-KR/faq/electron-faq.md index 40d10f293f4..ea9953fcd4c 100644 --- a/docs-translations/ko-KR/faq/electron-faq.md +++ b/docs-translations/ko-KR/faq/electron-faq.md @@ -144,19 +144,6 @@ npm uninstall -g electron 모듈이며, 반면 `electron.webFrame` 모듈은 랜더러 프로세스에서만 사용할 수 있는 모듈입니다. -## 왜 저의 앱 배경이 투명하죠? - -Electron `0.37.3` 부터, 기본 클라이언트 배경색이 `투명색`으로 변경되었습니다. -간단히 HTML에서 배경색을 지정합니다: - -```html - -``` - [memory-management]: https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management [variable-scope]: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx [electron-module]: https://www.npmjs.com/package/electron From 5ffa30a563d870e10aba42a2223e51f845a8d05a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 16:49:15 -0700 Subject: [PATCH 0411/1265] Update submodules for new org --- .gitmodules | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index c6e53ed39a6..6164ed8b970 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,21 +1,21 @@ [submodule "vendor/brightray"] path = vendor/brightray - url = https://github.com/atom/brightray.git + url = https://github.com/electron/brightray.git [submodule "vendor/node"] path = vendor/node - url = https://github.com/atom/node.git + url = https://github.com/electron/node.git [submodule "vendor/depot_tools"] path = vendor/depot_tools url = https://chromium.googlesource.com/chromium/tools/depot_tools.git [submodule "vendor/breakpad"] path = vendor/breakpad - url = https://github.com/atom/chromium-breakpad.git + url = https://github.com/electron/chromium-breakpad.git [submodule "vendor/native_mate"] path = vendor/native_mate url = https://github.com/zcbenz/native-mate.git [submodule "vendor/crashpad"] path = vendor/crashpad - url = https://github.com/atom/crashpad.git + url = https://github.com/electron/crashpad.git [submodule "vendor/requests"] path = vendor/requests url = https://github.com/kennethreitz/requests From 102f7e8e332b018bb500fd006d1a8208e8cae768 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 16:49:59 -0700 Subject: [PATCH 0412/1265] Update docs for new org --- .../es/development/atom-shell-vs-node-webkit.md | 2 +- .../es/development/build-instructions-linux.md | 2 +- .../es/development/build-instructions-osx.md | 2 +- docs-translations/es/development/coding-style.md | 2 +- docs-translations/es/styleguide.md | 2 +- docs-translations/es/tutorial/quick-start.md | 2 +- .../es/tutorial/using-selenium-and-webdriver.md | 4 ++-- docs-translations/fr-FR/styleguide.md | 2 +- docs-translations/jp/api/frameless-window.md | 2 +- docs-translations/jp/api/synopsis.md | 2 +- .../jp/tutorial/devtools-extension.md | 2 +- .../jp/tutorial/mac-app-store-submission-guide.md | 2 +- docs-translations/jp/tutorial/quick-start.md | 6 +++--- .../jp/tutorial/using-native-node-modules.md | 2 +- .../jp/tutorial/using-selenium-and-webdriver.md | 2 +- docs-translations/ko-KR/api/frameless-window.md | 2 +- docs-translations/ko-KR/api/menu.md | 2 +- docs-translations/ko-KR/api/synopsis.md | 2 +- .../ko-KR/development/atom-shell-vs-node-webkit.md | 2 +- .../ko-KR/development/build-instructions-linux.md | 2 +- .../ko-KR/development/build-instructions-osx.md | 2 +- .../development/build-instructions-windows.md | 2 +- .../ko-KR/development/coding-style.md | 2 +- docs-translations/ko-KR/styleguide.md | 2 +- .../ko-KR/tutorial/devtools-extension.md | 2 +- .../tutorial/mac-app-store-submission-guide.md | 2 +- docs-translations/ko-KR/tutorial/quick-start.md | 6 +++--- .../ko-KR/tutorial/using-native-node-modules.md | 4 ++-- .../pt-BR/development/build-instructions-linux.md | 2 +- .../pt-BR/development/coding-style.md | 2 +- docs-translations/pt-BR/tutorial/quick-start.md | 2 +- .../pt-BR/tutorial/using-native-node-modules.md | 4 ++-- docs-translations/uk-UA/styleguide.md | 2 +- docs-translations/zh-CN/api/menu.md | 2 +- docs-translations/zh-CN/api/synopsis.md | 2 +- .../zh-CN/development/atom-shell-vs-node-webkit.md | 2 +- .../zh-CN/development/build-instructions-linux.md | 2 +- .../zh-CN/development/build-instructions-osx.md | 2 +- .../development/build-instructions-windows.md | 4 ++-- .../zh-CN/development/coding-style.md | 2 +- .../tutorial/desktop-environment-integration.md | 14 +++++++------- .../zh-CN/tutorial/devtools-extension.md | 2 +- .../tutorial/mac-app-store-submission-guide.md | 2 +- docs-translations/zh-CN/tutorial/quick-start.md | 8 ++++---- .../zh-CN/tutorial/using-native-node-modules.md | 2 +- .../zh-CN/tutorial/using-selenium-and-webdriver.md | 2 +- .../zh-TW/tutorial/devtools-extension.md | 2 +- docs-translations/zh-TW/tutorial/quick-start.md | 8 ++++---- .../zh-TW/tutorial/using-native-node-modules.md | 2 +- .../zh-TW/tutorial/using-selenium-and-webdriver.md | 2 +- docs/api/frameless-window.md | 2 +- docs/api/menu.md | 2 +- docs/api/synopsis.md | 2 +- docs/development/atom-shell-vs-node-webkit.md | 2 +- docs/development/build-instructions-linux.md | 2 +- docs/development/build-instructions-osx.md | 2 +- docs/development/build-instructions-windows.md | 4 ++-- docs/development/coding-style.md | 2 +- docs/styleguide.md | 2 +- docs/tutorial/devtools-extension.md | 2 +- docs/tutorial/mac-app-store-submission-guide.md | 2 +- docs/tutorial/quick-start.md | 6 +++--- docs/tutorial/using-native-node-modules.md | 4 ++-- docs/tutorial/using-selenium-and-webdriver.md | 2 +- 64 files changed, 88 insertions(+), 88 deletions(-) diff --git a/docs-translations/es/development/atom-shell-vs-node-webkit.md b/docs-translations/es/development/atom-shell-vs-node-webkit.md index 434e6765807..8d017067329 100644 --- a/docs-translations/es/development/atom-shell-vs-node-webkit.md +++ b/docs-translations/es/development/atom-shell-vs-node-webkit.md @@ -31,4 +31,4 @@ Si usted es un usuario experimentado NW.js, usted debe estar familiarizado con e Mediante el uso de la característica [multi-contexto](http://strongloop.com/strongblog/whats-new-node-js-v0-12-multiple-context-execution/) de Node, Electron no introduce un nuevo contexto JavaScript en páginas web.Resultados de búsqueda -[node-bindings]: https://github.com/atom/electron/tree/master/atom/common +[node-bindings]: https://github.com/electron/electron/tree/master/atom/common diff --git a/docs-translations/es/development/build-instructions-linux.md b/docs-translations/es/development/build-instructions-linux.md index 28ad828fa70..58beef4ecf0 100644 --- a/docs-translations/es/development/build-instructions-linux.md +++ b/docs-translations/es/development/build-instructions-linux.md @@ -29,7 +29,7 @@ Si usted planea construir Electron en una máquina virtual, necesitará un disp #Obteniendo el codigo -`$ git clone https://github.com/atom/electron.git` +`$ git clone https://github.com/electron/electron.git` #Bootstrapping (Arranque) diff --git a/docs-translations/es/development/build-instructions-osx.md b/docs-translations/es/development/build-instructions-osx.md index 6e2d7b7f392..2ac3641e836 100644 --- a/docs-translations/es/development/build-instructions-osx.md +++ b/docs-translations/es/development/build-instructions-osx.md @@ -13,7 +13,7 @@ Si está utilizando Python descargado de Homebrew, también es necesario instal #Obtener el Código -`$ git clone https://github.com/atom/electron.git` +`$ git clone https://github.com/electron/electron.git` #Bootstrapping (arranque) diff --git a/docs-translations/es/development/coding-style.md b/docs-translations/es/development/coding-style.md index de02a33a86d..e2f364d8b9c 100644 --- a/docs-translations/es/development/coding-style.md +++ b/docs-translations/es/development/coding-style.md @@ -34,4 +34,4 @@ siguientes reglas: Al crear una nueva API, nosotros deberíamos preferir usar metodos `get` y `set` en vez de usar el estilo de jQuery que utiliza una sola función. Por ejemplo, se prefiere `.getText()` y `.setText()` por sobre `.text([text])`. Hay una -[discusión](https://github.com/atom/electron/issues/46) sobre esto. +[discusión](https://github.com/electron/electron/issues/46) sobre esto. diff --git a/docs-translations/es/styleguide.md b/docs-translations/es/styleguide.md index 4948035ffff..18fa1aa3bb3 100644 --- a/docs-translations/es/styleguide.md +++ b/docs-translations/es/styleguide.md @@ -43,7 +43,7 @@ Para agregar otro set (o un set parcial): - Actualizar el `README.md` dentro del subdirectorio del lenguaje apuntando a los archivos que has traducido. - Agregar un enlace al folder de tu traducción en la sección principal Electron -[README](https://github.com/atom/electron#documentation-translations). +[README](https://github.com/electron/electron#documentation-translations). ## Leyendo la Documentación de Electron diff --git a/docs-translations/es/tutorial/quick-start.md b/docs-translations/es/tutorial/quick-start.md index b038f7cb08d..2e6825669fa 100644 --- a/docs-translations/es/tutorial/quick-start.md +++ b/docs-translations/es/tutorial/quick-start.md @@ -147,4 +147,4 @@ En OS X: $ ./Electron.app/Contents/MacOS/Electron your-app/ ``` -`Electron.app` es parte del paquete de release de Electron, puedes descargarlo [aquí](https://github.com/atom/electron/releases). +`Electron.app` es parte del paquete de release de Electron, puedes descargarlo [aquí](https://github.com/electron/electron/releases). diff --git a/docs-translations/es/tutorial/using-selenium-and-webdriver.md b/docs-translations/es/tutorial/using-selenium-and-webdriver.md index 7d998905705..919a889d38d 100644 --- a/docs-translations/es/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/es/tutorial/using-selenium-and-webdriver.md @@ -8,7 +8,7 @@ De [ChromeDriver - WebDriver for Chrome][chrome-driver]: > el protocolo de WebDriver para Chromium. Se encuentra en desarrollo por los miembros de > Chromium y WebDriver. -En la página de [lanzamientos](https://github.com/atom/electron/releases) de Electron encontrarás paquetes de `chromedriver`. +En la página de [lanzamientos](https://github.com/electron/electron/releases) de Electron encontrarás paquetes de `chromedriver`. ## Ajustando parámetros con WebDriverJs @@ -65,7 +65,7 @@ driver.quit(); ## Workflow -Para probar tu aplicación sin recompilar Electron, simplemente [copia](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) las fuentes de tu aplicación en el directorio de recursos de Electron. +Para probar tu aplicación sin recompilar Electron, simplemente [copia](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md) las fuentes de tu aplicación en el directorio de recursos de Electron. [chrome-driver]: https://sites.google.com/a/chromium.org/chromedriver/ diff --git a/docs-translations/fr-FR/styleguide.md b/docs-translations/fr-FR/styleguide.md index 5fe781773c1..b683ee68aad 100644 --- a/docs-translations/fr-FR/styleguide.md +++ b/docs-translations/fr-FR/styleguide.md @@ -43,7 +43,7 @@ Pour ajouter une nouvelle langue (ou commencer) : - Traduire les fichiers. - Mettre à jour le `README.md` à l'intérieur du dossier de langue en mettant les liens vers les fichiers traduits. -- Ajouter un lien vers le nouveau dossier de langue dans le [README](https://github.com/atom/electron#documentation-translations) +- Ajouter un lien vers le nouveau dossier de langue dans le [README](https://github.com/electron/electron#documentation-translations) principal d'Electron. ## Lire la documentation d'Electron diff --git a/docs-translations/jp/api/frameless-window.md b/docs-translations/jp/api/frameless-window.md index 0b1e055602f..4478387877e 100644 --- a/docs-translations/jp/api/frameless-window.md +++ b/docs-translations/jp/api/frameless-window.md @@ -29,7 +29,7 @@ var win = new BrowserWindow({ transparent: true, frame: false }); ### 制限 -* 透明領域をクリックすることはできません。この問題を解決するためにウィンドウの輪郭を設定するAPIを導入しようとしています。詳細は、[our issue](https://github.com/atom/electron/issues/1335) を参照してください。 +* 透明領域をクリックすることはできません。この問題を解決するためにウィンドウの輪郭を設定するAPIを導入しようとしています。詳細は、[our issue](https://github.com/electron/electron/issues/1335) を参照してください。 * 透明なウィンドウはサイズ変更できません。いくつかのプラットフォーム上では、`resizable`の`true`設定は、いくつかのプラットフォーム上で、動作を停止する透明ウィンドウを作成するかもしれません。 * `blur`フィルターはウェブページのみに適用され、ウィンドウの下のコンテンツ(例えば、ユーザーのシステム上でほかのアプリケーションを開く)に、ぼやける効果を適用する方法はありません。 * Windows オペレーティングシステム上では、DMMが無効のとき透明なウィンドウは動作しません。 diff --git a/docs-translations/jp/api/synopsis.md b/docs-translations/jp/api/synopsis.md index 683f5611eb1..89d8973a14b 100644 --- a/docs-translations/jp/api/synopsis.md +++ b/docs-translations/jp/api/synopsis.md @@ -65,4 +65,4 @@ require('electron').hideInternalModules() [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface [desctructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment -[issue-387]: https://github.com/atom/electron/issues/387 +[issue-387]: https://github.com/electron/electron/issues/387 diff --git a/docs-translations/jp/tutorial/devtools-extension.md b/docs-translations/jp/tutorial/devtools-extension.md index 85eff391a43..2c8816a666f 100644 --- a/docs-translations/jp/tutorial/devtools-extension.md +++ b/docs-translations/jp/tutorial/devtools-extension.md @@ -4,7 +4,7 @@ DevToolsエクステンションのために、ソースコードをダウンローし、`BrowserWindow.addDevToolsExtension` APIを使って読み込みます。読み込んだエクステンションは維持されているので、ウィンドウを作成するとき、毎回APIをコールする必要はありません。 -** NOTE: React DevTools は動作しません。issue https://github.com/atom/electron/issues/915 でフォローしています** +** NOTE: React DevTools は動作しません。issue https://github.com/electron/electron/issues/915 でフォローしています** 例えば、[React DevTools Extension](https://github.com/facebook/react-devtools)を使うために、最初にソースコードをダウンロードする必要があります。 diff --git a/docs-translations/jp/tutorial/mac-app-store-submission-guide.md b/docs-translations/jp/tutorial/mac-app-store-submission-guide.md index 47d7a76b925..c4bbf0706eb 100644 --- a/docs-translations/jp/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/jp/tutorial/mac-app-store-submission-guide.md @@ -140,5 +140,5 @@ ERNの同意を取得するには、 [How to legally submit an app to Apple’s [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/atom/electron/issues/3871 +[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ diff --git a/docs-translations/jp/tutorial/quick-start.md b/docs-translations/jp/tutorial/quick-start.md index 4f2e5c9a52e..4a4a7f1692d 100644 --- a/docs-translations/jp/tutorial/quick-start.md +++ b/docs-translations/jp/tutorial/quick-start.md @@ -151,7 +151,7 @@ $ ./electron/electron your-app/ $ ./Electron.app/Contents/MacOS/Electron your-app/ ``` -`Electron.app` は Electron のリリースパッケージの一部で、[ここ](https://github.com/atom/electron/releases) からダウンロードできます。 +`Electron.app` は Electron のリリースパッケージの一部で、[ここ](https://github.com/electron/electron/releases) からダウンロードできます。 ### Run as a distribution @@ -159,13 +159,13 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ### 試してみよう -このチュートリアルのコードは [`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) リポジトリから clone して実行できます。 +このチュートリアルのコードは [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) リポジトリから clone して実行できます。 **注記**:例を試すには、[Git](https://git-scm.com) と [Node.js](https://nodejs.org/en/download/) ([npm](https://npmjs.org) もこれに含まれています) が必要です。 ```bash # Clone the repository -$ git clone https://github.com/atom/electron-quick-start +$ git clone https://github.com/electron/electron-quick-start # Go into the repository $ cd electron-quick-start # Install dependencies and run the app diff --git a/docs-translations/jp/tutorial/using-native-node-modules.md b/docs-translations/jp/tutorial/using-native-node-modules.md index c0bce4fab8d..eced3d36a2b 100644 --- a/docs-translations/jp/tutorial/using-native-node-modules.md +++ b/docs-translations/jp/tutorial/using-native-node-modules.md @@ -4,7 +4,7 @@ Electronは、ネイティブのNodeモジュールをサポートしていま ## ネイティブNodeモジュールとの互換性 -Nodeが新しいV8バージョンを使用し始めた時、Nativeモジュールは動作しなくなるかもしれません。ElectronでNativeモジュールが動作するかどうかを確認するために、Electronで使用する内部のNodeバージョンがサポートしているかを確認すべきです。ElectronでNodeが使用しているバージョンを確認するには、[releases](https://github.com/atom/electron/releases)ページを見るか、`process.version` (例えば [Quick Start](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md)を見てください)を使用してください。 +Nodeが新しいV8バージョンを使用し始めた時、Nativeモジュールは動作しなくなるかもしれません。ElectronでNativeモジュールが動作するかどうかを確認するために、Electronで使用する内部のNodeバージョンがサポートしているかを確認すべきです。ElectronでNodeが使用しているバージョンを確認するには、[releases](https://github.com/electron/electron/releases)ページを見るか、`process.version` (例えば [Quick Start](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md)を見てください)を使用してください。 Nodeの複数バージョンを簡単にサポートできるので、あなたのモジュールに [NAN](https://github.com/nodejs/nan/) を使うことを検討してください。古いバージョンからElectronで動作するNodeの新しいバージョンへ移植するのに役立ちます。 diff --git a/docs-translations/jp/tutorial/using-selenium-and-webdriver.md b/docs-translations/jp/tutorial/using-selenium-and-webdriver.md index a1fd0f21d7f..0250436844b 100644 --- a/docs-translations/jp/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/jp/tutorial/using-selenium-and-webdriver.md @@ -112,7 +112,7 @@ client ## ワークフロー -Electronはリビルドせずにアプリケーションをテストするために、単純にElectronのリソースディレクトリでアプリのソースを[配置します](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md)。 +Electronはリビルドせずにアプリケーションをテストするために、単純にElectronのリソースディレクトリでアプリのソースを[配置します](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md)。 もしくは、アプリのフォルダーを引数にしてElectronバイナリを実行します。これは、Electronのリソースディレクトリにアプリをコピー&ペーストする必要性を除きます。 diff --git a/docs-translations/ko-KR/api/frameless-window.md b/docs-translations/ko-KR/api/frameless-window.md index 94c87ca9a64..3d3e63312c7 100644 --- a/docs-translations/ko-KR/api/frameless-window.md +++ b/docs-translations/ko-KR/api/frameless-window.md @@ -39,7 +39,7 @@ var win = new BrowserWindow({ transparent: true, frame: false }); * 투명한 영역을 통과하여 클릭할 수 없습니다. 우리는 이 문제를 해결하기 위해 API를 제공할 예정이며 자세한 내용은 - [이슈](https://github.com/atom/electron/issues/1335)를 참고하세요. + [이슈](https://github.com/electron/electron/issues/1335)를 참고하세요. * 투명한 창은 크기를 조절할 수 없습니다. `resizable` 속성을 `true`로 할 경우 몇몇 플랫폼에선 크래시가 일어납니다. * `blur` 필터는 웹 페이지에서만 적용됩니다. 윈도우 아래 컨텐츠에는 블러 효과를 적용할 diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 44fe461bcc2..7f1a5af16c6 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -382,4 +382,4 @@ OS X에선 지정한 어플리케이션 메뉴에 상관없이 메뉴의 첫번 ``` [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html -[setMenu]: https://github.com/atom/electron/blob/master/docs-translations/ko-KR/api/browser-window.md#winsetmenumenu-linux-windows +[setMenu]: https://github.com/electron/electron/blob/master/docs-translations/ko-KR/api/browser-window.md#winsetmenumenu-linux-windows diff --git a/docs-translations/ko-KR/api/synopsis.md b/docs-translations/ko-KR/api/synopsis.md index 8f59d12c1ce..b392f206c13 100644 --- a/docs-translations/ko-KR/api/synopsis.md +++ b/docs-translations/ko-KR/api/synopsis.md @@ -79,4 +79,4 @@ require('electron').hideInternalModules() [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface [destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment -[issue-387]: https://github.com/atom/electron/issues/387 +[issue-387]: https://github.com/electron/electron/issues/387 diff --git a/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md b/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md index 22e8e375646..f59c7ceb70b 100644 --- a/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md +++ b/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md @@ -44,4 +44,4 @@ __4. 다중 컨텍스트__ Node의 [다중 컨텍스트](http://strongloop.com/strongblog/whats-new-node-js-v0-12-multiple-context-execution/)를 사용하기 때문에 Electron은 웹 페이지의 새로운 JavaScript 컨텍스트를 생성하지 않습니다. -[node-bindings]: https://github.com/atom/electron/tree/master/atom/common +[node-bindings]: https://github.com/electron/electron/tree/master/atom/common diff --git a/docs-translations/ko-KR/development/build-instructions-linux.md b/docs-translations/ko-KR/development/build-instructions-linux.md index 377a7977a85..e5712fcac99 100644 --- a/docs-translations/ko-KR/development/build-instructions-linux.md +++ b/docs-translations/ko-KR/development/build-instructions-linux.md @@ -44,7 +44,7 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring- ## 코드 가져오기 ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## 부트 스트랩 diff --git a/docs-translations/ko-KR/development/build-instructions-osx.md b/docs-translations/ko-KR/development/build-instructions-osx.md index 142cdaca4df..1a1a13a4576 100644 --- a/docs-translations/ko-KR/development/build-instructions-osx.md +++ b/docs-translations/ko-KR/development/build-instructions-osx.md @@ -15,7 +15,7 @@ ## 코드 가져오기 ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## 부트 스트랩 diff --git a/docs-translations/ko-KR/development/build-instructions-windows.md b/docs-translations/ko-KR/development/build-instructions-windows.md index 3c7932479ec..4d1c57a33b4 100644 --- a/docs-translations/ko-KR/development/build-instructions-windows.md +++ b/docs-translations/ko-KR/development/build-instructions-windows.md @@ -27,7 +27,7 @@ Studio를 사용할 수 없습니다. 하지만 여전히 Electron을 개발할 ## 코드 가져오기 ```powershell -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## 부트 스트랩 diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index dd64e724517..73bb65f458b 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -44,5 +44,5 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 새로운 API를 만들 땐 getter, setter스타일 대신 jQuery의 one-function 스타일을 사용해야 합니다. 예를 들어 `.getText()`와 `.setText(text)`대신에 `.text([text])` -형식으로 설계하면 됩니다. 포럼에 이 문제에 대한 [논의](https://github.com/atom/electron/issues/46)가 +형식으로 설계하면 됩니다. 포럼에 이 문제에 대한 [논의](https://github.com/electron/electron/issues/46)가 진행되고 있습니다. diff --git a/docs-translations/ko-KR/styleguide.md b/docs-translations/ko-KR/styleguide.md index 8327cd3c1dd..12dae10ec94 100644 --- a/docs-translations/ko-KR/styleguide.md +++ b/docs-translations/ko-KR/styleguide.md @@ -41,7 +41,7 @@ Electron 문서를 작성하는 규칙은 다음과 같습니다. 유지합니다. - 문서를 번역합니다. - 언어 디렉터리 내의 `README.md`에 번역한 문서의 링크를 추가합니다. -- 메인(upstream) Electron의 [README](https://github.com/atom/electron#documentation-translations)에 +- 메인(upstream) Electron의 [README](https://github.com/electron/electron#documentation-translations)에 번역된 언어 디렉터리의 링크를 추가합니다. ## Electron 문서 읽기 diff --git a/docs-translations/ko-KR/tutorial/devtools-extension.md b/docs-translations/ko-KR/tutorial/devtools-extension.md index 655c6ed7d5c..b45f88892d8 100644 --- a/docs-translations/ko-KR/tutorial/devtools-extension.md +++ b/docs-translations/ko-KR/tutorial/devtools-extension.md @@ -8,7 +8,7 @@ 한가지 주의할 점은 확장 기능 사용시 창이 생성될 때 마다 일일이 해당 API를 호출할 필요는 없습니다. -**주의: 현재 React DevTools은 작동하지 않습니다. https://github.com/atom/electron/issues/915 이슈를 참고하세요!** +**주의: 현재 React DevTools은 작동하지 않습니다. https://github.com/electron/electron/issues/915 이슈를 참고하세요!** 다음 예제는 [React DevTools Extension](https://github.com/facebook/react-devtools)을 사용합니다. diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index c319f344b63..e29c1cbc46e 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -164,5 +164,5 @@ ERN의 승인을 얻는 방법은, 다음 글을 참고하는 것이 좋습니 [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/atom/electron/issues/3871 +[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ diff --git a/docs-translations/ko-KR/tutorial/quick-start.md b/docs-translations/ko-KR/tutorial/quick-start.md index 82d359e0de5..d13e22351bc 100644 --- a/docs-translations/ko-KR/tutorial/quick-start.md +++ b/docs-translations/ko-KR/tutorial/quick-start.md @@ -186,7 +186,7 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ``` 어플리케이션 실행파일은 `Electron`의 release 패키지에 포함되어 있습니다. -[여기](https://github.com/atom/electron/releases)에서 다운로드 받을 수 있습니다. +[여기](https://github.com/electron/electron/releases)에서 다운로드 받을 수 있습니다. ### 배포용 실행 파일 만들기 @@ -195,7 +195,7 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ### 미리 작성된 앱 실행하기 -[`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) +[`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) 저장소를 클론하면 이 문서에서 작성한 예제 앱을 바로 실행해 볼 수 있습니다. **참고**: 이 예제를 실행시키려면 [Git](https://git-scm.com)과 @@ -206,7 +206,7 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ```bash # 저장소를 클론합니다 -$ git clone https://github.com/atom/electron-quick-start +$ git clone https://github.com/electron/electron-quick-start # 저장소 안으로 들어갑니다 $ cd electron-quick-start # 어플리케이션의 종속성 모듈을 설치한 후 실행합니다 diff --git a/docs-translations/ko-KR/tutorial/using-native-node-modules.md b/docs-translations/ko-KR/tutorial/using-native-node-modules.md index d1c3aa167ad..ed00d7ae608 100644 --- a/docs-translations/ko-KR/tutorial/using-native-node-modules.md +++ b/docs-translations/ko-KR/tutorial/using-native-node-modules.md @@ -9,9 +9,9 @@ Electron의 V8 버전에 맞춰 네이티브 모듈을 다시 빌드하고 헤 네이티브 모듈은 node.js가 새로운 V8 버전을 사용함으로 인해 작동하지 않을 수 있습니다. 사용하는 네이티브 모듈이 Electron에 맞춰 작동할 수 있도록 하려면 Electron에서 사용하는 node.js의 버전을 확인할 필요가 있습니다. Electron에서 사용하는 node 버전은 -[releases](https://github.com/atom/electron/releases)에서 확인할 수 있으며 +[releases](https://github.com/electron/electron/releases)에서 확인할 수 있으며 `process.version`을 출력하여 버전을 확인할 수도 있습니다. -([시작하기](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md)의 +([시작하기](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md)의 예제를 참고하세요) 혹시 직접 만든 네이티브 모듈이 있다면 [NAN](https://github.com/nodejs/nan/) 모듈을 diff --git a/docs-translations/pt-BR/development/build-instructions-linux.md b/docs-translations/pt-BR/development/build-instructions-linux.md index 532892a4083..5e8ffe44780 100644 --- a/docs-translations/pt-BR/development/build-instructions-linux.md +++ b/docs-translations/pt-BR/development/build-instructions-linux.md @@ -43,7 +43,7 @@ de um container de tamanho fixo de pelo menos 25 gigabytes. ## Baixando o Código ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping diff --git a/docs-translations/pt-BR/development/coding-style.md b/docs-translations/pt-BR/development/coding-style.md index b0068d56892..acfdf7e3dbd 100644 --- a/docs-translations/pt-BR/development/coding-style.md +++ b/docs-translations/pt-BR/development/coding-style.md @@ -23,4 +23,4 @@ Para CoffeeScript, seguimos o [Guia de Estilo] (https://github.com/styleguide/ja Ao criar uma nova API, devemos preferencialmente utilizar métodos getters e setters em vez do estilo de uma função única do jQuery. Por exemplo, `.getText()` e `.setText(text)` são preferenciais a `.text([text])`. Existe uma -[discussão](https://github.com/atom/electron/issues/46) sobre este assunto. +[discussão](https://github.com/electron/electron/issues/46) sobre este assunto. diff --git a/docs-translations/pt-BR/tutorial/quick-start.md b/docs-translations/pt-BR/tutorial/quick-start.md index 1b1d6942379..76b128df5d0 100644 --- a/docs-translations/pt-BR/tutorial/quick-start.md +++ b/docs-translations/pt-BR/tutorial/quick-start.md @@ -180,7 +180,7 @@ $ ./Electron.app/Contents/MacOS/Electron seu-app/ ``` `Electron.app` aqui é uma parte do pacote de lançamento do Electron, você pode baixa-lo -[aqui](https://github.com/atom/electron/releases). +[aqui](https://github.com/electron/electron/releases). ### Executar como uma distribuição diff --git a/docs-translations/pt-BR/tutorial/using-native-node-modules.md b/docs-translations/pt-BR/tutorial/using-native-node-modules.md index c5e9eeddd61..8cc883046eb 100644 --- a/docs-translations/pt-BR/tutorial/using-native-node-modules.md +++ b/docs-translations/pt-BR/tutorial/using-native-node-modules.md @@ -12,8 +12,8 @@ Para ter certeza que o módulo que você está interessado em trabalhar com o Electron, você deve checar se a versão do Node utilizada é compatível com a usada pelo Electron. Você pode verificar qual versão do Node foi utilizada no Electron olhando na -página [releases](https://github.com/atom/electron/releases) ou usando -`process.version` (veja [Quick Start](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md) +página [releases](https://github.com/electron/electron/releases) ou usando +`process.version` (veja [Quick Start](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md) por exemplo). Considere usar [NAN](https://github.com/nodejs/nan/) para seus próprios diff --git a/docs-translations/uk-UA/styleguide.md b/docs-translations/uk-UA/styleguide.md index 04159670001..2a5907ec4ea 100644 --- a/docs-translations/uk-UA/styleguide.md +++ b/docs-translations/uk-UA/styleguide.md @@ -39,7 +39,7 @@ or [writing Electron documentation](#writing-electron-documentation). - 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). +- Add a link to your translation directory on the main Electron [README](https://github.com/electron/electron#documentation-translations). ## Читання документації Electron diff --git a/docs-translations/zh-CN/api/menu.md b/docs-translations/zh-CN/api/menu.md index d0cfeeb33eb..1997a293d24 100644 --- a/docs-translations/zh-CN/api/menu.md +++ b/docs-translations/zh-CN/api/menu.md @@ -352,4 +352,4 @@ Property List Files][AboutInformationPropertyListFiles] . [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html [setMenu]: -https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows \ No newline at end of file +https://github.com/electron/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows \ No newline at end of file diff --git a/docs-translations/zh-CN/api/synopsis.md b/docs-translations/zh-CN/api/synopsis.md index a1a2a6d0122..014d5893c73 100644 --- a/docs-translations/zh-CN/api/synopsis.md +++ b/docs-translations/zh-CN/api/synopsis.md @@ -68,4 +68,4 @@ require('electron').hideInternalModules() [2]:https://github.com/heyunjiang/electron/blob/master/docs/tutorial/using-native-node-modules.md [3]:https://github.com/heyunjiang/electron/blob/master/docs/tutorial/quick-start.md#the-main-process [4]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment - [5]:https://github.com/atom/electron/issues/387 \ No newline at end of file + [5]:https://github.com/electron/electron/issues/387 \ No newline at end of file diff --git a/docs-translations/zh-CN/development/atom-shell-vs-node-webkit.md b/docs-translations/zh-CN/development/atom-shell-vs-node-webkit.md index beea91e3ff1..68fddb11d23 100644 --- a/docs-translations/zh-CN/development/atom-shell-vs-node-webkit.md +++ b/docs-translations/zh-CN/development/atom-shell-vs-node-webkit.md @@ -28,4 +28,4 @@ __4. 多上下文__ 通过使用 Node 的[多上下文](http://strongloop.com/strongblog/whats-new-node-js-v0-12-multiple-context-execution/)特性,Electron不需要在网页中引入新的 JavaScript 上下文。 -[node-bindings]: https://github.com/atom/electron/tree/master/atom/common +[node-bindings]: https://github.com/electron/electron/tree/master/atom/common diff --git a/docs-translations/zh-CN/development/build-instructions-linux.md b/docs-translations/zh-CN/development/build-instructions-linux.md index 0f76e78b9a5..9815aeb03e5 100644 --- a/docs-translations/zh-CN/development/build-instructions-linux.md +++ b/docs-translations/zh-CN/development/build-instructions-linux.md @@ -36,7 +36,7 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring- ## 获取代码 ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping diff --git a/docs-translations/zh-CN/development/build-instructions-osx.md b/docs-translations/zh-CN/development/build-instructions-osx.md index 15485e57acc..98f6648a359 100644 --- a/docs-translations/zh-CN/development/build-instructions-osx.md +++ b/docs-translations/zh-CN/development/build-instructions-osx.md @@ -15,7 +15,7 @@ ## 获取代码 ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping diff --git a/docs-translations/zh-CN/development/build-instructions-windows.md b/docs-translations/zh-CN/development/build-instructions-windows.md index 7b11dc7f57f..2e2ee38638b 100644 --- a/docs-translations/zh-CN/development/build-instructions-windows.md +++ b/docs-translations/zh-CN/development/build-instructions-windows.md @@ -25,7 +25,7 @@ ## 获取代码 ```powershell -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping @@ -76,7 +76,7 @@ $ python script\cpplint.py ```powershell $ python script\test.py ``` -在构建 debug 时为 Tests包含原生模块 (例如 `runas`) 将不会执行(详情 [#2558](https://github.com/atom/electron/issues/2558)), 但是它们在构建 release 会起效. +在构建 debug 时为 Tests包含原生模块 (例如 `runas`) 将不会执行(详情 [#2558](https://github.com/electron/electron/issues/2558)), 但是它们在构建 release 会起效. 运行 release 构建使用 : diff --git a/docs-translations/zh-CN/development/coding-style.md b/docs-translations/zh-CN/development/coding-style.md index 6652466b970..4136ae4805b 100644 --- a/docs-translations/zh-CN/development/coding-style.md +++ b/docs-translations/zh-CN/development/coding-style.md @@ -20,4 +20,4 @@ C++ 代码中用到了许多 Chromium 中的接口和数据类型,所以希望 ## API 命名 当新建一个 API 时,我们倾向于使用 getters 和 setters 而不是 jQuery 单函数的命名方式,比如 `.getText()` 和 `.setText(text)` - 而不是 `.text([text])`。这里有关于该规则的[讨论记录](https://github.com/atom/electron/issues/46)。 + 而不是 `.text([text])`。这里有关于该规则的[讨论记录](https://github.com/electron/electron/issues/46)。 diff --git a/docs-translations/zh-CN/tutorial/desktop-environment-integration.md b/docs-translations/zh-CN/tutorial/desktop-environment-integration.md index 614aeed708f..f069065cd65 100644 --- a/docs-translations/zh-CN/tutorial/desktop-environment-integration.md +++ b/docs-translations/zh-CN/tutorial/desktop-environment-integration.md @@ -149,19 +149,19 @@ window.setDocumentEdited(true); [1]:https://camo.githubusercontent.com/3310597e01f138b1d687e07aa618c50908a88dec/687474703a2f2f692e6d73646e2e6d6963726f736f66742e636f6d2f64796e696d672f49433432303533382e706e67 [2]: https://cloud.githubusercontent.com/assets/639601/5069610/2aa80758-6e97-11e4-8cfb-c1a414a10774.png - [3]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/app.md - [4]: https://github.com/atom/electron/blob/master/docs/tutorial/clearrecentdocuments + [3]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/app.md + [4]: https://github.com/electron/electron/blob/master/docs/tutorial/clearrecentdocuments [5]: https://msdn.microsoft.com/en-us/library/windows/desktop/ee872121%28v=vs.85%29.aspx [6]: https://cloud.githubusercontent.com/assets/639601/5069962/6032658a-6e9c-11e4-9953-aa84006bdfff.png [7]: https://camo.githubusercontent.com/30154e0cc36acfc968ac9ae076a8f0d6600dd736/687474703a2f2f692e6d73646e2e6d6963726f736f66742e636f6d2f64796e696d672f49433432303533392e706e67 - [8]: https://github.com/atom/electron/blob/master/docs/api/app.md#appsetusertaskstasks + [8]: https://github.com/electron/electron/blob/master/docs/api/app.md#appsetusertaskstasks [9]: https://camo.githubusercontent.com/098cb0f52f27084a80ec6429e51a195df3d8c333/68747470733a2f2f692d6d73646e2e7365632e732d6d7366742e636f6d2f64796e696d672f49433432303534302e706e67 - [10]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/browser-window.md + [10]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md [11]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [12]: https://camo.githubusercontent.com/b6f54e2bc3206ebf8e08dd029529af9ec84d58ae/68747470733a2f2f68656c702e7562756e74752e636f6d2f636f6d6d756e6974792f556e6974794c61756e6368657273416e644465736b746f7046696c65733f616374696f6e3d41747461636846696c6526646f3d676574267461726765743d73686f7274637574732e706e67 [13]: https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png [14]: https://cloud.githubusercontent.com/assets/639601/5081747/4a0a589e-6f0f-11e4-803f-91594716a546.png - [15]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/browser-window.md + [15]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md [16]: https://cloud.githubusercontent.com/assets/639601/5082061/670a949a-6f14-11e4-987a-9aaa04b23c1d.png - [17]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/browser-window.md - [18]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/browser-window.md + [17]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md + [18]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md diff --git a/docs-translations/zh-CN/tutorial/devtools-extension.md b/docs-translations/zh-CN/tutorial/devtools-extension.md index 0270eae2955..e35a971e1c7 100644 --- a/docs-translations/zh-CN/tutorial/devtools-extension.md +++ b/docs-translations/zh-CN/tutorial/devtools-extension.md @@ -4,7 +4,7 @@ 对于大多数DevTools的扩展,你可以直接下载源码,然后通过 `BrowserWindow.addDevToolsExtension` API 加载它们。Electron会记住已经加载了哪些扩展,所以你不需要每次创建一个新window时都调用 `BrowserWindow.addDevToolsExtension` API。 -** 注:React DevTools目前不能直接工作,详情留意 [https://github.com/atom/electron/issues/915](https://github.com/atom/electron/issues/915) ** +** 注:React DevTools目前不能直接工作,详情留意 [https://github.com/electron/electron/issues/915](https://github.com/electron/electron/issues/915) ** 例如,要用[React DevTools Extension](https://github.com/facebook/react-devtools),你得先下载他的源码: diff --git a/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md b/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md index 45cff454a96..e7c7af817aa 100644 --- a/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/zh-CN/tutorial/mac-app-store-submission-guide.md @@ -143,5 +143,5 @@ ERN)][ern-tutorial]. [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/atom/electron/issues/3871 +[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ \ No newline at end of file diff --git a/docs-translations/zh-CN/tutorial/quick-start.md b/docs-translations/zh-CN/tutorial/quick-start.md index c4d668417e4..8d948036bfa 100644 --- a/docs-translations/zh-CN/tutorial/quick-start.md +++ b/docs-translations/zh-CN/tutorial/quick-start.md @@ -127,7 +127,7 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ 在你完成了你的应用后,你可以按照[应用部署][4]指导发布一个版本,并且以已经打包好的形式运行应用。 - [1]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/ipc-main-process.md - [2]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/api/remote.md - [3]: https://github.com/atom/electron/releases - [4]: https://github.com/atom/electron/blob/master/docs-translations/zh-CN/tutorial/application-distribution.md + [1]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/ipc-main-process.md + [2]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/remote.md + [3]: https://github.com/electron/electron/releases + [4]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/tutorial/application-distribution.md diff --git a/docs-translations/zh-CN/tutorial/using-native-node-modules.md b/docs-translations/zh-CN/tutorial/using-native-node-modules.md index 0fe67d4a08a..ef85313e0c2 100644 --- a/docs-translations/zh-CN/tutorial/using-native-node-modules.md +++ b/docs-translations/zh-CN/tutorial/using-native-node-modules.md @@ -4,7 +4,7 @@ Electron 同样也支持原生模块,但由于和官方的 Node 相比使用 ## 原生Node模块的兼容性 -当 Node 开始换新的V8引擎版本时,原生模块可能“坏”掉。为确保一切工作正常,你需要检查你想要使用的原生模块是否被 Electron 内置的 Node 支持。你可以在[这里](https://github.com/atom/electron/releases)查看 Electron 内置的 Node 版本,或者使用 `process.version` (参考:[快速入门](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md))查看。 +当 Node 开始换新的V8引擎版本时,原生模块可能“坏”掉。为确保一切工作正常,你需要检查你想要使用的原生模块是否被 Electron 内置的 Node 支持。你可以在[这里](https://github.com/electron/electron/releases)查看 Electron 内置的 Node 版本,或者使用 `process.version` (参考:[快速入门](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md))查看。 考虑到 [NAN](https://github.com/nodejs/nan/) 可以使你的开发更容易对多版本 Node 的支持,建议使用它来开发你自己的模块。你也可以使用 [NAN](https://github.com/nodejs/nan/) 来移植旧的模块到新的 Nod e版本,以使它们可以在新的 Electron 下良好工作。 diff --git a/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md b/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md index 0a0b29c854f..4c1db714bde 100644 --- a/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/zh-CN/tutorial/using-selenium-and-webdriver.md @@ -112,7 +112,7 @@ client ## 工作流程 -无需重新编译 Electron,只要把 app 的源码放到 [Electron的资源目录](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) 里就可直接开始测试了。 +无需重新编译 Electron,只要把 app 的源码放到 [Electron的资源目录](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md) 里就可直接开始测试了。 当然,你也可以在运行 Electron 时传入参数指定你 app 的所在文件夹。这步可以免去你拷贝-粘贴你的 app 到 Electron 的资源目录。 diff --git a/docs-translations/zh-TW/tutorial/devtools-extension.md b/docs-translations/zh-TW/tutorial/devtools-extension.md index 1a419fb8375..e65ebbcfa1a 100644 --- a/docs-translations/zh-TW/tutorial/devtools-extension.md +++ b/docs-translations/zh-TW/tutorial/devtools-extension.md @@ -4,7 +4,7 @@ 多數的 DevTools 擴充可以簡單地透過下載原始碼然後使用 `BrowserWindow.addDevToolsExtension` API 來載入它們,已載入的擴充套件會被記住,如此一來你就不用每次建立一個視窗的時候就要呼叫 API。 -** 注意: React DevTools 無法使用,參考 [issue](https://github.com/atom/electron/issues/915) ** +** 注意: React DevTools 無法使用,參考 [issue](https://github.com/electron/electron/issues/915) ** 例如使用 [React DevTools Extension](https://github.com/facebook/react-devtools),首先你需要下載它的原始碼: diff --git a/docs-translations/zh-TW/tutorial/quick-start.md b/docs-translations/zh-TW/tutorial/quick-start.md index 8c5c701f17d..af98a0e580c 100644 --- a/docs-translations/zh-TW/tutorial/quick-start.md +++ b/docs-translations/zh-TW/tutorial/quick-start.md @@ -153,20 +153,20 @@ $ ./electron/electron your-app/ $ ./Electron.app/Contents/MacOS/Electron your-app/ ``` -`Electron.app` 裡面是 Electron 釋出包,你可以在[這裡](https://github.com/atom/electron/releases)下載到。 +`Electron.app` 裡面是 Electron 釋出包,你可以在[這裡](https://github.com/electron/electron/releases)下載到。 # 作為版本發行 -在你完成了你的應用程式後,你可以依照 [應用部署](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) 指南發布一個版本,並且運行已經打包好的應用程式。 +在你完成了你的應用程式後,你可以依照 [應用部署](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md) 指南發布一個版本,並且運行已經打包好的應用程式。 # 試試這個範例 -Clone 與執行本篇教學的程式碼,它們都放在 [`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) 這個 repository。 +Clone 與執行本篇教學的程式碼,它們都放在 [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) 這個 repository。 **Note**: 執行這個範例需要 [Git](https://git-scm.com) 以及 [Node.js](https://nodejs.org/en/download/) (其中包括 [npm](https://npmjs.org)) 在你的作業系統。 ```bash # Clone the repository -$ git clone https://github.com/atom/electron-quick-start +$ git clone https://github.com/electron/electron-quick-start # Go into the repository $ cd electron-quick-start # Install dependencies and run the app diff --git a/docs-translations/zh-TW/tutorial/using-native-node-modules.md b/docs-translations/zh-TW/tutorial/using-native-node-modules.md index 82febb6d5ab..8d90b82d02f 100644 --- a/docs-translations/zh-TW/tutorial/using-native-node-modules.md +++ b/docs-translations/zh-TW/tutorial/using-native-node-modules.md @@ -4,7 +4,7 @@ ## 原生 Node 模組的相容性 -原生模組可能在 Node 開始使用一個新版本的 V8 時毀損,為了確保你想要用的模組能正確與 Electron 一起運行,你應該檢查是否支援 Electron 內部 Node 版本,你可以查看 [releases](https://github.com/atom/electron/releases) 或是使用 `process.version` (範例請見 [Quick Start](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md)) 來檢查哪個 Node 版本是現在的 Electron 使用的。 +原生模組可能在 Node 開始使用一個新版本的 V8 時毀損,為了確保你想要用的模組能正確與 Electron 一起運行,你應該檢查是否支援 Electron 內部 Node 版本,你可以查看 [releases](https://github.com/electron/electron/releases) 或是使用 `process.version` (範例請見 [Quick Start](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md)) 來檢查哪個 Node 版本是現在的 Electron 使用的。 你可以考慮給你自己的模組使用 [NAN](https://github.com/nodejs/nan/),因為它可以較輕易的支援多種版本的 Node,它對於移植舊的模組到新版本的 Node 以便與 Electron 一起運作也是很有用的。 diff --git a/docs-translations/zh-TW/tutorial/using-selenium-and-webdriver.md b/docs-translations/zh-TW/tutorial/using-selenium-and-webdriver.md index 8f90597ddae..e312ffa4a1d 100644 --- a/docs-translations/zh-TW/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/zh-TW/tutorial/using-selenium-and-webdriver.md @@ -116,7 +116,7 @@ client ## 運作流程 -要在不重新建置 Electron 的情況下測試你的應用程式,只需要 [放置](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) 你的應用程式到 Electron 的資源目錄中即可。 +要在不重新建置 Electron 的情況下測試你的應用程式,只需要 [放置](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md) 你的應用程式到 Electron 的資源目錄中即可。 或者,傳遞一個指向你應用程式資料夾的參數來透過你的 Electron 執行檔運行,這會減少複製你應用程式到 Electron 資源資料夾的需求。 diff --git a/docs/api/frameless-window.md b/docs/api/frameless-window.md index 22309fa5862..3c26a36b032 100644 --- a/docs/api/frameless-window.md +++ b/docs/api/frameless-window.md @@ -38,7 +38,7 @@ var win = new BrowserWindow({ transparent: true, frame: false }); ### Limitations * You can not click through the transparent area. We are going to introduce an - API to set window shape to solve this, see [our issue](https://github.com/atom/electron/issues/1335) for details. + API to set window shape to solve this, see [our issue](https://github.com/electron/electron/issues/1335) for details. * Transparent windows are not resizable. Setting `resizable` to `true` may make a transparent window stop working on some platforms. * The `blur` filter only applies to the web page, so there is no way to apply diff --git a/docs/api/menu.md b/docs/api/menu.md index d7f32c787fd..2c1374fc888 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -387,4 +387,4 @@ Menu: ``` [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html -[setMenu]: https://github.com/atom/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows +[setMenu]: https://github.com/electron/electron/blob/master/docs/api/browser-window.md#winsetmenumenu-linux-windows diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index f2009e75520..015674c2ef6 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -80,4 +80,4 @@ require('electron').hideInternalModules() [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface [destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment -[issue-387]: https://github.com/atom/electron/issues/387 +[issue-387]: https://github.com/electron/electron/issues/387 diff --git a/docs/development/atom-shell-vs-node-webkit.md b/docs/development/atom-shell-vs-node-webkit.md index 76fa5d57d28..3ec11b78b7d 100644 --- a/docs/development/atom-shell-vs-node-webkit.md +++ b/docs/development/atom-shell-vs-node-webkit.md @@ -47,4 +47,4 @@ By using the [multi-context](http://strongloop.com/strongblog/whats-new-node-js- feature of Node, Electron doesn't introduce a new JavaScript context in web pages. -[node-bindings]: https://github.com/atom/electron/tree/master/atom/common +[node-bindings]: https://github.com/electron/electron/tree/master/atom/common diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index df0943050f7..79fbc501489 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -41,7 +41,7 @@ device container of at least 25 gigabytes in size. ## Getting the Code ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping diff --git a/docs/development/build-instructions-osx.md b/docs/development/build-instructions-osx.md index 598aa01c440..02bdb72e227 100644 --- a/docs/development/build-instructions-osx.md +++ b/docs/development/build-instructions-osx.md @@ -16,7 +16,7 @@ following python modules: ## Getting the Code ```bash -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping diff --git a/docs/development/build-instructions-windows.md b/docs/development/build-instructions-windows.md index 06ce696a9e3..73526b36258 100644 --- a/docs/development/build-instructions-windows.md +++ b/docs/development/build-instructions-windows.md @@ -27,7 +27,7 @@ building with Visual Studio will come in the future. ## Getting the Code ```powershell -$ git clone https://github.com/atom/electron.git +$ git clone https://github.com/electron/electron.git ``` ## Bootstrapping @@ -84,7 +84,7 @@ $ python script\test.py ``` Tests that include native modules (e.g. `runas`) can't be executed with the -debug build (see [#2558](https://github.com/atom/electron/issues/2558) for +debug build (see [#2558](https://github.com/electron/electron/issues/2558) for details), but they will work with the release build. To run the tests with the release build use: diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index 422a4226df6..52ae3c299a5 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -44,4 +44,4 @@ etc. When creating a new API, we should prefer getters and setters instead of jQuery's one-function style. For example, `.getText()` and `.setText(text)` are preferred to `.text([text])`. There is a -[discussion](https://github.com/atom/electron/issues/46) on this. +[discussion](https://github.com/electron/electron/issues/46) on this. diff --git a/docs/styleguide.md b/docs/styleguide.md index 6b745b988b3..28ebaa18b66 100644 --- a/docs/styleguide.md +++ b/docs/styleguide.md @@ -40,7 +40,7 @@ To add another set (or partial set): - 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). +- Add a link to your translation directory on the main Electron [README](https://github.com/electron/electron#documentation-translations). ## Reading Electron Documentation diff --git a/docs/tutorial/devtools-extension.md b/docs/tutorial/devtools-extension.md index 7c7ea7d64a2..1791c045920 100644 --- a/docs/tutorial/devtools-extension.md +++ b/docs/tutorial/devtools-extension.md @@ -8,7 +8,7 @@ the `BrowserWindow.addDevToolsExtension` API to load them. The loaded extensions will be remembered so you don't need to call the API every time when creating a window. -** NOTE: React DevTools does not work, follow the issue here https://github.com/atom/electron/issues/915 ** +** NOTE: React DevTools does not work, follow the issue here https://github.com/electron/electron/issues/915 ** For example, to use the [React DevTools Extension](https://github.com/facebook/react-devtools) , first you need to download its source code: diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index 91a10d40eb1..ec8d8653ca0 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -163,5 +163,5 @@ ERN)][ern-tutorial]. [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/atom/electron/issues/3871 +[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md index 684c72c6669..2a41d6356a8 100644 --- a/docs/tutorial/quick-start.md +++ b/docs/tutorial/quick-start.md @@ -184,7 +184,7 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ``` `Electron.app` here is part of the Electron's release package, you can download -it from [here](https://github.com/atom/electron/releases). +it from [here](https://github.com/electron/electron/releases). ### Run as a distribution @@ -194,14 +194,14 @@ and then executing the packaged app. ### Try this Example -Clone and run the code in this tutorial by using the [`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) +Clone and run the code in this tutorial by using the [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) repository. **Note**: Running this requires [Git](https://git-scm.com) and [Node.js](https://nodejs.org/en/download/) (which includes [npm](https://npmjs.org)) on your system. ```bash # Clone the repository -$ git clone https://github.com/atom/electron-quick-start +$ git clone https://github.com/electron/electron-quick-start # Go into the repository $ cd electron-quick-start # Install dependencies and run the app diff --git a/docs/tutorial/using-native-node-modules.md b/docs/tutorial/using-native-node-modules.md index 2defedd7418..f73c1cde1f0 100644 --- a/docs/tutorial/using-native-node-modules.md +++ b/docs/tutorial/using-native-node-modules.md @@ -10,8 +10,8 @@ Native modules might break when Node starts using a new version of V8. To make sure the module you're interested in will work with Electron, you should check if it supports the internal Node version used by Electron. You can check what version of Node is used in Electron by looking it up in -the [releases](https://github.com/atom/electron/releases) page or by using -`process.version` (see [Quick Start](https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md) +the [releases](https://github.com/electron/electron/releases) page or by using +`process.version` (see [Quick Start](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md) for example). Consider using [NAN](https://github.com/nodejs/nan/) for your own modules, since diff --git a/docs/tutorial/using-selenium-and-webdriver.md b/docs/tutorial/using-selenium-and-webdriver.md index 2d296548dd9..32a96cd84b7 100644 --- a/docs/tutorial/using-selenium-and-webdriver.md +++ b/docs/tutorial/using-selenium-and-webdriver.md @@ -122,7 +122,7 @@ client ## Workflow To test your application without rebuilding Electron, simply -[place](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) +[place](https://github.com/electron/electron/blob/master/docs/tutorial/application-distribution.md) your app source into Electron's resource directory. Alternatively, pass an argument to run with your electron binary that points to From fc84c952f20b44bda10231f7ce26649361b6429f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 16:50:30 -0700 Subject: [PATCH 0413/1265] Update source code for new org --- atom/browser/atom_browser_main_parts.cc | 2 +- default_app/index.html | 4 ++-- default_app/main.js | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index f45f6492a84..25338c0df17 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -49,7 +49,7 @@ AtomBrowserMainParts::~AtomBrowserMainParts() { // Leak the JavascriptEnvironment on exit. // This is to work around the bug that V8 would be waiting for background // tasks to finish on exit, while somehow it waits forever in Electron, more - // about this can be found at https://github.com/atom/electron/issues/4767. + // about this can be found at https://github.com/electron/electron/issues/4767. // On the other handle there is actually no need to gracefully shutdown V8 // on exit in the main process, we already ensured all necessary resources get // cleaned up, and it would make quitting faster. diff --git a/default_app/index.html b/default_app/index.html index 80c347eff6d..5c8440cfdad 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -112,13 +112,13 @@

You can read the guide in Electron's to learn how to write one. diff --git a/default_app/main.js b/default_app/main.js index 43c8d729804..cf71277c19d 100644 --- a/default_app/main.js +++ b/default_app/main.js @@ -147,7 +147,7 @@ app.once('ready', function () { label: 'Documentation', click: function () { shell.openExternal( - `https://github.com/atom/electron/tree/v${process.versions.electron}/docs#readme` + `https://github.com/electron/electron/tree/v${process.versions.electron}/docs#readme` ) } }, @@ -160,7 +160,7 @@ app.once('ready', function () { { label: 'Search Issues', click: function () { - shell.openExternal('https://github.com/atom/electron/issues') + shell.openExternal('https://github.com/electron/electron/issues') } } ] @@ -257,7 +257,7 @@ function loadApplicationPackage (packagePath) { dialog.showErrorBox( 'Error opening app', 'The app provided is not a valid Electron app, please read the docs on how to write one:\n' + - `https://github.com/atom/electron/tree/v${process.versions.electron}/docs + `https://github.com/electron/electron/tree/v${process.versions.electron}/docs ${e.toString()}` ) From b553981644ffc169efd651e8927956766cb7d080 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 31 Mar 2016 16:51:42 -0700 Subject: [PATCH 0414/1265] Update readme and contributing guide for new org --- CONTRIBUTING-ko.md | 4 ++-- CONTRIBUTING.md | 4 ++-- README-ko.md | 26 +++++++++++++------------- README.md | 24 ++++++++++++------------ 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/CONTRIBUTING-ko.md b/CONTRIBUTING-ko.md index 52887c8d38a..1c938d434b1 100644 --- a/CONTRIBUTING-ko.md +++ b/CONTRIBUTING-ko.md @@ -12,7 +12,7 @@ ## 이슈 제출 -* [여기](https://github.com/atom/electron/issues/new)에서 새로운 이슈를 만들 수 +* [여기](https://github.com/electron/electron/issues/new)에서 새로운 이슈를 만들 수 있습니다. 하지만 이슈를 작성하기 전에 아래의 항목들을 숙지하고 가능한한 이슈 보고에 대해 최대한 많은 정보와 자세한 설명을 포함해야 합니다. 가능하다면 다음 항목을 포함해야 합니다: @@ -23,7 +23,7 @@ * 추가로 다음 사항을 준수하면 이슈를 해결하는데 큰 도움이 됩니다: * 스크린샷 또는 GIF 애니메이션 이미지들 * 터미널에 출력된 에러의 내용 또는 개발자 도구, 알림창에 뜬 내용 - * [Cursory search](https://github.com/atom/electron/issues?utf8=✓&q=is%3Aissue+)를 + * [Cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+)를 통해 이미 비슷한 내용의 이슈가 등록되어있는지 확인 ## Pull Request 하기 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7c221863dc..d6bc3cb2d67 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,7 +12,7 @@ propose changes to this document in a pull request. ## Submitting Issues -* You can create an issue [here](https://github.com/atom/electron/issues/new), +* You can create an issue [here](https://github.com/electron/electron/issues/new), but before doing that please read the notes below and include as many details as possible with your report. If you can, please include: * The version of Electron you are using @@ -22,7 +22,7 @@ possible with your report. If you can, please include: * Other things that will help resolve your issue: * Screenshots and animated GIFs * Error output that appears in your terminal, dev tools or as an alert - * Perform a [cursory search](https://github.com/atom/electron/issues?utf8=✓&q=is%3Aissue+) + * Perform a [cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+) to see if a similar issue has already been submitted ## Submitting Pull Requests diff --git a/README-ko.md b/README-ko.md index 5bef003966d..246898d2a14 100644 --- a/README-ko.md +++ b/README-ko.md @@ -5,7 +5,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/) -### [Electron](https://github.com/atom/electron/) 한국어 참조문서 +### [Electron](https://github.com/electron/electron/) 한국어 참조문서 :zap: *프레임워크 이름이 Atom Shell에서 Electron으로 변경되었습니다* :zap: @@ -24,7 +24,7 @@ Electron에 대한 중요한 알림을 받고 싶다면 Twitter에서 ## 다운로드 Linux, Windows, OS X 용으로 미리 빌드된 Electron 바이너리와 디버그 심볼이 준비되어 -있습니다. [releases](https://github.com/atom/electron/releases) 페이지에서 받아 볼 +있습니다. [releases](https://github.com/electron/electron/releases) 페이지에서 받아 볼 수 있습니다. 또한 [`npm`](https://docs.npmjs.com/)을 통해 미리 빌드된 Electron 바이너리를 설치할 @@ -44,25 +44,25 @@ npm install electron-prebuilt --save-dev ## 참조 문서 -[Docs](https://github.com/atom/electron/tree/master/docs/README.md)에 개발 지침과 +[Docs](https://github.com/electron/electron/tree/master/docs/README.md)에 개발 지침과 API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝트에 기여하는법 또한 문서에 포함되어 있으니 참고하시기 바랍니다. ## 참조 문서 (번역) -- [브라질 포르투갈어](https://github.com/atom/electron/tree/master/docs-translations/pt-BR) -- [한국어](https://github.com/atom/electron/tree/master/docs-translations/ko-KR) -- [일본어](https://github.com/atom/electron/tree/master/docs-translations/jp) -- [스페인어](https://github.com/atom/electron/tree/master/docs-translations/es) -- [중국어 간체](https://github.com/atom/electron/tree/master/docs-translations/zh-CN) -- [중국어 번체](https://github.com/atom/electron/tree/master/docs-translations/zh-TW) -- [우크라이나어](https://github.com/atom/electron/tree/master/docs-translations/uk-UA) -- [러시아어](https://github.com/atom/electron/tree/master/docs-translations/ru-RU) -- [프랑스어](https://github.com/atom/electron/tree/master/docs-translations/fr-FR) +- [브라질 포르투갈어](https://github.com/electron/electron/tree/master/docs-translations/pt-BR) +- [한국어](https://github.com/electron/electron/tree/master/docs-translations/ko-KR) +- [일본어](https://github.com/electron/electron/tree/master/docs-translations/jp) +- [스페인어](https://github.com/electron/electron/tree/master/docs-translations/es) +- [중국어 간체](https://github.com/electron/electron/tree/master/docs-translations/zh-CN) +- [중국어 번체](https://github.com/electron/electron/tree/master/docs-translations/zh-TW) +- [우크라이나어](https://github.com/electron/electron/tree/master/docs-translations/uk-UA) +- [러시아어](https://github.com/electron/electron/tree/master/docs-translations/ru-RU) +- [프랑스어](https://github.com/electron/electron/tree/master/docs-translations/fr-FR) ## 시작하기 -[`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) +[`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) 저장소를 클론하여 Electron을 간단히 접해볼 수 있습니다. ## 커뮤니티 diff --git a/README.md b/README.md index f7b5cb79000..6894ef9882f 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ behavior to atom@github.com. ## Downloads Prebuilt binaries and debug symbols of Electron for Linux, Windows and OS X can -be found on the [releases](https://github.com/atom/electron/releases) page. +be found on the [releases](https://github.com/electron/electron/releases) page. You can also use [`npm`](https://docs.npmjs.com/) to install prebuilt electron binaries: @@ -42,24 +42,24 @@ npm install electron-prebuilt --save-dev ## Documentation Guides and the API reference are located in the -[docs](https://github.com/atom/electron/tree/master/docs) directory. It also +[docs](https://github.com/electron/electron/tree/master/docs) directory. It also contains documents describing how to build and contribute to Electron. ## Documentation Translations -- [Brazilian Portuguese](https://github.com/atom/electron/tree/master/docs-translations/pt-BR) -- [Korean](https://github.com/atom/electron/tree/master/docs-translations/ko-KR) -- [Japanese](https://github.com/atom/electron/tree/master/docs-translations/jp) -- [Spanish](https://github.com/atom/electron/tree/master/docs-translations/es) -- [Simplified Chinese](https://github.com/atom/electron/tree/master/docs-translations/zh-CN) -- [Traditional Chinese](https://github.com/atom/electron/tree/master/docs-translations/zh-TW) -- [Ukrainian](https://github.com/atom/electron/tree/master/docs-translations/uk-UA) -- [Russian](https://github.com/atom/electron/tree/master/docs-translations/ru-RU) -- [French](https://github.com/atom/electron/tree/master/docs-translations/fr-FR) +- [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR) +- [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR) +- [Japanese](https://github.com/electron/electron/tree/master/docs-translations/jp) +- [Spanish](https://github.com/electron/electron/tree/master/docs-translations/es) +- [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN) +- [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW) +- [Ukrainian](https://github.com/electron/electron/tree/master/docs-translations/uk-UA) +- [Russian](https://github.com/electron/electron/tree/master/docs-translations/ru-RU) +- [French](https://github.com/electron/electron/tree/master/docs-translations/fr-FR) ## Quick Start -Clone and run the [`atom/electron-quick-start`](https://github.com/atom/electron-quick-start) +Clone and run the [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) repository to see a minimal Electron app in action. ## Community From c2bcf8cbdea7838b8c36362acf3a5d4ba9eba553 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 4 Apr 2016 12:18:37 -0700 Subject: [PATCH 0415/1265] Update links for new Electron org --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6894ef9882f..52e290f53ef 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) -[![Travis Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) +[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) -[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies) +[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/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: @@ -59,7 +59,7 @@ contains documents describing how to build and contribute to Electron. ## Quick Start -Clone and run the [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) +Clone and run the [`electron/electron-quick-start`](https://github.com/electron/electron-quick-start) repository to see a minimal Electron app in action. ## Community From f12f87d6f0c330a2516bba61c29b63d5aac59687 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Mon, 4 Apr 2016 19:24:58 -0700 Subject: [PATCH 0416/1265] Add `isMainFrame` as last argument to WebContents `did-fail-load` event. Fixes #5013. --- atom/browser/api/atom_api_web_contents.cc | 17 ++++++++++++++--- lib/renderer/web-view/guest-view-internal.js | 2 +- spec/api-browser-window-spec.js | 14 ++++++++++++-- spec/fixtures/api/did-fail-load-iframe.html | 5 +++++ 4 files changed, 32 insertions(+), 6 deletions(-) create mode 100644 spec/fixtures/api/did-fail-load-iframe.html diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 5156600bb73..c2b04a87aa2 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -541,7 +541,12 @@ void WebContents::DidFailProvisionalLoad( int error_code, const base::string16& error_description, bool was_ignored_by_handler) { - Emit("did-fail-provisional-load", error_code, error_description, url); + bool is_main_frame = !render_frame_host->GetParent(); + Emit("did-fail-provisional-load", + error_code, + error_description, + url, + is_main_frame); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, @@ -549,7 +554,12 @@ 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, validated_url); + bool is_main_frame = !render_frame_host->GetParent(); + Emit("did-fail-load", + error_code, + error_description, + validated_url, + is_main_frame); } void WebContents::DidStartLoading() { @@ -705,7 +715,8 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) { Emit("did-fail-load", static_cast(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), - url.possibly_invalid_spec()); + url.possibly_invalid_spec(), + true); return; } diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index f4023d22701..f8a47ac259a 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -8,7 +8,7 @@ var requestId = 0 var WEB_VIEW_EVENTS = { 'load-commit': ['url', 'isMainFrame'], 'did-finish-load': [], - 'did-fail-load': ['errorCode', 'errorDescription', 'validatedURL'], + 'did-fail-load': ['errorCode', 'errorDescription', 'validatedURL', 'isMainFrame'], 'did-frame-finish-load': ['isMainFrame'], 'did-start-loading': [], 'did-stop-loading': [], diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 468586eb7bb..a9940bde263 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -102,21 +102,31 @@ describe('browser-window module', function () { }) it('should emit did-fail-load event for files that do not exist', function (done) { - w.webContents.on('did-fail-load', function (event, code) { + w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) { assert.equal(code, -6) + assert.equal(isMainFrame, true) done() }) w.loadURL('file://a.txt') }) it('should emit did-fail-load event for invalid URL', function (done) { - w.webContents.on('did-fail-load', function (event, code, desc) { + w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) { assert.equal(desc, 'ERR_INVALID_URL') assert.equal(code, -300) + assert.equal(isMainFrame, true) done() }) w.loadURL('http://example:port') }) + + it('should set `mainFrame = false` on did-fail-load events in iframes', function (done) { + w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) { + assert.equal(isMainFrame, false) + done() + }) + w.loadURL('file://' + path.join(fixtures, 'api', 'did-fail-load-iframe.html')) + }) }) describe('BrowserWindow.show()', function () { diff --git a/spec/fixtures/api/did-fail-load-iframe.html b/spec/fixtures/api/did-fail-load-iframe.html new file mode 100644 index 00000000000..293041b65ec --- /dev/null +++ b/spec/fixtures/api/did-fail-load-iframe.html @@ -0,0 +1,5 @@ + + + + + From 884c9cc2f551d2146ef57fa48de98d80cb10cad1 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Mon, 4 Apr 2016 19:36:19 -0700 Subject: [PATCH 0417/1265] Document `isMainFrame` argument for WebContents `did-fail-load` event. --- docs-translations/ko-KR/api/web-contents.md | 1 + docs-translations/zh-CN/api/web-contents.md | 1 + docs/api/web-contents.md | 1 + 3 files changed, 3 insertions(+) diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 1cda4a3af5e..2c066a94110 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -31,6 +31,7 @@ Returns: * `errorCode` Integer * `errorDescription` String * `validatedURL` String +* `isMainFrame` Boolean 이 이벤트는 `did-finish-load`와 비슷하나, 로드가 실패했거나 취소되었을 때 발생합니다. 예를 들면 `window.stop()`이 실행되었을 때 발생합니다. 발생할 수 있는 전체 에러 코드의 diff --git a/docs-translations/zh-CN/api/web-contents.md b/docs-translations/zh-CN/api/web-contents.md index f168849863a..89d72f77aa7 100644 --- a/docs-translations/zh-CN/api/web-contents.md +++ b/docs-translations/zh-CN/api/web-contents.md @@ -30,6 +30,7 @@ var webContents = win.webContents; * `errorCode` Integer * `errorDescription` String * `validatedURL` String +* `isMainFrame` Boolean 这个事件类似 `did-finish-load` ,但是是在加载失败或取消加载时发出, 例如, `window.stop()` 请求结束.错误代码的完整列表和它们的含义都可以在 [here](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h) 找到. diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 5295b79ceb3..f2705582293 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -33,6 +33,7 @@ Returns: * `errorCode` Integer * `errorDescription` String * `validatedURL` String +* `isMainFrame` Boolean This event is like `did-finish-load` but emitted when the load failed or was cancelled, e.g. `window.stop()` is invoked. From c562b24df8c53b091753c20cfb9ca82360b39a1d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 5 Apr 2016 17:08:27 +0900 Subject: [PATCH 0418/1265] spec: Add test case for #5028 --- spec/node-spec.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spec/node-spec.js b/spec/node-spec.js index 286c4d6f916..c5c26196769 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -196,6 +196,11 @@ describe('node feature', function () { assert.equal(b.toString(), 'Jøhänñéß') assert.equal(Buffer.byteLength(p.innerText), 13) }) + + it('does not crash when creating large Buffers', function () { + new Buffer(new Array(4096).join(' ')); + new Buffer(new Array(4097).join(' ')); + }) }) describe('process.stdout', function () { From 7796dbb7cedbf6822fba97c2aafbb62d0adf22d3 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 5 Apr 2016 17:30:18 +0900 Subject: [PATCH 0419/1265] Update node: rebase on v5.10.0 tag instead of master branch --- vendor/node | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/node b/vendor/node index 95e76436b3a..c18d608cd58 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit 95e76436b3aceff54ebf8b32282cdbf8c74c4a5a +Subproject commit c18d608cd584e6b1c94a5d0d89939a1457f589b0 From dd283ff8d7c54a79a528114a881376af30598448 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 5 Apr 2016 19:53:07 +0900 Subject: [PATCH 0420/1265] spec: We should not use pre release of Node --- spec/node-spec.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spec/node-spec.js b/spec/node-spec.js index c5c26196769..0ab98aa67ab 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -217,6 +217,12 @@ describe('node feature', function () { }) }) + describe('process.version', function () { + it('should not have -pre', function () { + assert(!process.version.endsWith('-pre')) + }) + }) + describe('vm.createContext', function () { it('should not crash', function () { require('vm').runInNewContext('') From c474ad09134d2d3e5bdeff8be114cbb4a003ec0f Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 6 Apr 2016 10:16:41 -0700 Subject: [PATCH 0421/1265] Revert "Remove custom WM_GETOBJECT" This reverts commit 705001a50e3790c3c3e232dcb5be2ebf187b9417. --- atom/browser/native_window_views_win.cc | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/atom/browser/native_window_views_win.cc b/atom/browser/native_window_views_win.cc index e5ed1975f80..b395c4dd9bd 100644 --- a/atom/browser/native_window_views_win.cc +++ b/atom/browser/native_window_views_win.cc @@ -84,6 +84,20 @@ bool NativeWindowViews::PreHandleMSG( NotifyWindowMessage(message, w_param, l_param); switch (message) { + // Screen readers send WM_GETOBJECT in order to get the accessibility + // object, so take this opportunity to push Chromium into accessible + // mode if it isn't already, always say we didn't handle the message + // because we still want Chromium to handle returning the actual + // accessibility object. + case WM_GETOBJECT: { + const DWORD obj_id = static_cast(l_param); + if (obj_id == OBJID_CLIENT) { + const auto axState = content::BrowserAccessibilityState::GetInstance(); + if (axState && !axState->IsAccessibleBrowser()) + axState->OnScreenReaderDetected(); + } + return false; + } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) From 6e7aa6d299f5c4e5a7a2b59781c01778a03a5942 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Wed, 6 Apr 2016 10:36:39 -0700 Subject: [PATCH 0422/1265] Even though this call is probably fast, it can potentially happen a lot, make it _really_ fast --- atom/browser/native_window_views.h | 4 ++++ atom/browser/native_window_views_win.cc | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/atom/browser/native_window_views.h b/atom/browser/native_window_views.h index 862cd5458bb..bcf3ca8bd16 100644 --- a/atom/browser/native_window_views.h +++ b/atom/browser/native_window_views.h @@ -199,6 +199,10 @@ class NativeWindowViews : public NativeWindow, // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; + + // If true we have enabled a11y + bool enabled_a11y_support_; + #endif // Handles unhandled keyboard messages coming back from the renderer process. diff --git a/atom/browser/native_window_views_win.cc b/atom/browser/native_window_views_win.cc index b395c4dd9bd..038ab105222 100644 --- a/atom/browser/native_window_views_win.cc +++ b/atom/browser/native_window_views_win.cc @@ -91,11 +91,16 @@ bool NativeWindowViews::PreHandleMSG( // accessibility object. case WM_GETOBJECT: { const DWORD obj_id = static_cast(l_param); + if (enabled_a11y_support_) return false; + if (obj_id == OBJID_CLIENT) { const auto axState = content::BrowserAccessibilityState::GetInstance(); - if (axState && !axState->IsAccessibleBrowser()) + if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); + enabled_a11y_support_ = true; + } } + return false; } case WM_COMMAND: From b4885b9a371858cc4448a04a903f25e2973302b9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 7 Apr 2016 10:34:11 +0900 Subject: [PATCH 0423/1265] atom => electron in upload script --- script/upload.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/upload.py b/script/upload.py index d23bc554c3c..fd795172a67 100755 --- a/script/upload.py +++ b/script/upload.py @@ -14,7 +14,7 @@ from lib.util import atom_gyp, execute, get_atom_shell_version, parse_version, \ from lib.github import GitHub -ATOM_SHELL_REPO = 'atom/electron' +ATOM_SHELL_REPO = 'electron/electron' ATOM_SHELL_VERSION = get_atom_shell_version() PROJECT_NAME = atom_gyp()['project_name%'] From 55b8e9aa440057705c12169c3d80af5e0a40f95d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 6 Apr 2016 17:43:42 +0900 Subject: [PATCH 0424/1265] Bump v0.37.5 --- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- electron.gyp | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 7827a50d9fa..6cc84e06a90 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 0.37.4 + 0.37.5 CFBundleShortVersionString - 0.37.4 + 0.37.5 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 95f34256345..ff4fca04758 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,4,0 - PRODUCTVERSION 0,37,4,0 + FILEVERSION 0,37,5,0 + PRODUCTVERSION 0,37,5,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.4" + VALUE "FileVersion", "0.37.5" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.4" + VALUE "ProductVersion", "0.37.5" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 73662b177c9..437b97460dc 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 4 +#define ATOM_PATCH_VERSION 5 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/electron.gyp b/electron.gyp index bcea9365b23..94f5e07bfe9 100644 --- a/electron.gyp +++ b/electron.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.4', + 'version%': '0.37.5', }, 'includes': [ 'filenames.gypi', diff --git a/package.json b/package.json index 2d1f7ec8b46..555648a2519 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.4", + "version": "0.37.5", "devDependencies": { "asar": "^0.10.0", "request": "*", From fb299c7fcb1c94b7dc66889608176c5a449abb33 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 7 Apr 2016 14:58:14 +0900 Subject: [PATCH 0425/1265] Update node: bring CI back to green --- vendor/node | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/node b/vendor/node index c18d608cd58..6bcd8af891a 160000 --- a/vendor/node +++ b/vendor/node @@ -1 +1 @@ -Subproject commit c18d608cd584e6b1c94a5d0d89939a1457f589b0 +Subproject commit 6bcd8af891a991f8aa196e49e6bf908ebbe24cae From f9644463a9eedf2fe7427d574a4acdddf305fb2c Mon Sep 17 00:00:00 2001 From: Ben Gotow Date: Sat, 26 Mar 2016 19:29:24 -0700 Subject: [PATCH 0426/1265] Fix broken template image support in Tray icon Between Electron `0.30.x` and `0.37.x`, the tray icon stopped automatically inverting template images when highlighted. NSImageView normally uses the correct color for template images magicaly, but I think the addition of event handlers in the container view prevents the image view from determining highlight state. This PR switches to drawing the image manually. The `drawRect` function decides whether to use `image` or `alternateImage`(pressed image) and then if that image is marked as a template, it fills it with the same color used for the text before drawing it. --- atom/browser/ui/tray_icon_cocoa.mm | 64 +++++++++++++++++------------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/atom/browser/ui/tray_icon_cocoa.mm b/atom/browser/ui/tray_icon_cocoa.mm index d2a2fe83460..d833851eac5 100644 --- a/atom/browser/ui/tray_icon_cocoa.mm +++ b/atom/browser/ui/tray_icon_cocoa.mm @@ -27,7 +27,6 @@ const CGFloat kVerticalTitleMargin = 2; BOOL inMouseEventSequence_; base::scoped_nsobject image_; base::scoped_nsobject alternateImage_; - base::scoped_nsobject image_view_; base::scoped_nsobject title_; base::scoped_nsobject statusItem_; } @@ -44,15 +43,6 @@ const CGFloat kVerticalTitleMargin = 2; inMouseEventSequence_ = NO; if ((self = [super initWithFrame: CGRectZero])) { - // Setup the image view. - image_view_.reset([[NSImageView alloc] initWithFrame: CGRectZero]); - [image_view_ setImageScaling:NSImageScaleNone]; - [image_view_ setImageAlignment:NSImageAlignCenter]; - [self addSubview:image_view_]; - - // Unregister image_view_ as a dragged destination, allows its parent view - // (StatusItemView) handle dragging events. - [image_view_ unregisterDraggedTypes]; [self registerForDraggedTypes: @[NSFilenamesPboardType]]; // Create the status item. @@ -69,7 +59,6 @@ const CGFloat kVerticalTitleMargin = 2; - (void)updateDimensions { NSStatusBar * bar = [NSStatusBar systemStatusBar]; - [image_view_ setFrame: NSMakeRect(0, 0, [self iconWidth], [bar thickness])]; [self setFrame: NSMakeRect(0, 0, [self fullWidth], [bar thickness])]; [self setNeedsDisplay:YES]; } @@ -85,28 +74,44 @@ const CGFloat kVerticalTitleMargin = 2; // | icon | title | /// ---------------- - // Draw background. BOOL highlight = [self shouldHighlight]; + BOOL highlightContent = highlight | [self isDarkMode]; CGFloat thickness = [[statusItem_ statusBar] thickness]; + + // Draw the system bar background [statusItem_ drawStatusBarBackgroundInRect:self.bounds withHighlight:highlight]; - // Make use of NSImageView to draw the image, which can correctly draw - // template image under dark menu bar. - if (inMouseEventSequence_ && alternateImage_ && - [image_view_ image] != alternateImage_.get()) { - [image_view_ setImage:alternateImage_]; - } else if ([image_view_ image] != image_.get()) { - [image_view_ setImage:image_]; + // Determine which image to use + NSImage * image = image_.get(); + if (inMouseEventSequence_ && alternateImage_) { + image = alternateImage_.get(); } + // Apply the higlight color if the image is a template image. When this moves + // to using the new [NSStatusItem button] API, this should work automagically. + if ([image isTemplate] == YES) { + NSImage * imageWithColor = [image copy]; + [imageWithColor lockFocus]; + [[self colorWithHighlight: highlightContent] set]; + NSRectFillUsingOperation(self.bounds, NSCompositeSourceAtop); + [imageWithColor unlockFocus]; + image = imageWithColor; + } + + // Draw the image + [image drawInRect: CGRectMake( + roundf(([self iconWidth] - [image size].width) / 2), + roundf((thickness - [image size].height) / 2), + [image size].width, + [image size].height + )]; + if (title_) { - // Highlight the text when icon is highlighted or in dark mode. - highlight |= [self isDarkMode]; // Draw title. NSRect titleDrawRect = NSMakeRect( [self iconWidth], -kVerticalTitleMargin, [self titleWidth], thickness); [title_ drawInRect:titleDrawRect - withAttributes:[self titleAttributesWithHighlight:highlight]]; + withAttributes:[self titleAttributesWithHighlight:highlightContent]]; } } @@ -157,14 +162,17 @@ const CGFloat kVerticalTitleMargin = 2; return [attributes size].width; } +- (NSColor*)colorWithHighlight:(BOOL)highlight +{ + return highlight ? + [NSColor whiteColor] : + [NSColor colorWithRed:0.265625 green:0.25390625 blue:0.234375 alpha:1.0]; +} + - (NSDictionary*)titleAttributesWithHighlight:(BOOL)highlight { - NSFont* font = [NSFont menuBarFontOfSize:0]; - NSColor* foregroundColor = highlight ? - [NSColor whiteColor] : - [NSColor colorWithRed:0.265625 green:0.25390625 blue:0.234375 alpha:1.0]; return @{ - NSFontAttributeName: font, - NSForegroundColorAttributeName: foregroundColor + NSFontAttributeName: [NSFont menuBarFontOfSize:0], + NSForegroundColorAttributeName: [self colorWithHighlight: highlight] }; } From 91457fe7393c6b206e64f795beea221686e64259 Mon Sep 17 00:00:00 2001 From: Ben Gotow Date: Sat, 26 Mar 2016 19:40:52 -0700 Subject: [PATCH 0427/1265] Support images larger than self.bounds --- atom/browser/ui/tray_icon_cocoa.mm | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/atom/browser/ui/tray_icon_cocoa.mm b/atom/browser/ui/tray_icon_cocoa.mm index d833851eac5..6d7cdfaf981 100644 --- a/atom/browser/ui/tray_icon_cocoa.mm +++ b/atom/browser/ui/tray_icon_cocoa.mm @@ -86,24 +86,24 @@ const CGFloat kVerticalTitleMargin = 2; if (inMouseEventSequence_ && alternateImage_) { image = alternateImage_.get(); } - // Apply the higlight color if the image is a template image. When this moves // to using the new [NSStatusItem button] API, this should work automagically. if ([image isTemplate] == YES) { NSImage * imageWithColor = [image copy]; [imageWithColor lockFocus]; [[self colorWithHighlight: highlightContent] set]; - NSRectFillUsingOperation(self.bounds, NSCompositeSourceAtop); + CGRect imageBounds = CGRectMake(0,0, image.size.width, image.size.height); + NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop); [imageWithColor unlockFocus]; image = imageWithColor; } // Draw the image [image drawInRect: CGRectMake( - roundf(([self iconWidth] - [image size].width) / 2), - roundf((thickness - [image size].height) / 2), - [image size].width, - [image size].height + roundf(([self iconWidth] - image.size.width) / 2), + roundf((thickness - image.size.height) / 2), + image.size.width, + image.size.height )]; if (title_) { From e0ee60f290573fa889dbe448b6dd2c4b00a97a8c Mon Sep 17 00:00:00 2001 From: Ben Gotow Date: Tue, 5 Apr 2016 11:38:58 -0700 Subject: [PATCH 0428/1265] Fix memory leak --- atom/browser/ui/tray_icon_cocoa.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/ui/tray_icon_cocoa.mm b/atom/browser/ui/tray_icon_cocoa.mm index 6d7cdfaf981..ed1a774f2eb 100644 --- a/atom/browser/ui/tray_icon_cocoa.mm +++ b/atom/browser/ui/tray_icon_cocoa.mm @@ -89,7 +89,7 @@ const CGFloat kVerticalTitleMargin = 2; // Apply the higlight color if the image is a template image. When this moves // to using the new [NSStatusItem button] API, this should work automagically. if ([image isTemplate] == YES) { - NSImage * imageWithColor = [image copy]; + NSImage * imageWithColor = [image copy] autorelease]; [imageWithColor lockFocus]; [[self colorWithHighlight: highlightContent] set]; CGRect imageBounds = CGRectMake(0,0, image.size.width, image.size.height); From 548febfa4cc20835e1d4d537a97ea5ff8983a305 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 7 Apr 2016 13:58:51 +0900 Subject: [PATCH 0429/1265] Fix style issues --- atom/browser/ui/tray_icon_cocoa.mm | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/atom/browser/ui/tray_icon_cocoa.mm b/atom/browser/ui/tray_icon_cocoa.mm index ed1a774f2eb..c3fa3f3b927 100644 --- a/atom/browser/ui/tray_icon_cocoa.mm +++ b/atom/browser/ui/tray_icon_cocoa.mm @@ -78,18 +78,18 @@ const CGFloat kVerticalTitleMargin = 2; BOOL highlightContent = highlight | [self isDarkMode]; CGFloat thickness = [[statusItem_ statusBar] thickness]; - // Draw the system bar background + // Draw the system bar background. [statusItem_ drawStatusBarBackgroundInRect:self.bounds withHighlight:highlight]; - // Determine which image to use - NSImage * image = image_.get(); + // Determine which image to use. + NSImage* image = image_.get(); if (inMouseEventSequence_ && alternateImage_) { image = alternateImage_.get(); } // Apply the higlight color if the image is a template image. When this moves // to using the new [NSStatusItem button] API, this should work automagically. if ([image isTemplate] == YES) { - NSImage * imageWithColor = [image copy] autorelease]; + NSImage* imageWithColor = [[image copy] autorelease]; [imageWithColor lockFocus]; [[self colorWithHighlight: highlightContent] set]; CGRect imageBounds = CGRectMake(0,0, image.size.width, image.size.height); @@ -162,17 +162,16 @@ const CGFloat kVerticalTitleMargin = 2; return [attributes size].width; } -- (NSColor*)colorWithHighlight:(BOOL)highlight -{ +- (NSColor*)colorWithHighlight:(BOOL)highlight { return highlight ? - [NSColor whiteColor] : - [NSColor colorWithRed:0.265625 green:0.25390625 blue:0.234375 alpha:1.0]; + [NSColor whiteColor] : + [NSColor colorWithRed:0.265625 green:0.25390625 blue:0.234375 alpha:1.0]; } - (NSDictionary*)titleAttributesWithHighlight:(BOOL)highlight { return @{ - NSFontAttributeName: [NSFont menuBarFontOfSize:0], - NSForegroundColorAttributeName: [self colorWithHighlight: highlight] + NSFontAttributeName:[NSFont menuBarFontOfSize:0], + NSForegroundColorAttributeName:[self colorWithHighlight: highlight] }; } From 3ee366257c93fc5c931cb207ebbd72580785a175 Mon Sep 17 00:00:00 2001 From: Paul Betts Date: Tue, 5 Apr 2016 13:28:50 -0700 Subject: [PATCH 0430/1265] Allow bootstrap to be invoked via python2 This means that on most Linux distributions where python3 is the default, we can invoke `python2 script/bootstrap.py` and have it all work --- common.gypi | 2 +- script/bootstrap.py | 3 ++- toolchain.gypi | 2 +- tools/atom_source_root.js | 3 +++ tools/atom_source_root.py | 9 --------- tools/get-endianness.js | 1 + tools/linux/pkg-config-wrapper | 7 ++++++- 7 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 tools/atom_source_root.js delete mode 100755 tools/atom_source_root.py create mode 100644 tools/get-endianness.js diff --git a/common.gypi b/common.gypi index a9f067bcc54..1088beb1b7b 100644 --- a/common.gypi +++ b/common.gypi @@ -15,7 +15,7 @@ 'openssl_fips': '', 'openssl_no_asm': 1, 'node_release_urlbase': 'https://atom.io/download/atom-shell', - 'node_byteorder': ' Date: Thu, 7 Apr 2016 15:45:20 +0900 Subject: [PATCH 0431/1265] Fix coding styles --- script/bootstrap.py | 4 ++-- tools/linux/pkg-config-wrapper | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index b6cb9deaaf5..54f59c68f90 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -164,12 +164,12 @@ def update_clang(): def download_sysroot(target_arch): - python = sys.executable; if target_arch == 'ia32': target_arch = 'i386' if target_arch == 'x64': target_arch = 'amd64' - execute_stdout([python, os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py'), + execute_stdout([sys.executable, + os.path.join(SOURCE_ROOT, 'script', 'install-sysroot.py'), '--arch', target_arch]) def create_chrome_version_h(): diff --git a/tools/linux/pkg-config-wrapper b/tools/linux/pkg-config-wrapper index 7950b0b019b..84b57a8fe58 100755 --- a/tools/linux/pkg-config-wrapper +++ b/tools/linux/pkg-config-wrapper @@ -33,8 +33,8 @@ fi python2=$(which python2) if [ ! -x "$python2" ] ; then - python2=python -fi + python2=python +fi rewrite=`dirname $0`/rewrite_dirs.py package=${!#} From cb47dfa90e3bc6c02ee41715de560f620cbcc9e8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 7 Apr 2016 15:56:25 +0900 Subject: [PATCH 0432/1265] Fix problem with old Node --- tools/get-endianness.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tools/get-endianness.js b/tools/get-endianness.js index a1f985e18a0..a910e664b05 100644 --- a/tools/get-endianness.js +++ b/tools/get-endianness.js @@ -1 +1,6 @@ -console.log(require('os').endianness() === 'BE' ? 'big' : 'little') +var os = require('os') +if (os.endianness) { + console.log(require('os').endianness() === 'BE' ? 'big' : 'little') +} else { // Your Node is rather old, but I don't care. + console.log('little') +} From a79c63581d973a68d86531b890be55401ae95afd Mon Sep 17 00:00:00 2001 From: christoth Date: Thu, 7 Apr 2016 10:42:42 -0400 Subject: [PATCH 0433/1265] Update doc to reflect use of flexbox layout Updated documentation, changed `display:inline-block` to `display:inline-flex', explicitly noted the use of the new layout and how it can be broken by overwriting the CSS `display' property. --- docs/api/web-view-tag.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 47e23dc9943..3bb71936be2 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -18,8 +18,13 @@ form, the `webview` tag includes the `src` of the web page and css styles that control the appearance of the `webview` container: ```html - + ``` +Please note that the `webview` tag's style uses `display:flex;` internally to +ensure the child `object` element fills the full height and width of its `webview` +container when used with traditional and flexbox layouts (since v0.36.11). Please +do not overwrite the default `display:flex;` CSS property, unless specifying +`display:inline-flex;` for inline layout. If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the From 59991f2fd81c2b3277923bad17693eef7471b790 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 6 Apr 2016 17:40:07 -0700 Subject: [PATCH 0434/1265] Mention codesigning is required on OS X --- docs/api/auto-updater.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 58584d73800..8dd6d2412a4 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -19,6 +19,9 @@ On OS X, the `autoUpdater` module is built upon [Squirrel.Mac][squirrel-mac], meaning you don't need any special setup to make it work. For server-side requirements, you can read [Server Support][server-support]. +**Note:** Your application must be signed for automatic updates on Mac OS X. +This is a requirement of `Squirrel.Mac`. + ### Windows On Windows, you have to install your app into a user's machine before you can From 79ba8feaf8485a0c7a94e717281d1e13deff9e6c Mon Sep 17 00:00:00 2001 From: Pete Burgers Date: Thu, 7 Apr 2016 17:04:15 +0100 Subject: [PATCH 0435/1265] Don't wait for xdg-open to exit when OpenExternal is called (Linux) Some browsers (eg. Firefox) may not return until the browser window is closed. This causes the Electron application to lock up while the browser window is open. See https://github.com/atom/atom/issues/6320 --- atom/common/platform_util_linux.cc | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/atom/common/platform_util_linux.cc b/atom/common/platform_util_linux.cc index 1e437b866cc..0419c1143bc 100644 --- a/atom/common/platform_util_linux.cc +++ b/atom/common/platform_util_linux.cc @@ -13,7 +13,9 @@ namespace { -bool XDGUtil(const std::string& util, const std::string& arg) { +bool XDGUtil(const std::string& util, + const std::string& arg, + bool wait_for_exit) { std::vector argv; argv.push_back(util); argv.push_back(arg); @@ -30,6 +32,9 @@ bool XDGUtil(const std::string& util, const std::string& arg) { if (!process.IsValid()) return false; + if (!wait_for_exit) + return true; + int exit_code = -1; if (!process.WaitForExit(&exit_code)) return false; @@ -37,12 +42,12 @@ bool XDGUtil(const std::string& util, const std::string& arg) { return (exit_code == 0); } -bool XDGOpen(const std::string& path) { - return XDGUtil("xdg-open", path); +bool XDGOpen(const std::string& path, bool wait_for_exit) { + return XDGUtil("xdg-open", path, wait_for_exit); } -bool XDGEmail(const std::string& email) { - return XDGUtil("xdg-email", email); +bool XDGEmail(const std::string& email, bool wait_for_exit) { + return XDGUtil("xdg-email", email, wait_for_exit); } } // namespace @@ -57,22 +62,24 @@ void ShowItemInFolder(const base::FilePath& full_path) { if (!base::DirectoryExists(dir)) return; - XDGOpen(dir.value()); + XDGOpen(dir.value(), true); } void OpenItem(const base::FilePath& full_path) { - XDGOpen(full_path.value()); + XDGOpen(full_path.value(), true); } bool OpenExternal(const GURL& url, bool activate) { + // Don't wait for exit, since we don't want to wait for the browser/email + // client window to close before returning if (url.SchemeIs("mailto")) - return XDGEmail(url.spec()); + return XDGEmail(url.spec(), false); else - return XDGOpen(url.spec()); + return XDGOpen(url.spec(), false); } bool MoveItemToTrash(const base::FilePath& full_path) { - return XDGUtil("gvfs-trash", full_path.value()); + return XDGUtil("gvfs-trash", full_path.value(), true); } void Beep() { From 8d8d5878a3f3c36da83da8e5d64ad9d44cf7946b Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 6 Apr 2016 16:21:26 -0700 Subject: [PATCH 0436/1265] Rename ATOM_ ipc event prefix to ELECTRON_ --- lib/browser/api/browser-window.js | 10 +++--- lib/browser/api/navigation-controller.js | 4 +-- lib/browser/desktop-capturer.js | 6 ++-- lib/browser/guest-view-manager.js | 16 ++++----- lib/browser/guest-window-manager.js | 14 ++++---- lib/browser/rpc-server.js | 34 ++++++++++---------- lib/renderer/api/desktop-capturer.js | 4 +-- lib/renderer/api/remote.js | 30 ++++++++--------- lib/renderer/override.js | 26 +++++++-------- lib/renderer/web-view/guest-view-internal.js | 22 ++++++------- lib/renderer/web-view/web-view.js | 6 ++-- 11 files changed, 86 insertions(+), 86 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 33aea5da4d0..694cbf6d669 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -28,7 +28,7 @@ BrowserWindow.prototype._init = function () { width: 800, height: 600 } - return ipcMain.emit('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, disposition, options) + return ipcMain.emit('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', event, url, frameName, disposition, options) }) // window.resizeTo(...) @@ -80,16 +80,16 @@ BrowserWindow.prototype._init = function () { // Evented visibilityState changes this.on('show', () => { - this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) + this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) }) this.on('hide', () => { - this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) + this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) }) this.on('minimize', () => { - this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) + this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) }) this.on('restore', () => { - this.webContents.send('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) + this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) }) // Notify the creation of the window. diff --git a/lib/browser/api/navigation-controller.js b/lib/browser/api/navigation-controller.js index d9dedc91e34..c7aa7f4e92a 100644 --- a/lib/browser/api/navigation-controller.js +++ b/lib/browser/api/navigation-controller.js @@ -3,12 +3,12 @@ const ipcMain = require('electron').ipcMain // The history operation in renderer is redirected to browser. -ipcMain.on('ATOM_SHELL_NAVIGATION_CONTROLLER', function (event, method, ...args) { +ipcMain.on('ELECTRON_NAVIGATION_CONTROLLER', function (event, method, ...args) { var ref (ref = event.sender)[method].apply(ref, args) }) -ipcMain.on('ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER', function (event, method, ...args) { +ipcMain.on('ELECTRON_SYNC_NAVIGATION_CONTROLLER', function (event, method, ...args) { var ref event.returnValue = (ref = event.sender)[method].apply(ref, args) }) diff --git a/lib/browser/desktop-capturer.js b/lib/browser/desktop-capturer.js index 5ba64fcddb1..5e8ad3e7328 100644 --- a/lib/browser/desktop-capturer.js +++ b/lib/browser/desktop-capturer.js @@ -10,7 +10,7 @@ var deepEqual = function (opt1, opt2) { // A queue for holding all requests from renderer process. var requestsQueue = [] -ipcMain.on('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function (event, captureWindow, captureScreen, thumbnailSize, id) { +ipcMain.on('ELECTRON_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', function (event, captureWindow, captureScreen, thumbnailSize, id) { var request request = { id: id, @@ -51,7 +51,7 @@ desktopCapturer.emit = function (event, name, sources) { return results })() if ((ref = handledRequest.webContents) != null) { - ref.send('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + handledRequest.id, result) + ref.send('ELECTRON_RENDERER_DESKTOP_CAPTURER_RESULT_' + handledRequest.id, result) } // Check the queue to see whether there is other same request. If has, handle @@ -61,7 +61,7 @@ desktopCapturer.emit = function (event, name, sources) { request = requestsQueue[i] if (deepEqual(handledRequest.options, request.options)) { if ((ref1 = request.webContents) != null) { - ref1.send('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + request.id, result) + ref1.send('ELECTRON_RENDERER_DESKTOP_CAPTURER_RESULT_' + request.id, result) } } else { unhandledRequestsQueue.push(request) diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index ee633cf2901..ad79fe699a4 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -137,7 +137,7 @@ var createGuest = function (embedder, params) { // Dispatch events to embedder. fn = function (event) { return guest.on(event, function (_, ...args) { - return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + guest.viewInstanceId, event].concat(args)) + return embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + guest.viewInstanceId, event].concat(args)) }) } for (j = 0, len1 = supportedWebViewEvents.length; j < len1; j++) { @@ -147,12 +147,12 @@ var createGuest = function (embedder, params) { // Dispatch guest's IPC messages to embedder. guest.on('ipc-message-host', function (_, [channel, ...args]) { - return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + guest.viewInstanceId, channel].concat(args)) + return embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + guest.viewInstanceId, channel].concat(args)) }) // Autosize. guest.on('size-changed', function (_, ...args) { - return embedder.send.apply(embedder, ['ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + guest.viewInstanceId].concat(args)) + return embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + guest.viewInstanceId].concat(args)) }) return id } @@ -204,19 +204,19 @@ var destroyGuest = function (embedder, id) { } } -ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) { - return event.sender.send('ATOM_SHELL_RESPONSE_' + requestId, createGuest(event.sender, params)) +ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) { + return event.sender.send('ELECTRON_RESPONSE_' + requestId, createGuest(event.sender, params)) }) -ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, elementInstanceId, guestInstanceId, params) { +ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, elementInstanceId, guestInstanceId, params) { return attachGuest(event.sender, elementInstanceId, guestInstanceId, params) }) -ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, id) { +ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, id) { return destroyGuest(event.sender, id) }) -ipcMain.on('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', function (event, id, params) { +ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_SET_SIZE', function (event, id, params) { var ref1 return (ref1 = guestInstances[id]) != null ? ref1.guest.setSize(params) : void 0 }) diff --git a/lib/browser/guest-window-manager.js b/lib/browser/guest-window-manager.js index 7508b6f16a2..c5189bee60c 100644 --- a/lib/browser/guest-window-manager.js +++ b/lib/browser/guest-window-manager.js @@ -70,7 +70,7 @@ var createGuest = function (embedder, url, frameName, options) { return guest.destroy() } closedByUser = function () { - embedder.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId) + embedder.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + guestId) return embedder.removeListener('render-view-deleted', closedByEmbedder) } embedder.once('render-view-deleted', closedByEmbedder) @@ -86,7 +86,7 @@ var createGuest = function (embedder, url, frameName, options) { } // Routed window.open messages. -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, frameName, disposition, options) { +ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, frameName, disposition, options) { options = mergeBrowserWindowOptions(event.sender, options) event.sender.emit('new-window', event, url, frameName, disposition, options) if ((event.sender.isGuest() && !event.sender.allowPopups) || event.defaultPrevented) { @@ -96,17 +96,17 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', function (event, url, } }) -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function (event, guestId) { +ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', function (event, guestId) { var ref1 return (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1.destroy() : void 0 }) -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function (event, guestId, method, ...args) { +ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', function (event, guestId, method, ...args) { var ref1 event.returnValue = (ref1 = BrowserWindow.fromId(guestId)) != null ? ref1[method].apply(ref1, args) : void 0 }) -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event, guestId, message, targetOrigin, sourceOrigin) { +ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event, guestId, message, targetOrigin, sourceOrigin) { var guestContents, ref1, ref2, sourceId sourceId = (ref1 = BrowserWindow.fromWebContents(event.sender)) != null ? ref1.id : void 0 if (sourceId == null) { @@ -114,11 +114,11 @@ ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', function (event } guestContents = (ref2 = BrowserWindow.fromId(guestId)) != null ? ref2.webContents : void 0 if ((guestContents != null ? guestContents.getURL().indexOf(targetOrigin) : void 0) === 0 || targetOrigin === '*') { - return guestContents != null ? guestContents.send('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', sourceId, message, sourceOrigin) : void 0 + return guestContents != null ? guestContents.send('ELECTRON_GUEST_WINDOW_POSTMESSAGE', sourceId, message, sourceOrigin) : void 0 } }) -ipcMain.on('ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function (event, guestId, method, ...args) { +ipcMain.on('ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', function (event, guestId, method, ...args) { var ref1, ref2 return (ref1 = BrowserWindow.fromId(guestId)) != null ? (ref2 = ref1.webContents) != null ? ref2[method].apply(ref2, args) : void 0 : void 0 }) diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index 79a52b13262..4603ba332c2 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -193,14 +193,14 @@ var unwrapArgs = function (sender, args) { let callIntoRenderer = function (...args) { if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) { - sender.send('ATOM_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args)) + sender.send('ELECTRON_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args)) } else { throw new Error(`Attempting to call a function in a renderer window that has been closed or released. Function provided here: ${meta.location}.`) } } v8Util.setDestructor(callIntoRenderer, function () { if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) { - sender.send('ATOM_RENDERER_RELEASE_CALLBACK', meta.id) + sender.send('ELECTRON_RENDERER_RELEASE_CALLBACK', meta.id) } }) callbacks.set(meta.id, callIntoRenderer) @@ -238,7 +238,7 @@ var callFunction = function (event, func, caller, args) { } } -ipcMain.on('ATOM_BROWSER_REQUIRE', function (event, module) { +ipcMain.on('ELECTRON_BROWSER_REQUIRE', function (event, module) { try { event.returnValue = valueToMeta(event.sender, process.mainModule.require(module)) } catch (error) { @@ -246,7 +246,7 @@ ipcMain.on('ATOM_BROWSER_REQUIRE', function (event, module) { } }) -ipcMain.on('ATOM_BROWSER_GET_BUILTIN', function (event, module) { +ipcMain.on('ELECTRON_BROWSER_GET_BUILTIN', function (event, module) { try { event.returnValue = valueToMeta(event.sender, electron[module]) } catch (error) { @@ -254,7 +254,7 @@ ipcMain.on('ATOM_BROWSER_GET_BUILTIN', function (event, module) { } }) -ipcMain.on('ATOM_BROWSER_GLOBAL', function (event, name) { +ipcMain.on('ELECTRON_BROWSER_GLOBAL', function (event, name) { try { event.returnValue = valueToMeta(event.sender, global[name]) } catch (error) { @@ -262,7 +262,7 @@ ipcMain.on('ATOM_BROWSER_GLOBAL', function (event, name) { } }) -ipcMain.on('ATOM_BROWSER_CURRENT_WINDOW', function (event) { +ipcMain.on('ELECTRON_BROWSER_CURRENT_WINDOW', function (event) { try { event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow()) } catch (error) { @@ -270,11 +270,11 @@ ipcMain.on('ATOM_BROWSER_CURRENT_WINDOW', function (event) { } }) -ipcMain.on('ATOM_BROWSER_CURRENT_WEB_CONTENTS', function (event) { +ipcMain.on('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS', function (event) { event.returnValue = valueToMeta(event.sender, event.sender) }) -ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) { +ipcMain.on('ELECTRON_BROWSER_CONSTRUCTOR', function (event, id, args) { try { args = unwrapArgs(event.sender, args) let constructor = objectsRegistry.get(id) @@ -288,7 +288,7 @@ ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function (event, id, args) { } }) -ipcMain.on('ATOM_BROWSER_FUNCTION_CALL', function (event, id, args) { +ipcMain.on('ELECTRON_BROWSER_FUNCTION_CALL', function (event, id, args) { try { args = unwrapArgs(event.sender, args) let func = objectsRegistry.get(id) @@ -298,7 +298,7 @@ ipcMain.on('ATOM_BROWSER_FUNCTION_CALL', function (event, id, args) { } }) -ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) { +ipcMain.on('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) { try { args = unwrapArgs(event.sender, args) let constructor = objectsRegistry.get(id)[method] @@ -311,7 +311,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function (event, id, method, args) } }) -ipcMain.on('ATOM_BROWSER_MEMBER_CALL', function (event, id, method, args) { +ipcMain.on('ELECTRON_BROWSER_MEMBER_CALL', function (event, id, method, args) { try { args = unwrapArgs(event.sender, args) let obj = objectsRegistry.get(id) @@ -321,7 +321,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_CALL', function (event, id, method, args) { } }) -ipcMain.on('ATOM_BROWSER_MEMBER_SET', function (event, id, name, value) { +ipcMain.on('ELECTRON_BROWSER_MEMBER_SET', function (event, id, name, value) { try { let obj = objectsRegistry.get(id) obj[name] = value @@ -331,7 +331,7 @@ ipcMain.on('ATOM_BROWSER_MEMBER_SET', function (event, id, name, value) { } }) -ipcMain.on('ATOM_BROWSER_MEMBER_GET', function (event, id, name) { +ipcMain.on('ELECTRON_BROWSER_MEMBER_GET', function (event, id, name) { try { let obj = objectsRegistry.get(id) event.returnValue = valueToMeta(event.sender, obj[name]) @@ -340,11 +340,11 @@ ipcMain.on('ATOM_BROWSER_MEMBER_GET', function (event, id, name) { } }) -ipcMain.on('ATOM_BROWSER_DEREFERENCE', function (event, id) { +ipcMain.on('ELECTRON_BROWSER_DEREFERENCE', function (event, id) { return objectsRegistry.remove(event.sender.getId(), id) }) -ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) { +ipcMain.on('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) { try { let guestViewManager = require('./guest-view-manager') event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId)) @@ -353,13 +353,13 @@ ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function (event, guestInstanceId) } }) -ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) { +ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, ...args) { try { let guestViewManager = require('./guest-view-manager') let guest = guestViewManager.getGuest(guestInstanceId) if (requestId) { const responseCallback = function (result) { - event.sender.send(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result) + event.sender.send(`ELECTRON_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, result) } args.push(responseCallback) } diff --git a/lib/renderer/api/desktop-capturer.js b/lib/renderer/api/desktop-capturer.js index 5683e9cff25..32f78f7a6a3 100644 --- a/lib/renderer/api/desktop-capturer.js +++ b/lib/renderer/api/desktop-capturer.js @@ -27,8 +27,8 @@ exports.getSources = function (options, callback) { } } id = getNextId() - ipcRenderer.send('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', captureWindow, captureScreen, options.thumbnailSize, id) - return ipcRenderer.once('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + id, function (event, sources) { + ipcRenderer.send('ELECTRON_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', captureWindow, captureScreen, options.thumbnailSize, id) + return ipcRenderer.once('ELECTRON_RENDERER_DESKTOP_CAPTURER_RESULT_' + id, function (event, sources) { var source return callback(null, (function () { var i, len, results diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 30b66983a7d..8865c33c277 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -102,11 +102,11 @@ let setObjectMembers = function (ref, object, metaId, members) { let remoteMemberFunction = function () { if (this && this.constructor === remoteMemberFunction) { // Constructor call. - let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, member.name, wrapArgs(arguments)) + let ret = ipcRenderer.sendSync('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', metaId, member.name, wrapArgs(arguments)) return metaToValue(ret) } else { // Call member function. - let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, member.name, wrapArgs(arguments)) + let ret = ipcRenderer.sendSync('ELECTRON_BROWSER_MEMBER_CALL', metaId, member.name, wrapArgs(arguments)) return metaToValue(ret) } } @@ -122,13 +122,13 @@ let setObjectMembers = function (ref, object, metaId, members) { descriptor.configurable = true } else if (member.type === 'get') { descriptor.get = function () { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, member.name)) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_MEMBER_GET', metaId, member.name)) } // Only set setter when it is writable. if (member.writable) { descriptor.set = function (value) { - ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, member.name, value) + ipcRenderer.sendSync('ELECTRON_BROWSER_MEMBER_SET', metaId, member.name, value) return value } } @@ -182,14 +182,14 @@ let metaToValue = function (meta) { let remoteFunction = function () { if (this && this.constructor === remoteFunction) { // Constructor call. - let obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)) + let obj = ipcRenderer.sendSync('ELECTRON_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)) // Returning object in constructor will replace constructed object // with the returned object. // http://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this return metaToValue(obj) } else { // Function call. - let obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)) + let obj = ipcRenderer.sendSync('ELECTRON_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)) return metaToValue(obj) } } @@ -209,7 +209,7 @@ let metaToValue = function (meta) { // Track delegate object's life time, and tell the browser to clean up // when the object is GCed. v8Util.setDestructor(ret, function () { - ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id) + ipcRenderer.send('ELECTRON_BROWSER_DEREFERENCE', meta.id) }) // Remember object's id. @@ -239,12 +239,12 @@ var metaToPlainObject = function (meta) { } // Browser calls a callback in renderer. -ipcRenderer.on('ATOM_RENDERER_CALLBACK', function (event, id, args) { +ipcRenderer.on('ELECTRON_RENDERER_CALLBACK', function (event, id, args) { return callbacksRegistry.apply(id, metaToValue(args)) }) // A callback in browser is released. -ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function (event, id) { +ipcRenderer.on('ELECTRON_RENDERER_RELEASE_CALLBACK', function (event, id) { return callbacksRegistry.remove(id) }) @@ -265,27 +265,27 @@ for (var name in browserModules) { // Get remote module. exports.require = function (module) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_REQUIRE', module)) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_REQUIRE', module)) } // Alias to remote.require('electron').xxx. exports.getBuiltin = function (module) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GET_BUILTIN', module)) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_GET_BUILTIN', module)) } // Get current BrowserWindow. exports.getCurrentWindow = function () { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WINDOW')) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_CURRENT_WINDOW')) } // Get current WebContents object. exports.getCurrentWebContents = function () { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WEB_CONTENTS')) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS')) } // Get a global object in browser. exports.getGlobal = function (name) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name)) + return metaToValue(ipcRenderer.sendSync('ELECTRON_BROWSER_GLOBAL', name)) } // Get the process object in browser. @@ -306,6 +306,6 @@ exports.createFunctionWithReturnValue = function (returnValue) { // Get the guest WebContents from guestInstanceId. exports.getGuestWebContents = function (guestInstanceId) { var meta - meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId) + meta = ipcRenderer.sendSync('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId) return metaToValue(meta) } diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 20c993d0bc5..5f808d66300 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -38,30 +38,30 @@ var BrowserWindowProxy = (function () { function BrowserWindowProxy (guestId1) { this.guestId = guestId1 this.closed = false - ipcRenderer.once('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + this.guestId, () => { + ipcRenderer.once('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + this.guestId, () => { BrowserWindowProxy.remove(this.guestId) this.closed = true }) } BrowserWindowProxy.prototype.close = function () { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', this.guestId) + return ipcRenderer.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', this.guestId) } BrowserWindowProxy.prototype.focus = function () { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'focus') + return ipcRenderer.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'focus') } BrowserWindowProxy.prototype.blur = function () { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'blur') + return ipcRenderer.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'blur') } Object.defineProperty(BrowserWindowProxy.prototype, 'location', { get: function () { - return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'getURL') + return ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'getURL') }, set: function (url) { - return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'loadURL', url) + return ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'loadURL', url) } }) @@ -69,11 +69,11 @@ var BrowserWindowProxy = (function () { if (targetOrigin == null) { targetOrigin = '*' } - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, window.location.origin) + return ipcRenderer.send('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, window.location.origin) } BrowserWindowProxy.prototype['eval'] = function (...args) { - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(args)) + return ipcRenderer.send.apply(ipcRenderer, ['ELECTRON_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(args)) } return BrowserWindowProxy @@ -147,7 +147,7 @@ window.open = function (url, frameName, features) { options[name] = parseInt(options[name], 10) } } - guestId = ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, disposition, options) + guestId = ipcRenderer.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, disposition, options) if (guestId) { return BrowserWindowProxy.getOrCreate(guestId) } else { @@ -200,7 +200,7 @@ if (process.openerId != null) { window.opener = BrowserWindowProxy.getOrCreate(process.openerId) } -ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { +ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { var hasChanged = _isVisible !== isVisible || _isMinimized !== isMinimized if (hasChanged) { @@ -211,7 +211,7 @@ ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisi } }) -ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function (event, sourceId, message, sourceOrigin) { +ipcRenderer.on('ELECTRON_GUEST_WINDOW_POSTMESSAGE', function (event, sourceId, message, sourceOrigin) { // Manually dispatch event instead of using postMessage because we also need to // set event.source. event = document.createEvent('Event') @@ -224,11 +224,11 @@ ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function (event, sourceId, // Forward history operations to browser. var sendHistoryOperation = function (...args) { - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_NAVIGATION_CONTROLLER'].concat(args)) + return ipcRenderer.send.apply(ipcRenderer, ['ELECTRON_NAVIGATION_CONTROLLER'].concat(args)) } var getHistoryOperation = function (...args) { - return ipcRenderer.sendSync.apply(ipcRenderer, ['ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER'].concat(args)) + return ipcRenderer.sendSync.apply(ipcRenderer, ['ELECTRON_SYNC_NAVIGATION_CONTROLLER'].concat(args)) } window.history.back = function () { diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index f8a47ac259a..efe462fc914 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -61,18 +61,18 @@ var dispatchEvent = function (webView, eventName, eventKey, ...args) { module.exports = { registerEvents: function (webView, viewInstanceId) { - ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId, function (event, eventName, ...args) { + ipcRenderer.on('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId, function (event, eventName, ...args) { return dispatchEvent.apply(null, [webView, eventName, eventName].concat(args)) }) - ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId, function (event, channel, ...args) { + ipcRenderer.on('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId, function (event, channel, ...args) { var domEvent = new Event('ipc-message') domEvent.channel = channel domEvent.args = args return webView.dispatchEvent(domEvent) }) - return ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId, function (event, ...args) { + return ipcRenderer.on('ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId, function (event, ...args) { var domEvent, f, i, j, len, ref1 domEvent = new Event('size-changed') ref1 = ['oldWidth', 'oldHeight', 'newWidth', 'newHeight'] @@ -84,23 +84,23 @@ module.exports = { }) }, deregisterEvents: function (viewInstanceId) { - ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId) - ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId) - return ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId) + ipcRenderer.removeAllListeners('ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId) + ipcRenderer.removeAllListeners('ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId) + return ipcRenderer.removeAllListeners('ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId) }, createGuest: function (params, callback) { requestId++ - ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId) - return ipcRenderer.once('ATOM_SHELL_RESPONSE_' + requestId, callback) + ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId) + return ipcRenderer.once('ELECTRON_RESPONSE_' + requestId, callback) }, attachGuest: function (elementInstanceId, guestInstanceId, params) { - ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params) + ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params) return webFrame.attachGuest(elementInstanceId) }, destroyGuest: function (guestInstanceId) { - return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId) + return ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId) }, setSize: function (guestInstanceId, params) { - return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params) + return ipcRenderer.send('ELECTRON_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params) } } diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 0e96d0c0643..974d5c6608d 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -404,7 +404,7 @@ var registerWebViewElement = function () { createNonBlockHandler = function (m) { return function (...args) { const internal = v8Util.getHiddenValue(this, 'internal') - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)) + return ipcRenderer.send.apply(ipcRenderer, ['ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)) } } for (j = 0, len1 = nonblockMethods.length; j < len1; j++) { @@ -419,8 +419,8 @@ var registerWebViewElement = function () { hasUserGesture = false } let requestId = getNextId() - ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, 'executeJavaScript', code, hasUserGesture) - ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function (event, result) { + ipcRenderer.send('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, 'executeJavaScript', code, hasUserGesture) + ipcRenderer.once(`ELECTRON_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function (event, result) { if (callback) callback(result) }) } From 193c6d6e93dc09050e46521ab5e7ca6622c2e465 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 7 Apr 2016 09:40:31 -0700 Subject: [PATCH 0437/1265] :memo: document API naming conventions --- docs/development/coding-style.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index 52ae3c299a5..ca517486218 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -39,9 +39,16 @@ etc. * [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) instead of string concatenation using `+` -## API Names +## Naming Things -When creating a new API, we should prefer getters and setters instead of +Electron APIs uses the same capitalization scheme as Node.js: + +- When the module itself is a class like `BrowserWindow`, use CamelCase. +- When the module is a set of APIs, like `clipboard`, use mixedCase. +- When the API is a property of object, and it is complex enough to be in a separate chapter like `win.webContents`, use mixedCase. +- For other non-module APIs, use natural titles, like ` Tag` or `Process Object`. + +When creating a new API, it is preferred to use getters and setters instead of jQuery's one-function style. For example, `.getText()` and `.setText(text)` are preferred to `.text([text])`. There is a [discussion](https://github.com/electron/electron/issues/46) on this. From 4d8d4d5f2ac74a9ad3d3853c7fee3fe059c16e24 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 7 Apr 2016 09:49:17 -0700 Subject: [PATCH 0438/1265] use globalShortcut as a better mixedCase example --- docs/development/coding-style.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index ca517486218..c08efa42ca6 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -44,7 +44,7 @@ etc. Electron APIs uses the same capitalization scheme as Node.js: - When the module itself is a class like `BrowserWindow`, use CamelCase. -- When the module is a set of APIs, like `clipboard`, use mixedCase. +- When the module is a set of APIs, like `globalShortcut`, use mixedCase. - When the API is a property of object, and it is complex enough to be in a separate chapter like `win.webContents`, use mixedCase. - For other non-module APIs, use natural titles, like ` Tag` or `Process Object`. From 348a0e958bfeaa56633ddf6005a6f5d0524d48bf Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 7 Apr 2016 09:49:55 -0700 Subject: [PATCH 0439/1265] wrap cases in backticks --- docs/development/coding-style.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index c08efa42ca6..baf2a2cce7d 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -43,9 +43,9 @@ etc. Electron APIs uses the same capitalization scheme as Node.js: -- When the module itself is a class like `BrowserWindow`, use CamelCase. -- When the module is a set of APIs, like `globalShortcut`, use mixedCase. -- When the API is a property of object, and it is complex enough to be in a separate chapter like `win.webContents`, use mixedCase. +- When the module itself is a class like `BrowserWindow`, use `CamelCase`. +- When the module is a set of APIs, like `globalShortcut`, use `mixedCase`. +- When the API is a property of object, and it is complex enough to be in a separate chapter like `win.webContents`, use `mixedCase`. - For other non-module APIs, use natural titles, like ` Tag` or `Process Object`. When creating a new API, it is preferred to use getters and setters instead of From d3308cf8c34bf15e6eaf903b52c7d03de602f793 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 09:53:33 -0700 Subject: [PATCH 0440/1265] Use node 0.10.21 on CI --- script/cibuild | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/script/cibuild b/script/cibuild index 54cfa508910..de4dca50bb8 100755 --- a/script/cibuild +++ b/script/cibuild @@ -32,6 +32,9 @@ LINUX_DEPS_ARM = [ def main(): os.environ['CI'] = '1' + if os.environ.has_key('JANKY_SHA1'): + setup_nodenv() + target_arch = 'x64' if os.environ.has_key('TARGET_ARCH'): target_arch = os.environ['TARGET_ARCH'] @@ -86,5 +89,12 @@ def run_script(script, args=[]): subprocess.check_call([sys.executable, script] + args) +def setup_nodenv(): + if os.isdir('/usr/local/share/nodenv'): + os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' + os.environ['PATH'] += '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] + os.environ['NODENV_VERSION'] = 'v0.10.21' + + if __name__ == '__main__': sys.exit(main()) From 7e87973d60718a8eeaa456a9318f873c8802d42f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 09:55:23 -0700 Subject: [PATCH 0441/1265] Log version to verify --- script/cibuild | 1 + 1 file changed, 1 insertion(+) diff --git a/script/cibuild b/script/cibuild index de4dca50bb8..c9332040094 100755 --- a/script/cibuild +++ b/script/cibuild @@ -94,6 +94,7 @@ def setup_nodenv(): os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' os.environ['PATH'] += '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] os.environ['NODENV_VERSION'] = 'v0.10.21' + subprocess.call(["node", "--version"]) if __name__ == '__main__': From 0fad8fdc4b331175454213449dd2c72450b0b46f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 09:56:04 -0700 Subject: [PATCH 0442/1265] Add missing .path --- script/cibuild | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/cibuild b/script/cibuild index c9332040094..0e9f764f7c1 100755 --- a/script/cibuild +++ b/script/cibuild @@ -90,7 +90,7 @@ def run_script(script, args=[]): def setup_nodenv(): - if os.isdir('/usr/local/share/nodenv'): + if os.path.isdir('/usr/local/share/nodenv'): os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' os.environ['PATH'] += '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] os.environ['NODENV_VERSION'] = 'v0.10.21' From a74b9607b61f057c4d36b5de2cce01cf2dbf3a85 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 09:59:46 -0700 Subject: [PATCH 0443/1265] Add more logging --- script/cibuild | 1 + 1 file changed, 1 insertion(+) diff --git a/script/cibuild b/script/cibuild index 0e9f764f7c1..0f65c4eb3b2 100755 --- a/script/cibuild +++ b/script/cibuild @@ -94,6 +94,7 @@ def setup_nodenv(): os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' os.environ['PATH'] += '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] os.environ['NODENV_VERSION'] = 'v0.10.21' + print('configured nodenv') subprocess.call(["node", "--version"]) From e95224deabb7a0483b56d0caf1b2fcfd9bc5695d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 10:00:23 -0700 Subject: [PATCH 0444/1265] Remove += --- script/cibuild | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/cibuild b/script/cibuild index 0f65c4eb3b2..ce847177fa4 100755 --- a/script/cibuild +++ b/script/cibuild @@ -92,7 +92,7 @@ def run_script(script, args=[]): def setup_nodenv(): if os.path.isdir('/usr/local/share/nodenv'): os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' - os.environ['PATH'] += '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] + os.environ['PATH'] = '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] os.environ['NODENV_VERSION'] = 'v0.10.21' print('configured nodenv') subprocess.call(["node", "--version"]) From 687a512b11e05c768aba4860617460c157546e6c Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 10:03:16 -0700 Subject: [PATCH 0445/1265] Log node and npm versions --- script/cibuild | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/script/cibuild b/script/cibuild index ce847177fa4..90ee9e42f44 100755 --- a/script/cibuild +++ b/script/cibuild @@ -59,6 +59,8 @@ def main(): npm = 'npm.cmd' if PLATFORM == 'win32' else 'npm' execute([npm, 'install', 'npm@2.12.1']) + log_versions() + is_release = os.environ.has_key('ELECTRON_RELEASE') args = ['--target_arch=' + target_arch] if not is_release: @@ -89,13 +91,21 @@ def run_script(script, args=[]): subprocess.check_call([sys.executable, script] + args) +def log_versions(): + sys.stderr.write('\nnode --version\n') + sys.stderr.flush() + subprocess.call(["node", "--version"]) + + sys.stderr.write('\nnpm --version\n') + sys.stderr.flush() + subprocess.call(["npm", "--version"]) + + def setup_nodenv(): if os.path.isdir('/usr/local/share/nodenv'): os.environ['NODENV_ROOT'] = '/usr/local/share/nodenv' os.environ['PATH'] = '/usr/local/share/nodenv/bin:/usr/local/share/nodenv/shims:' + os.environ['PATH'] os.environ['NODENV_VERSION'] = 'v0.10.21' - print('configured nodenv') - subprocess.call(["node", "--version"]) if __name__ == '__main__': From 10860e4ec55f575ee0bd7f1b460ed4ced314ac7a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 10:14:47 -0700 Subject: [PATCH 0446/1265] Use npm.cmd on Windows to print version --- script/cibuild | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/script/cibuild b/script/cibuild index 90ee9e42f44..141d831a105 100755 --- a/script/cibuild +++ b/script/cibuild @@ -98,7 +98,8 @@ def log_versions(): sys.stderr.write('\nnpm --version\n') sys.stderr.flush() - subprocess.call(["npm", "--version"]) + npm = 'npm.cmd' if PLATFORM == 'win32' else 'npm' + subprocess.call([npm, "--version"]) def setup_nodenv(): From 4041d52864aef4c921c028d6d65a99707e0fafdd Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 10:15:31 -0700 Subject: [PATCH 0447/1265] Use single quotes --- script/cibuild | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/script/cibuild b/script/cibuild index 141d831a105..fda5817b6b8 100755 --- a/script/cibuild +++ b/script/cibuild @@ -94,12 +94,12 @@ def run_script(script, args=[]): def log_versions(): sys.stderr.write('\nnode --version\n') sys.stderr.flush() - subprocess.call(["node", "--version"]) + subprocess.call(['node', '--version']) sys.stderr.write('\nnpm --version\n') sys.stderr.flush() npm = 'npm.cmd' if PLATFORM == 'win32' else 'npm' - subprocess.call([npm, "--version"]) + subprocess.call([npm, '--version']) def setup_nodenv(): From f20950702dd6d93af706281b2227d27c26e9790f Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 6 Apr 2016 18:15:17 -0700 Subject: [PATCH 0448/1265] :arrow_up: asar@0.11 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 555648a2519..8d9e7564b3d 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "electron", "version": "0.37.5", "devDependencies": { - "asar": "^0.10.0", + "asar": "^0.11.0", "request": "*", "standard": "^6.0.8" }, From 4fc35a458767a8bf6345fdd39058c9df3b155316 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Tue, 5 Apr 2016 08:48:20 +0530 Subject: [PATCH 0449/1265] session: webRequest.OnHeadersReceived should follow server redirect Its required to follow server redirects. --- atom/browser/net/atom_network_delegate.cc | 2 ++ spec/api-web-request-spec.js | 35 +++++++++++++++++++---- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 91b63fada35..6bcc4bfeeb6 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -178,6 +178,8 @@ void ReadFromResponseObject(const base::DictionaryValue& response, !it.IsAtEnd(); it.Advance()) { const base::ListValue* list; + if (base::ToLowerASCII(it.key()) == "location") + (*headers)->ReplaceStatusLine("HTTP/1.1 302 Found"); if (it.value().GetAsList(&list)) { (*headers)->RemoveHeader(it.key()); for (size_t i = 0; i < list->GetSize(); ++i) { diff --git a/spec/api-web-request-spec.js b/spec/api-web-request-spec.js index abc4f9568cd..7169315ab1b 100644 --- a/spec/api-web-request-spec.js +++ b/spec/api-web-request-spec.js @@ -7,12 +7,18 @@ const session = remote.session describe('webRequest module', function () { var ses = session.defaultSession var server = http.createServer(function (req, res) { - res.setHeader('Custom', ['Header']) - var content = req.url - if (req.headers.accept === '*/*;test/header') { - content += 'header/received' + if (req.url == '/serverRedirect') { + res.statusCode = 301 + res.setHeader('Location', 'http://' + req.rawHeaders[1]) + res.end() + } else { + res.setHeader('Custom', ['Header']) + var content = req.url + if (req.headers.accept === '*/*;test/header') { + content += 'header/received' + } + res.end(content) } - res.end(content) }) var defaultURL = null @@ -297,6 +303,25 @@ describe('webRequest module', function () { } }) }) + + it('follows server redirect', function (done) { + ses.webRequest.onHeadersReceived(function (details, callback) { + var responseHeaders = details.responseHeaders + callback({ + responseHeaders: responseHeaders, + }) + }) + $.ajax({ + url: defaultURL + 'serverRedirect', + success: function (data, status, xhr) { + assert.equal(xhr.getResponseHeader('Custom'), 'Header') + done() + }, + error: function (xhr, errorType) { + done(errorType) + } + }) + }) }) describe('webRequest.onResponseStarted', function () { From d703a87317999ca722862521afb719b452c86872 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 8 Apr 2016 15:22:57 +0900 Subject: [PATCH 0450/1265] Update libchromiumcontent with disable_hidden.patch --- script/lib/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/lib/config.py b/script/lib/config.py index 707917f6f10..6cd31452caa 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '9229f39b44ca1dde25db9c648547861286b61935' +LIBCHROMIUMCONTENT_COMMIT = '4e506867ad95907e0a9cbec4ab3ee0f84214de94' PLATFORM = { 'cygwin': 'win32', From d156846036a3dc3fba67f6d799a2dfbb002d0571 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 8 Apr 2016 15:54:33 +0900 Subject: [PATCH 0451/1265] Add backgroundThrottling option to webPreferences --- atom/browser/api/atom_api_web_contents.cc | 23 ++++++++++++++++++----- atom/browser/api/atom_api_web_contents.h | 3 +++ docs/api/browser-window.md | 2 ++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index c2b04a87aa2..610d958ca1e 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -19,6 +19,7 @@ #include "atom/browser/web_view_guest_delegate.h" #include "atom/common/api/api_messages.h" #include "atom/common/api/event_emitter_caller.h" +#include "atom/common/mouse_util.h" #include "atom/common/native_mate_converters/blink_converter.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/content_converter.h" @@ -28,13 +29,14 @@ #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/value_converter.h" -#include "atom/common/mouse_util.h" +#include "atom/common/options_switches.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents_view.h" #include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/printing/print_preview_message_handler.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/common/view_messages.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/native_web_keyboard_event.h" @@ -212,7 +214,9 @@ content::ServiceWorkerContext* GetServiceWorkerContext( WebContents::WebContents(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), - type_(REMOTE) { + type_(REMOTE), + request_id_(0), + background_throttling_(true) { AttachAsUserData(web_contents); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); } @@ -220,7 +224,11 @@ WebContents::WebContents(content::WebContents* web_contents) WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options) : embedder_(nullptr), - request_id_(0) { + request_id_(0), + background_throttling_(true) { + // Read options. + options.Get("backgroundThrottling", &background_throttling_); + // Whether it is a guest WebContents. bool is_guest = false; options.Get("isGuest", &is_guest); @@ -744,8 +752,13 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) { // override the background color set by the user. // We have to call it right after LoadURL because the RenderViewHost is only // created after loading a page. - web_contents()->GetRenderViewHost()->GetWidget()->GetView() - ->SetBackgroundColor(SK_ColorTRANSPARENT); + const auto view = web_contents()->GetRenderWidgetHostView(); + view->SetBackgroundColor(SK_ColorTRANSPARENT); + + // For the same reason we can only disable hidden here. + const auto host = static_cast( + view->GetRenderWidgetHost()); + host->disable_hidden_ = !background_throttling_; } void WebContents::DownloadURL(const GURL& url) { diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 5fb1947f579..ee5a25b2666 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -296,6 +296,9 @@ class WebContents : public mate::TrackableObject, // Request id used for findInPage request. uint32_t request_id_; + // Whether background throttling is disabled. + bool background_throttling_; + DISALLOW_COPY_AND_ASSIGN(WebContents); }; diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 0e79659854a..877a6d0f745 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -179,6 +179,8 @@ The `webPreferences` option is an object that can have following properties: * `defaultMonospaceFontSize` Integer - Defaults to `13`. * `minimumFontSize` Integer - Defaults to `0`. * `defaultEncoding` String - Defaults to `ISO-8859-1`. +* `backgroundThrottling` Boolean - Whether to throttle animations and timers + when the page becomes background. Defaults to `true`. ## Events From 2f6796bd7f9427b9953c9e935fac68280fe5745b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 8 Apr 2016 15:57:14 +0900 Subject: [PATCH 0452/1265] Disable throttling in tests --- spec/static/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/static/main.js b/spec/static/main.js index 2707f6a686d..84e9ba3da55 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -83,7 +83,7 @@ app.on('ready', function () { width: 800, height: 600, webPreferences: { - javascript: true // Test whether web preferences crashes. + backgroundThrottling: false, } }) window.loadURL(url.format({ From 46365f407627d24d22a7c7a4d7ccbe8e575d2550 Mon Sep 17 00:00:00 2001 From: Pete Burgers Date: Fri, 8 Apr 2016 08:32:45 +0100 Subject: [PATCH 0453/1265] wait_for_exit param should be const --- atom/common/platform_util_linux.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/common/platform_util_linux.cc b/atom/common/platform_util_linux.cc index 0419c1143bc..e63dc83f609 100644 --- a/atom/common/platform_util_linux.cc +++ b/atom/common/platform_util_linux.cc @@ -15,7 +15,7 @@ namespace { bool XDGUtil(const std::string& util, const std::string& arg, - bool wait_for_exit) { + const bool wait_for_exit) { std::vector argv; argv.push_back(util); argv.push_back(arg); @@ -42,11 +42,11 @@ bool XDGUtil(const std::string& util, return (exit_code == 0); } -bool XDGOpen(const std::string& path, bool wait_for_exit) { +bool XDGOpen(const std::string& path, const bool wait_for_exit) { return XDGUtil("xdg-open", path, wait_for_exit); } -bool XDGEmail(const std::string& email, bool wait_for_exit) { +bool XDGEmail(const std::string& email, const bool wait_for_exit) { return XDGUtil("xdg-email", email, wait_for_exit); } From 00ff209fe7f6c1fb25238c46c25b09eedc01446d Mon Sep 17 00:00:00 2001 From: Pete Burgers Date: Fri, 8 Apr 2016 08:35:35 +0100 Subject: [PATCH 0454/1265] Ensure process is cleaned up, to avoid leaks --- atom/common/platform_util_linux.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/atom/common/platform_util_linux.cc b/atom/common/platform_util_linux.cc index e63dc83f609..9811c8760d0 100644 --- a/atom/common/platform_util_linux.cc +++ b/atom/common/platform_util_linux.cc @@ -32,8 +32,10 @@ bool XDGUtil(const std::string& util, if (!process.IsValid()) return false; - if (!wait_for_exit) + if (!wait_for_exit) { + base::EnsureProcessGetsReaped(process.Pid()); return true; + } int exit_code = -1; if (!process.WaitForExit(&exit_code)) From 3fb39ad3ef26b8556bbd2699b0f9e28d3c07e6eb Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Fri, 8 Apr 2016 14:03:57 +0530 Subject: [PATCH 0455/1265] provide option to override status line --- atom/browser/net/atom_network_delegate.cc | 16 ++++++++++++---- docs/api/session.md | 2 ++ spec/api-web-request-spec.js | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 6bcc4bfeeb6..dd3e83f0732 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -5,6 +5,7 @@ #include "atom/browser/net/atom_network_delegate.h" #include +#include #include "atom/common/native_mate_converters/net_converter.h" #include "base/stl_util.h" @@ -19,6 +20,9 @@ namespace atom { namespace { +using ResponseHeadersContainer = + std::pair*, const std::string&>; + const char* ResourceTypeToString(content::ResourceType type) { switch (type) { case content::RESOURCE_TYPE_MAIN_FRAME: @@ -170,16 +174,19 @@ void ReadFromResponseObject(const base::DictionaryValue& response, } void ReadFromResponseObject(const base::DictionaryValue& response, - scoped_refptr* headers) { + const ResponseHeadersContainer& container) { const base::DictionaryValue* dict; + std::string status_line; + if (!response.GetString("statusLine", &status_line)) + status_line = container.second; if (response.GetDictionary("responseHeaders", &dict)) { + auto headers = container.first; *headers = new net::HttpResponseHeaders(""); + (*headers)->ReplaceStatusLine(status_line); for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { const base::ListValue* list; - if (base::ToLowerASCII(it.key()) == "location") - (*headers)->ReplaceStatusLine("HTTP/1.1 302 Found"); if (it.value().GetAsList(&list)) { (*headers)->RemoveHeader(it.key()); for (size_t i = 0; i < list->GetSize(); ++i) { @@ -265,7 +272,8 @@ int AtomNetworkDelegate::OnHeadersReceived( request, callback, original, override, allowed); return HandleResponseEvent( - kOnHeadersReceived, request, callback, override, original); + kOnHeadersReceived, request, callback, + std::make_pair(override, original->GetStatusLine()), original); } void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request, diff --git a/docs/api/session.md b/docs/api/session.md index cc90a0b542c..9cccefcbdb6 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -446,6 +446,8 @@ The `callback` has to be called with an `response` object: * `cancel` Boolean * `responseHeaders` Object (optional) - When provided, the server is assumed to have responded with these headers. + * `statusLine` String (optional) - Should be provided when overriding `responseHeaders` + to change header status otherwise original response header's status will be used. #### `ses.webRequest.onResponseStarted([filter, ]listener)` diff --git a/spec/api-web-request-spec.js b/spec/api-web-request-spec.js index 7169315ab1b..211c69a1476 100644 --- a/spec/api-web-request-spec.js +++ b/spec/api-web-request-spec.js @@ -322,6 +322,25 @@ describe('webRequest module', function () { } }) }) + + it('can change the header status', function (done) { + ses.webRequest.onHeadersReceived(function (details, callback) { + var responseHeaders = details.responseHeaders + callback({ + responseHeaders: responseHeaders, + statusLine: "HTTP/1.1 404 Not Found" + }) + }) + $.ajax({ + url: defaultURL, + success: function (data, status, xhr) { + }, + error: function (xhr, errorType) { + assert.equal(xhr.getResponseHeader('Custom'), 'Header') + done() + } + }) + }) }) describe('webRequest.onResponseStarted', function () { From 37119768a092b6abacbd06a7dc37743d02a6aa63 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 7 Apr 2016 15:06:19 -0700 Subject: [PATCH 0456/1265] :arrow_up: node@5.10.0 --- .node-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.node-version b/.node-version index 346d9cae72c..339cbf236a7 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -v5.1.1 +v5.10.0 From 732697a8a28332e5c4f4bad991f0d7c3072f89ff Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Fri, 8 Apr 2016 08:53:58 -0700 Subject: [PATCH 0457/1265] Rename ATOM_SHELL_ASAR to ELECTRON_ASAR --- lib/common/asar_init.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/common/asar_init.js b/lib/common/asar_init.js index 0f728200880..13ee449a42c 100644 --- a/lib/common/asar_init.js +++ b/lib/common/asar_init.js @@ -1,10 +1,10 @@ ;(function () { return function (process, require, asarSource) { // Make asar.coffee accessible via "require". - process.binding('natives').ATOM_SHELL_ASAR = asarSource + process.binding('natives').ELECTRON_ASAR = asarSource // Monkey-patch the fs module. - require('ATOM_SHELL_ASAR').wrapFsWithAsar(require('fs')) + require('ELECTRON_ASAR').wrapFsWithAsar(require('fs')) // Make graceful-fs work with asar. var source = process.binding('natives') @@ -13,7 +13,7 @@ var nativeModule = new process.NativeModule('original-fs') nativeModule.cache() nativeModule.compile() -var asar = require('ATOM_SHELL_ASAR') +var asar = require('ELECTRON_ASAR') asar.wrapFsWithAsar(nativeModule.exports) module.exports = nativeModule.exports` } From c1b1348735e969c496cc87adbbc8819b4c98b24b Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Fri, 8 Apr 2016 11:19:36 -0700 Subject: [PATCH 0458/1265] Add `resourceType` arg to webContents `did-get-response-details` event. Fixes #5074 and follows @zcbenz's recommendation to expose ResourceTypeToString from atom_network_delegate publicly. Also adds testing for other arguments to the `did-get-response-details` events, since there were no existing tests for them. --- atom/browser/api/atom_api_web_contents.cc | 4 ++- atom/browser/net/atom_network_delegate.cc | 5 ++-- atom/browser/net/atom_network_delegate.h | 3 +++ spec/api-browser-window-spec.js | 26 +++++++++++++++++++ .../pages/did-get-response-details.html | 5 ++++ 5 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 spec/fixtures/pages/did-get-response-details.html diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 610d958ca1e..f8f8add95aa 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -14,6 +14,7 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" +#include "atom/browser/net/atom_network_delegate.h" #include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_guest_delegate.h" @@ -587,7 +588,8 @@ void WebContents::DidGetResourceResponseStart( details.http_response_code, details.method, details.referrer, - details.headers.get()); + details.headers.get(), + ResourceTypeToString(details.resource_type)); } void WebContents::DidGetRedirectForResourceRequest( diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 91b63fada35..9050fadbe50 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -10,15 +10,12 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/resource_request_info.h" #include "net/url_request/url_request.h" using content::BrowserThread; namespace atom { -namespace { - const char* ResourceTypeToString(content::ResourceType type) { switch (type) { case content::RESOURCE_TYPE_MAIN_FRAME: @@ -39,6 +36,8 @@ const char* ResourceTypeToString(content::ResourceType type) { return "other"; } } + +namespace { void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener, scoped_ptr details) { diff --git a/atom/browser/net/atom_network_delegate.h b/atom/browser/net/atom_network_delegate.h index 4f55f7c0986..ee159df60f1 100644 --- a/atom/browser/net/atom_network_delegate.h +++ b/atom/browser/net/atom_network_delegate.h @@ -15,6 +15,7 @@ #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" +#include "content/public/browser/resource_request_info.h" namespace extensions { class URLPattern; @@ -24,6 +25,8 @@ namespace atom { using URLPatterns = std::set; +const char* ResourceTypeToString(content::ResourceType type); + class AtomNetworkDelegate : public brightray::NetworkDelegate { public: using ResponseCallback = base::Callback; diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index a9940bde263..5775a89e294 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -101,6 +101,32 @@ describe('browser-window module', function () { w.loadURL('about:blank') }) + it('should emit did-get-response-details event', function (done) { + // expected {fileName: resourceType} pairs + var expectedResources = { + 'did-get-response-details.html': 'mainFrame', + 'logo.png': 'image' + } + var responses = 0; + w.webContents.on('did-get-response-details', function (event, status, newUrl, oldUrl, responseCode, method, referrer, headers, resourceType) { + responses++ + var fileName = newUrl.slice(newUrl.lastIndexOf('/') + 1) + var expectedType = expectedResources[fileName] + assert(!!expectedType, `Unexpected response details for ${newUrl}`) + assert(typeof status === 'boolean', 'status should be boolean') + assert.equal(responseCode, 200) + assert.equal(method, 'GET') + assert(typeof referrer === 'string', 'referrer should be string') + assert(!!headers, 'headers should be present') + assert(typeof headers === 'object', 'headers should be object') + assert.equal(resourceType, expectedType, 'Incorrect resourceType') + if (responses === Object.keys(expectedResources).length) { + done() + } + }) + w.loadURL('file://' + path.join(fixtures, 'pages', 'did-get-response-details.html')) + }) + it('should emit did-fail-load event for files that do not exist', function (done) { w.webContents.on('did-fail-load', function (event, code, desc, url, isMainFrame) { assert.equal(code, -6) diff --git a/spec/fixtures/pages/did-get-response-details.html b/spec/fixtures/pages/did-get-response-details.html new file mode 100644 index 00000000000..c98458c8ffa --- /dev/null +++ b/spec/fixtures/pages/did-get-response-details.html @@ -0,0 +1,5 @@ + + + + + From 15b042b5f6196c917169b9b865cbd1d8114e3c47 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Fri, 8 Apr 2016 12:55:20 -0700 Subject: [PATCH 0459/1265] Add support/tests for `did-get-response-details` event on --- lib/renderer/web-view/guest-view-internal.js | 2 +- spec/webview-spec.js | 29 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index efe462fc914..4f920707d1b 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -12,7 +12,7 @@ var WEB_VIEW_EVENTS = { 'did-frame-finish-load': ['isMainFrame'], 'did-start-loading': [], 'did-stop-loading': [], - 'did-get-response-details': ['status', 'newURL', 'originalURL', 'httpResponseCode', 'requestMethod', 'referrer', 'headers'], + 'did-get-response-details': ['status', 'newURL', 'originalURL', 'httpResponseCode', 'requestMethod', 'referrer', 'headers', 'resourceType'], 'did-get-redirect-request': ['oldURL', 'newURL', 'isMainFrame'], 'dom-ready': [], 'console-message': ['level', 'message', 'line', 'sourceId'], diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 0d32138906e..64b73d9d220 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -763,4 +763,33 @@ describe(' tag', function () { document.body.appendChild(webview) }) }) + + describe('did-get-response-details event', function () { + it('emits for the page and its resources', function (done) { + // expected {fileName: resourceType} pairs + var expectedResources = { + 'did-get-response-details.html': 'mainFrame', + 'logo.png': 'image' + } + var responses = 0; + webview.addEventListener('did-get-response-details', function (event) { + responses++ + var fileName = event.newURL.slice(event.newURL.lastIndexOf('/') + 1) + var expectedType = expectedResources[fileName] + assert(!!expectedType, `Unexpected response details for ${event.newURL}`) + assert(typeof event.status === 'boolean', 'status should be boolean') + assert.equal(event.httpResponseCode, 200) + assert.equal(event.requestMethod, 'GET') + assert(typeof event.referrer === 'string', 'referrer should be string') + assert(!!event.headers, 'headers should be present') + assert(typeof event.headers === 'object', 'headers should be object') + assert.equal(event.resourceType, expectedType, 'Incorrect resourceType') + if (responses === Object.keys(expectedResources).length) { + done() + } + }) + webview.src = 'file://' + path.join(fixtures, 'pages', 'did-get-response-details.html') + document.body.appendChild(webview) + }) + }) }) From 50f51899de609d75ea7a33dfb531b79f630d0780 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Fri, 8 Apr 2016 13:03:22 -0700 Subject: [PATCH 0460/1265] Document `resourceType` arg for `did-get-response-details` event. --- docs-translations/ko-KR/api/web-contents.md | 1 + docs-translations/ko-KR/api/web-view-tag.md | 1 + docs-translations/zh-CN/api/web-contents.md | 1 + docs-translations/zh-CN/api/web-view-tag.md | 1 + docs/api/web-contents.md | 1 + docs/api/web-view-tag.md | 1 + 6 files changed, 6 insertions(+) diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 2c066a94110..3e19fcd66bc 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -67,6 +67,7 @@ Returns: * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String 요청한 리소스에 관련된 자세한 정보를 사용할 수 있을 때 발생하는 이벤트입니다. `status`는 리소스를 다운로드하기 위한 소켓 연결을 나타냅니다. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index a40a22070f3..b2d22325840 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -495,6 +495,7 @@ Returns: * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String 요청한 리소스에 관해 자세한 내용을 알 수 있을 때 발생하는 이벤트입니다. `status`는 리소스를 다운로드할 소켓 커낵션을 나타냅니다. diff --git a/docs-translations/zh-CN/api/web-contents.md b/docs-translations/zh-CN/api/web-contents.md index 89d72f77aa7..54b9c56dcc6 100644 --- a/docs-translations/zh-CN/api/web-contents.md +++ b/docs-translations/zh-CN/api/web-contents.md @@ -63,6 +63,7 @@ var webContents = win.webContents; * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String 当有关请求资源的详细信息可用的时候发出事件. `status` 标识了 socket链接来下载资源. diff --git a/docs-translations/zh-CN/api/web-view-tag.md b/docs-translations/zh-CN/api/web-view-tag.md index e1e31f6f5a0..a1348c4d588 100644 --- a/docs-translations/zh-CN/api/web-view-tag.md +++ b/docs-translations/zh-CN/api/web-view-tag.md @@ -457,6 +457,7 @@ Returns: * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String 当获得返回详情的时候触发. diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index f2705582293..8fc7a959f69 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -68,6 +68,7 @@ Returns: * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String Emitted when details regarding a requested resource are available. `status` indicates the socket connection to download the resource. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 3bb71936be2..8df8d29347c 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -510,6 +510,7 @@ Returns: * `requestMethod` String * `referrer` String * `headers` Object +* `resourceType` String Fired when details regarding a requested resource is available. `status` indicates socket connection to download the resource. From 1a842bf9d50b8a424bcd7a29183c2b795fbb656b Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Fri, 8 Apr 2016 13:15:40 -0700 Subject: [PATCH 0461/1265] Fix trailing whitespace caught by linter. --- atom/browser/net/atom_network_delegate.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 9050fadbe50..1a83174abfd 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -36,7 +36,7 @@ const char* ResourceTypeToString(content::ResourceType type) { return "other"; } } - + namespace { void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener, From fca3a5f853073e3f7d320ddc1b7b45c2523d44b2 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Sun, 10 Apr 2016 11:23:26 +0800 Subject: [PATCH 0462/1265] Update quick-start.md Translation error about system events(line43). --- docs-translations/zh-CN/tutorial/quick-start.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/tutorial/quick-start.md b/docs-translations/zh-CN/tutorial/quick-start.md index 8d948036bfa..8bdcc05cb02 100644 --- a/docs-translations/zh-CN/tutorial/quick-start.md +++ b/docs-translations/zh-CN/tutorial/quick-start.md @@ -40,7 +40,7 @@ your-app/ ``` **注意**:如果 `main` 字段没有在 `package.json` 声明,Electron会优先加载 `index.js`。 -`main.js` 应该用于创建窗口和处理系统时间,一个典型的例子如下: +`main.js` 应该用于创建窗口和处理系统事件,一个典型的例子如下: ```javascript var app = require('app'); // 控制应用生命周期的模块。 var BrowserWindow = require('browser-window'); // 创建原生浏览器窗口的模块 From 0a806182631a0919eae0390cc3080c5102040b11 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 10:18:47 +0900 Subject: [PATCH 0463/1265] :memo: Add missing changes [ci skip] --- docs-translations/ko-KR/api/auto-updater.md | 2 +- docs-translations/ko-KR/api/crash-reporter.md | 2 +- docs-translations/ko-KR/tutorial/application-distribution.md | 2 +- docs-translations/ko-KR/tutorial/application-packaging.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs-translations/ko-KR/api/auto-updater.md b/docs-translations/ko-KR/api/auto-updater.md index e5121d0f9b1..9d081967b99 100644 --- a/docs-translations/ko-KR/api/auto-updater.md +++ b/docs-translations/ko-KR/api/auto-updater.md @@ -95,5 +95,5 @@ Returns: [squirrel-mac]: https://github.com/Squirrel/Squirrel.Mac [server-support]: https://github.com/Squirrel/Squirrel.Mac#server-support [squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows -[installer]: https://github.com/atom/grunt-electron-installer +[installer]: https://github.com/electron/grunt-electron-installer [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx diff --git a/docs-translations/ko-KR/api/crash-reporter.md b/docs-translations/ko-KR/api/crash-reporter.md index c1437571d3f..fafc5d9fa32 100644 --- a/docs-translations/ko-KR/api/crash-reporter.md +++ b/docs-translations/ko-KR/api/crash-reporter.md @@ -20,7 +20,7 @@ crashReporter.start({ 있습니다: * [socorro](https://github.com/mozilla/socorro) -* [mini-breakpad-server](https://github.com/atom/mini-breakpad-server) +* [mini-breakpad-server](https://github.com/electron/mini-breakpad-server) ## Methods diff --git a/docs-translations/ko-KR/tutorial/application-distribution.md b/docs-translations/ko-KR/tutorial/application-distribution.md index 7072d7c4d95..445a9dda21d 100644 --- a/docs-translations/ko-KR/tutorial/application-distribution.md +++ b/docs-translations/ko-KR/tutorial/application-distribution.md @@ -30,7 +30,7 @@ electron/resources/app ## asar로 앱 패키징 하기 -소스파일 전체를 복사해서 배포하는 것과는 별개로 [asar](https://github.com/atom/asar) +소스파일 전체를 복사해서 배포하는 것과는 별개로 [asar](https://github.com/electron/asar) 아카이브를 통해 어플리케이션의 소스코드가 사용자에게 노출되는 것을 방지할 수 있습니다. `asar` 아카이브를 사용할 땐 단순히 `app` 폴더 대신에 어플리케이션을 패키징한 diff --git a/docs-translations/ko-KR/tutorial/application-packaging.md b/docs-translations/ko-KR/tutorial/application-packaging.md index 9183f0eafe9..a33e2eef96c 100644 --- a/docs-translations/ko-KR/tutorial/application-packaging.md +++ b/docs-translations/ko-KR/tutorial/application-packaging.md @@ -179,4 +179,4 @@ $ asar pack app app.asar --unpack *.node 포함되어 있습니다. 사용자에게 어플리케이션을 배포할 때 반드시 해당 폴더도 같이 배포해야 합니다. -[asar]: https://github.com/atom/asar +[asar]: https://github.com/electron/asar From 1fe97ddf2ee06143235faca336392ed0b927b71c Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 10:29:24 +0900 Subject: [PATCH 0464/1265] :memo: Fix url locale [ci skip] --- docs-translations/ko-KR/api/frameless-window.md | 2 +- docs-translations/ko-KR/api/menu.md | 2 +- docs-translations/ko-KR/api/remote.md | 2 +- docs-translations/ko-KR/api/synopsis.md | 2 +- docs-translations/ko-KR/development/coding-style.md | 8 ++++---- docs-translations/ko-KR/faq/electron-faq.md | 8 ++++---- docs-translations/ko-KR/styleguide.md | 12 ++++++------ .../ko-KR/tutorial/using-native-node-modules.md | 2 +- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/docs-translations/ko-KR/api/frameless-window.md b/docs-translations/ko-KR/api/frameless-window.md index 3d3e63312c7..7bcdeb4a60b 100644 --- a/docs-translations/ko-KR/api/frameless-window.md +++ b/docs-translations/ko-KR/api/frameless-window.md @@ -1,6 +1,6 @@ # Frameless Window -Frameless Window는 [창 테두리](https://developer.mozilla.org/en-US/docs/Glossary/Chrome)가 +Frameless Window는 [창 테두리](https://developer.mozilla.org/ko/docs/Glossary/Chrome)가 없는 윈도우를 말합니다. 이 기능은 윈도우의 일부분인 툴바와 같이 웹 페이지의 일부분이 아닌 부분을 보이지 않도록 합니다. [`BrowserWindow`](browser-window.md) 클래스의 옵션에서 설정할 수 있습니다. diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 7f1a5af16c6..69d03c09413 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -1,6 +1,6 @@ # Menu -`menu` 클래스는 어플리케이션 메뉴와 [컨텍스트 메뉴](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/ContextMenus)를 +`menu` 클래스는 어플리케이션 메뉴와 [컨텍스트 메뉴](https://developer.mozilla.org/ko/docs/Mozilla/Tech/XUL/PopupGuide/ContextMenus)를 만들 때 사용됩니다. 이 모듈은 메인 프로세스용 모듈이지만 `remote` 모듈을 통해 랜더러 프로세스에서도 사용할 수 있습니다. diff --git a/docs-translations/ko-KR/api/remote.md b/docs-translations/ko-KR/api/remote.md index 3a09084acde..a483850920d 100644 --- a/docs-translations/ko-KR/api/remote.md +++ b/docs-translations/ko-KR/api/remote.md @@ -34,7 +34,7 @@ win.loadURL('https://github.com'); 않습니다. 대신에 이 `BrowserWindow` 객체는 메인 프로세스에서 생성되며 랜더러 프로세스에 `win` 객체와 같이 이에 대응하는 remote 객체를 반환합니다. -참고로 remote를 통해선 [enumerable 속성](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)을 +참고로 remote를 통해선 [enumerable 속성](https://developer.mozilla.org/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)을 가진 프로퍼티에만 접근할 수 있습니다. ## Remote 객체의 생명 주기 diff --git a/docs-translations/ko-KR/api/synopsis.md b/docs-translations/ko-KR/api/synopsis.md index b392f206c13..47771b23ceb 100644 --- a/docs-translations/ko-KR/api/synopsis.md +++ b/docs-translations/ko-KR/api/synopsis.md @@ -78,5 +78,5 @@ require('electron').hideInternalModules() ``` [gui]: https://en.wikipedia.org/wiki/Graphical_user_interface -[destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment +[destructuring-assignment]: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment [issue-387]: https://github.com/electron/electron/issues/387 diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index cb3e68ce25b..b961ff3e1e3 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -30,13 +30,13 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 [github/atom](https://github.com/github/atom)에서 사용되는 모듈의 이름은 보통 `module-name` 형식이기 때문입니다. 이 규칙은 '.js' 파일에만 적용됩니다. * 적절한 곳에 새로운 ES6/ES2015 문법을 사용해도 됩니다. - * [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) + * [`const`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/const) 는 requires와 다른 상수에 사용합니다 - * [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) + * [`let`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/let) 은 변수를 정의할 때 사용합니다 - * [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) + * [Arrow functions](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions) 는 `function () { }` 표현 대신에 사용합니다 - * [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) + * [Template literals](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals) 는 `+`로 문자열을 합치는 대신 사용합니다. ## API 이름 diff --git a/docs-translations/ko-KR/faq/electron-faq.md b/docs-translations/ko-KR/faq/electron-faq.md index ea9953fcd4c..5382372bfbb 100644 --- a/docs-translations/ko-KR/faq/electron-faq.md +++ b/docs-translations/ko-KR/faq/electron-faq.md @@ -147,7 +147,7 @@ npm uninstall -g electron [memory-management]: https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management [variable-scope]: https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx [electron-module]: https://www.npmjs.com/package/electron -[storage]: https://developer.mozilla.org/en-US/docs/Web/API/Storage -[local-storage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage -[session-storage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage -[indexed-db]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API +[storage]: https://developer.mozilla.org/ko/docs/Web/API/Storage +[local-storage]: https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage +[session-storage]: https://developer.mozilla.org/ko/docs/Web/API/Window/sessionStorage +[indexed-db]: https://developer.mozilla.org/ko/docs/Web/API/IndexedDB_API diff --git a/docs-translations/ko-KR/styleguide.md b/docs-translations/ko-KR/styleguide.md index 12dae10ec94..91aa233dd4d 100644 --- a/docs-translations/ko-KR/styleguide.md +++ b/docs-translations/ko-KR/styleguide.md @@ -50,7 +50,7 @@ Electron 문서 구조를 이해하는 데 참고할 수 있는 유용한 도움 ### Methods -[Method](https://developer.mozilla.org/en-US/docs/Glossary/Method) 문서의 +[Method](https://developer.mozilla.org/ko/docs/Glossary/Method) 문서의 예제입니다: --- @@ -66,16 +66,16 @@ Electron 문서 구조를 이해하는 데 참고할 수 있는 유용한 도움 묶어 이 인수가 다른 인수뒤에서 선택적으로 사용될 수 있다는 것을 표시합니다. 메서드 이름 하단에선 각 인수에 대해 자세한 설명을 합니다. 인수의 타입은: -[`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), -[`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), -[`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), -[`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) +[`String`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String), +[`Number`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number), +[`Object`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object), +[`Array`](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array) 와 같은 일반적으로 쓰이는 타입 중 하나를 받거나 Electron의 [`webContent`](api/web-content.md) 같은 커스텀 타입을 받습니다. ### Events -[Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) 문서의 예제입니다: +[Event](https://developer.mozilla.org/ko/docs/Web/API/Event) 문서의 예제입니다: --- diff --git a/docs-translations/ko-KR/tutorial/using-native-node-modules.md b/docs-translations/ko-KR/tutorial/using-native-node-modules.md index ed00d7ae608..9c32e33751e 100644 --- a/docs-translations/ko-KR/tutorial/using-native-node-modules.md +++ b/docs-translations/ko-KR/tutorial/using-native-node-modules.md @@ -11,7 +11,7 @@ Electron의 V8 버전에 맞춰 네이티브 모듈을 다시 빌드하고 헤 node.js의 버전을 확인할 필요가 있습니다. Electron에서 사용하는 node 버전은 [releases](https://github.com/electron/electron/releases)에서 확인할 수 있으며 `process.version`을 출력하여 버전을 확인할 수도 있습니다. -([시작하기](https://github.com/electron/electron/blob/master/docs/tutorial/quick-start.md)의 +([시작하기](https://github.com/electron/electron/blob/master/docs-translations/ko-KR/tutorial/quick-start.md)의 예제를 참고하세요) 혹시 직접 만든 네이티브 모듈이 있다면 [NAN](https://github.com/nodejs/nan/) 모듈을 From 3c44dfa21042a25b5a43821c5a8107ac8ffd6103 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 10:33:47 +0900 Subject: [PATCH 0465/1265] :memo: Fix grammatical typos [ci skip] --- docs-translations/ko-KR/api/crash-reporter.md | 2 +- docs-translations/ko-KR/api/remote.md | 2 +- docs-translations/ko-KR/api/tray.md | 2 +- .../ko-KR/development/atom-shell-vs-node-webkit.md | 2 +- .../ko-KR/development/setting-up-symbol-server.md | 4 ++-- docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs-translations/ko-KR/api/crash-reporter.md b/docs-translations/ko-KR/api/crash-reporter.md index fafc5d9fa32..382fcd5924b 100644 --- a/docs-translations/ko-KR/api/crash-reporter.md +++ b/docs-translations/ko-KR/api/crash-reporter.md @@ -43,7 +43,7 @@ crashReporter.start({ **참고:** OS X에선 Windows와 Linux의 `breakpad`와 달리 새로운 `crashpad` 클라이언트를 사용합니다. 오류 수집 기능을 활성화 시키려면 오류를 수집하고 싶은 메인 프로세스나 랜더러 프로세스에서 `crashReporter.start` 메서드를 호출하여 `crashpad`를 -초기화 해야합니다. +초기화해야 합니다. ### `crashReporter.getLastCrashReport()` diff --git a/docs-translations/ko-KR/api/remote.md b/docs-translations/ko-KR/api/remote.md index a483850920d..ab05d838cc5 100644 --- a/docs-translations/ko-KR/api/remote.md +++ b/docs-translations/ko-KR/api/remote.md @@ -5,7 +5,7 @@ Electron의 메인 프로세스에선 GUI와 관련 있는(`dialog`, `menu`등) 모듈만 사용할 수 있습니다. 랜더러 프로세스에서 이러한 모듈들을 사용하려면 `ipc` 모듈을 통해 메인 -프로세스와 inter-process 통신을 해야합니다. 또한, `remote` 모듈을 사용하면 +프로세스와 inter-process 통신을 해야 합니다. 또한, `remote` 모듈을 사용하면 inter-process 통신을 하지 않고도 간단한 API를 통해 직접 메인 프로세스의 모듈과 메서드를 사용할 수 있습니다. 이 개념은 Java의 [RMI][rmi]와 비슷합니다. diff --git a/docs-translations/ko-KR/api/tray.md b/docs-translations/ko-KR/api/tray.md index 28a44199c00..b0293d40fcb 100644 --- a/docs-translations/ko-KR/api/tray.md +++ b/docs-translations/ko-KR/api/tray.md @@ -11,7 +11,7 @@ const Tray = electron.Tray; var appIcon = null; app.on('ready', function(){ - appIcon = new Tray('/path/to/my/icon'); // 현재 어플리케이션 디렉터리를 기준으로 하려면 `__dirname + '/images/tray.png'` 형식으로 입력해야합니다. + appIcon = new Tray('/path/to/my/icon'); // 현재 어플리케이션 디렉터리를 기준으로 하려면 `__dirname + '/images/tray.png'` 형식으로 입력해야 합니다. var contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }, diff --git a/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md b/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md index f59c7ceb70b..21972d2f38a 100644 --- a/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md +++ b/docs-translations/ko-KR/development/atom-shell-vs-node-webkit.md @@ -16,7 +16,7 @@ main 필드에 메인 웹 페이지(index.html) URL을 지정하면 어플리케 Electron에선 JavaScript를 엔트리 포인트로 사용합니다. URL을 직접 제공하는 대신 API를 사용하여 직접 브라우저 창과 HTML 파일을 로드할 수 있습니다. 또한 윈도우의 종료시기를 -결정하는 이벤트를 리스닝해야합니다. +결정하는 이벤트를 리스닝해야 합니다. Electron은 Node.js 런타임과 비슷하게 작동합니다. Electron의 API는 저수준이기에 브라우저 테스팅을 위해 [PhantomJS](http://phantomjs.org/)를 사용할 수도 있습니다. diff --git a/docs-translations/ko-KR/development/setting-up-symbol-server.md b/docs-translations/ko-KR/development/setting-up-symbol-server.md index e2bcd173a4b..abfda6851bf 100644 --- a/docs-translations/ko-KR/development/setting-up-symbol-server.md +++ b/docs-translations/ko-KR/development/setting-up-symbol-server.md @@ -14,7 +14,7 @@ 공식적인 Electron의 심볼 서버의 URL은 http://54.249.141.255:8086/atom-shell/symbols 입니다. 일단 이 URL에 직접적으로 -접근할 수는 없습니다: 디버깅 툴에 심볼의 경로를 추가해야합니다. 아래의 예제를 참고하면 +접근할 수는 없습니다: 디버깅 툴에 심볼의 경로를 추가해야 합니다. 아래의 예제를 참고하면 로컬 캐시 디렉터리는 서버로부터 중복되지 않게 PDB를 가져오는데 사용됩니다. `c:\code\symbols` 캐시 디렉터리를 사용중인 OS에 맞춰 적당한 경로로 변경하세요. @@ -30,7 +30,7 @@ SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols Windbg 메뉴 또는 `.sympath` 커맨드를 이용하여 환경에 `_NT_SYMBOL_PATH` 문자열을 설정합니다. 만약 Microsoft의 심볼서버로부터 심볼을 받아오려면 다음과 같이 리스팅을 -먼저 해야합니다: +먼저해야 합니다: ``` SRV*c:\code\symbols\*http://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols diff --git a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md index 2f15a3532ee..1437bbde92c 100644 --- a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md +++ b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md @@ -13,7 +13,7 @@ Pepper 플래시 플러그인을 사용하려면 Pepper 플래시 플러그인 플러그인을 사용하려면 Electron 커맨드 라인에 `--ppapi-flash-path` 와 `ppapi-flash-version` 플래그를 app의 ready 이벤트가 호출되기 전에 추가해야 합니다. -그리고 `browser-window`에 `plugins` 스위치도 추가해야합니다. +그리고 `browser-window`에 `plugins` 스위치도 추가해야 합니다. ```javascript // 플래시 플러그인의 위치를 설정합니다. From c1f64b3f85eafe00fb87941d3bf5d6aa306a2019 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 10:34:56 +0900 Subject: [PATCH 0466/1265] :memo: Add missing changes [ci skip] --- docs-translations/ko-KR/development/coding-style.md | 2 +- .../ko-KR/tutorial/mac-app-store-submission-guide.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index b961ff3e1e3..9c15f677fe2 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -26,7 +26,7 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 * [표준](http://npm.im/standard) JavaScript 코딩 스타일을 사용합니다. * Google의 코딩 스타일에도 맞추기 위해 파일의 끝에는 **절대** 개행을 삽입해선 안됩니다. * 파일 이름의 공백은 `_`대신에 `-`을 사용하여야 합니다. 예를 들어 -`file_name.js`를 `file-name.js`로 고쳐야합니다. 왜냐하면 +`file_name.js`를 `file-name.js`로 고쳐야 합니다. 왜냐하면 [github/atom](https://github.com/github/atom)에서 사용되는 모듈의 이름은 보통 `module-name` 형식이기 때문입니다. 이 규칙은 '.js' 파일에만 적용됩니다. * 적절한 곳에 새로운 ES6/ES2015 문법을 사용해도 됩니다. diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index ee70114fad1..43d707b7942 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -17,7 +17,7 @@ Electron은 v0.34.0 버전부터 앱 패키지를 Mac App Store(MAS)에 제출 다음 몇 가지 간단한 절차에 따라 앱 스토어에 어플리케이션을 등록하는 방법을 알아봅니다. 한가지, 이 절차는 제출한 앱이 Apple로부터 승인되는 것을 보장하지 않습니다. 따라서 여전히 Apple의 [Submitting Your App][submitting-your-app] 가이드를 숙지하고 있어야 -하며 앱 스토어 제출 요구 사항을 확실히 인지하고 있어야합니다. +하며 앱 스토어 제출 요구 사항을 확실히 인지하고 있어야 합니다. ### 인증서 취득 From a048bddaa55bb055558676801bf56c456512c3a3 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 10:51:31 +0900 Subject: [PATCH 0467/1265] :memo: Fix url to relative [ci skip] --- docs-translations/ko-KR/api/menu.md | 2 +- docs-translations/ko-KR/tutorial/using-native-node-modules.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 69d03c09413..7ab9c6c02aa 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -382,4 +382,4 @@ OS X에선 지정한 어플리케이션 메뉴에 상관없이 메뉴의 첫번 ``` [AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html -[setMenu]: https://github.com/electron/electron/blob/master/docs-translations/ko-KR/api/browser-window.md#winsetmenumenu-linux-windows +[setMenu]: ./browser-window.md#winsetmenumenu-linux-windows diff --git a/docs-translations/ko-KR/tutorial/using-native-node-modules.md b/docs-translations/ko-KR/tutorial/using-native-node-modules.md index 9c32e33751e..e153b265b63 100644 --- a/docs-translations/ko-KR/tutorial/using-native-node-modules.md +++ b/docs-translations/ko-KR/tutorial/using-native-node-modules.md @@ -11,7 +11,7 @@ Electron의 V8 버전에 맞춰 네이티브 모듈을 다시 빌드하고 헤 node.js의 버전을 확인할 필요가 있습니다. Electron에서 사용하는 node 버전은 [releases](https://github.com/electron/electron/releases)에서 확인할 수 있으며 `process.version`을 출력하여 버전을 확인할 수도 있습니다. -([시작하기](https://github.com/electron/electron/blob/master/docs-translations/ko-KR/tutorial/quick-start.md)의 +([시작하기](./quick-start.md)의 예제를 참고하세요) 혹시 직접 만든 네이티브 모듈이 있다면 [NAN](https://github.com/nodejs/nan/) 모듈을 From 726d0d6b6063e95f6d5ee86ab58c7a50f77d6a8f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 11 Apr 2016 11:18:25 +0900 Subject: [PATCH 0468/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/auto-updater.md | 15 +++++++++++++-- docs-translations/ko-KR/api/browser-window.md | 2 ++ docs-translations/ko-KR/api/web-view-tag.md | 8 +++++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/docs-translations/ko-KR/api/auto-updater.md b/docs-translations/ko-KR/api/auto-updater.md index 9d081967b99..e699108a649 100644 --- a/docs-translations/ko-KR/api/auto-updater.md +++ b/docs-translations/ko-KR/api/auto-updater.md @@ -2,8 +2,14 @@ 이 모듈은 `Squirrel` 자동 업데이트 프레임워크의 인터페이스를 제공합니다. -[electron-release-server](https://github.com/ArekSredzki/electron-release-server)를 -포크하면 어플리케이션을 배포하기 위한 멀티 플랫폼 릴리즈 서버를 손쉽게 구축할 수 있습니다. +다음 프로젝트 중 하나를 택하여 사용하면, 어플리케이션을 배포하기 위한 멀티 플랫폼 +릴리즈 서버를 손쉽게 구축할 수 있습니다: + +- [electron-release-server][electron-release-server]: *완벽하게 모든 기능을 +지원하는 electron 어플리케이션을 위한 자가 호스트 릴리즈 서버입니다. auto-updater와 +호환됩니다* +- [squirrel-updates-server][squirrel-updates-server]: *GitHub 릴리즈를 사용하는 +Squirrel.Mac 와 Squirrel.Windows를 위한 간단한 node.js 기반 서버입니다* ## 플랫폼별 참고 사항 @@ -16,6 +22,9 @@ OS X에선 `auto-updater` 모듈이 [Squirrel.Mac][squirrel-mac]를 기반으로 따라서 이 모듈을 작동시키기 위해 특별히 준비해야 할 작업은 없습니다. 서버 사이드 요구 사항은 [서버 지원][server-support]을 참고하세요. +**참고:** Mac OS X에서 자동 업데이트를 지원하려면 반드시 사인이 되어있어야 합니다. +이것은 `Squirrel.Mac`의 요구사항입니다. + ### Windows Windows에선 `auto-updater` 모듈을 사용하기 전에 어플리케이션을 사용자의 장치에 @@ -97,3 +106,5 @@ Returns: [squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows [installer]: https://github.com/electron/grunt-electron-installer [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx +[electron-release-server]: https://github.com/ArekSredzki/electron-release-server +[squirrel-updates-server]: https://github.com/Aluxian/squirrel-updates-server diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index e93956b6fd8..45b7d308308 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -173,6 +173,8 @@ win.show(); * `defaultMonospaceFontSize` Integer - 기본값 `13`. * `minimumFontSize` Integer - 기본값 `0`. * `defaultEncoding` String - 기본값 `ISO-8859-1`. +* `backgroundThrottling` Boolean - 페이지가 백그라운드 상태에 진입할 때 애니메이션과 + 타이머에 스로틀을 적용할지 여부입니다. 기본값은 `true`입니다. ## Events diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index a40a22070f3..c5daaeab265 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -17,9 +17,15 @@ 수 있습니다: ```html - + ``` +주의할 점은 `webview` 태그의 스타일은 전통적인 flexbox 레이아웃을 사용했을 때 자식 +`object` 요소가 해당 `webview` 컨테이너의 전체 높이와 넓이를 확실히 채우도록 +내부적으로 `display:flex;`를 사용합니다. (v0.36.11 부터) 따라서 인라인 레이아웃을 +위해 `display:inline-flex;`를 쓰지 않는 한, 기본 `display:flex;` CSS 속성을 +덮어쓰지 않도록 주의해야 합니다. + 게스트 컨텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 응답을 받을 수 있습니다. 다음 예제를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 이벤트를 확인하고 두번째 리스너는 페이지의 로딩이 끝난시점을 확인합니다. 그리고 From 056aaa2a62ea8fe875a8202578802b7485ee5cfd Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 11 Apr 2016 19:30:59 +0900 Subject: [PATCH 0469/1265] Update brightray for #4931 --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index 242feb1c817..f7fa7efc287 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 242feb1c817565de6592e9e672c136635bfff453 +Subproject commit f7fa7efc28798bddd302ef5849a74c8bef164347 From 337d10510486c9c05afe39eb4c0954dd8765ec24 Mon Sep 17 00:00:00 2001 From: zenganshao Date: Mon, 11 Apr 2016 22:40:12 +0800 Subject: [PATCH 0470/1265] Delete the extra text --- docs-translations/zh-CN/tutorial/application-distribution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/tutorial/application-distribution.md b/docs-translations/zh-CN/tutorial/application-distribution.md index f3cf3692b5d..2dca19342ad 100644 --- a/docs-translations/zh-CN/tutorial/application-distribution.md +++ b/docs-translations/zh-CN/tutorial/application-distribution.md @@ -27,7 +27,7 @@ electron/resources/app ## 将你的应用程序打包成一个文件 -除了通过拷贝所有的资源文件来分发你的应用程序之外,你可以可以通过打包你的应用程序为一个 [asar](https://github.com/atom/asar) 库文件以避免暴露你的源代码。 +除了通过拷贝所有的资源文件来分发你的应用程序之外,你可以通过打包你的应用程序为一个 [asar](https://github.com/atom/asar) 库文件以避免暴露你的源代码。 为了使用一个 `asar` 库文件代替 `app` 文件夹,你需要修改这个库文件的名字为 `app.asar` , 然后将其放到 Electron 的资源文件夹下,然后 Electron 就会试图读取这个库文件并从中启动。 From 5efa075aca6237814667cf78fc04d68b77953f5b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 12 Apr 2016 14:57:40 +0900 Subject: [PATCH 0471/1265] spec: preload attribute should work without script tag in page --- spec/webview-spec.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 64b73d9d220..c9f44747bef 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -155,6 +155,18 @@ describe(' tag', function () { webview.src = 'file://' + fixtures + '/pages/e.html' document.body.appendChild(webview) }) + + it('works without script tag in page', function (done) { + var listener = function (e) { + assert.equal(e.message, 'function object object') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('preload', fixtures + '/module/preload.js') + webview.src = 'file://' + fixtures + '/pages/base-page.html' + document.body.appendChild(webview) + }) }) describe('httpreferrer attribute', function () { From bb70defcb8236aebaa23032d52c575ae8bd00c3c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 12 Apr 2016 15:10:26 +0900 Subject: [PATCH 0472/1265] spec: webview should work without script tag in page --- spec/fixtures/pages/ping.html | 7 +++++++ spec/fixtures/pages/webview-no-script.html | 5 +++++ spec/webview-spec.js | 11 ++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 spec/fixtures/pages/ping.html create mode 100644 spec/fixtures/pages/webview-no-script.html diff --git a/spec/fixtures/pages/ping.html b/spec/fixtures/pages/ping.html new file mode 100644 index 00000000000..5bd6a8772a9 --- /dev/null +++ b/spec/fixtures/pages/ping.html @@ -0,0 +1,7 @@ + + + + + diff --git a/spec/fixtures/pages/webview-no-script.html b/spec/fixtures/pages/webview-no-script.html new file mode 100644 index 00000000000..00b8f21bde7 --- /dev/null +++ b/spec/fixtures/pages/webview-no-script.html @@ -0,0 +1,5 @@ + + + + + diff --git a/spec/webview-spec.js b/spec/webview-spec.js index c9f44747bef..10758a0a436 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -2,7 +2,7 @@ const assert = require('assert') const path = require('path') const http = require('http') const url = require('url') -const {app, session} = require('electron').remote +const {app, session, ipcMain, BrowserWindow} = require('electron').remote describe(' tag', function () { this.timeout(10000) @@ -20,6 +20,15 @@ describe(' tag', function () { } }) + it('works without script tag in page', function (done) { + let w = new BrowserWindow({show: false}) + ipcMain.once('pong', function () { + w.destroy() + done() + }) + w.loadURL('file://' + fixtures + '/pages/webview-no-script.html') + }) + describe('src attribute', function () { it('specifies the page to load', function (done) { webview.addEventListener('console-message', function (e) { From 17446f42848d2215cbe96d8381eada07d8dfe93e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 12 Apr 2016 15:11:10 +0900 Subject: [PATCH 0473/1265] Make sure every page will get a script context created --- atom/renderer/atom_render_view_observer.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/atom/renderer/atom_render_view_observer.cc b/atom/renderer/atom_render_view_observer.cc index bbaea351378..96dffbd512a 100644 --- a/atom/renderer/atom_render_view_observer.cc +++ b/atom/renderer/atom_render_view_observer.cc @@ -27,6 +27,7 @@ #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebKit.h" +#include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebView.h" #include "ui/base/resource/resource_bundle.h" #include "native_mate/dictionary.h" @@ -88,6 +89,9 @@ void AtomRenderViewObserver::DidCreateDocumentElement( blink::WebLocalFrame* frame) { document_created_ = true; + // Make sure every page will get a script context created. + frame->executeScript(blink::WebScriptSource("void 0")); + // Read --zoom-factor from command line. std::string zoom_factor_str = base::CommandLine::ForCurrentProcess()-> GetSwitchValueASCII(switches::kZoomFactor); From 2fbe06a2a559a853dcba5bc6e6cfbe5d5a3c12a1 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 12 Apr 2016 16:36:12 +0900 Subject: [PATCH 0474/1265] Handle the Page.reload command coming from devtools --- atom/browser/api/atom_api_web_contents.cc | 4 ++++ atom/browser/api/atom_api_web_contents.h | 3 +++ lib/browser/api/web-contents.js | 6 ++++++ vendor/brightray | 2 +- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index f8f8add95aa..985c541a15a 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -635,6 +635,10 @@ void WebContents::DidUpdateFaviconURL( Emit("page-favicon-updated", unique_urls); } +void WebContents::DevToolsReloadPage() { + Emit("devtools-reload-page"); +} + void WebContents::DevToolsFocused() { Emit("devtools-focused"); } diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index ee5a25b2666..0cb2a348e17 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -251,6 +251,9 @@ class WebContents : public mate::TrackableObject, void MediaStoppedPlaying(const MediaPlayerId& id) override; void DidChangeThemeColor(SkColor theme_color) override; + // brightray::InspectableWebContentsDelegate: + void DevToolsReloadPage() override; + // brightray::InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 2ec7c14bae1..bc32161e77e 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -155,6 +155,11 @@ let wrapWebContents = function (webContents) { }) }) + // The devtools requests the webContents to reload. + webContents.on('devtools-reload-page', function () { + webContents.reload() + }) + // Delays the page-title-updated event to next tick. webContents.on('-page-title-updated', function (...args) { setImmediate(() => { @@ -168,6 +173,7 @@ let wrapWebContents = function (webContents) { deprecate.event(webContents, 'page-title-set', 'page-title-updated', function (...args) { return this.emit.apply(this, ['page-title-set'].concat(args)) }) + webContents.printToPDF = function (options, callback) { var printingSetting printingSetting = { diff --git a/vendor/brightray b/vendor/brightray index f7fa7efc287..cedb1131662 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit f7fa7efc28798bddd302ef5849a74c8bef164347 +Subproject commit cedb11316627ac0e01a5dcd38e75bd1c5a6afa17 From 99a9aa085efb8c637319a9056339c4a5e16cdf76 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 11:02:34 +0900 Subject: [PATCH 0475/1265] views: Delay the focus/blur event to next tick --- atom/browser/native_window_views.cc | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 59d3556d05e..93e43661302 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -15,6 +15,7 @@ #include "base/strings/utf_string_conversions.h" #include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents_view.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/native_web_keyboard_event.h" #include "native_mate/dictionary.h" #include "ui/aura/window_tree_host.h" @@ -780,10 +781,12 @@ void NativeWindowViews::OnWidgetActivationChanged( if (widget != window_.get()) return; - if (active) - NotifyWindowFocus(); - else - NotifyWindowBlur(); + // Post the notification to next tick. + content::BrowserThread::PostTask( + content::BrowserThread::UI, FROM_HERE, + base::Bind(active ? &NativeWindow::NotifyWindowFocus : + &NativeWindow::NotifyWindowBlur, + GetWeakPtr())); if (active && inspectable_web_contents() && !inspectable_web_contents()->IsDevToolsViewShowing()) From 3780d9f0333419e050fd92797c876fd87bfe712e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 16:38:39 +0900 Subject: [PATCH 0476/1265] Use LowMemoryNotification for GC --- atom/browser/atom_browser_main_parts.cc | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index 25338c0df17..335e0576fcb 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -136,9 +136,8 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() { // Start idle gc. gc_timer_.Start( FROM_HERE, base::TimeDelta::FromMinutes(1), - base::Bind(base::IgnoreResult(&v8::Isolate::IdleNotification), - base::Unretained(js_env_->isolate()), - 1000)); + base::Bind(&v8::Isolate::LowMemoryNotification, + base::Unretained(js_env_->isolate()))); brightray::BrowserMainParts::PreMainMessageLoopRun(); bridge_task_runner_->MessageLoopIsReady(); From 92882c358a0cdf091059a8cec98a00762f368c17 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 19:33:59 +0900 Subject: [PATCH 0477/1265] No more need to delay did-fail-load event --- atom/browser/api/atom_api_web_contents.cc | 19 ++++++------------- lib/browser/api/web-contents.js | 9 --------- 2 files changed, 6 insertions(+), 22 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 985c541a15a..81e2423a351 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -547,28 +547,21 @@ void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, void WebContents::DidFailProvisionalLoad( content::RenderFrameHost* render_frame_host, const GURL& url, - int error_code, - const base::string16& error_description, + int code, + const base::string16& description, bool was_ignored_by_handler) { bool is_main_frame = !render_frame_host->GetParent(); - Emit("did-fail-provisional-load", - error_code, - error_description, - url, - is_main_frame); + Emit("did-fail-provisional-load", code, description, url, is_main_frame); + Emit("did-fail-load", code, description, url, is_main_frame); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, + const GURL& url, int error_code, const base::string16& error_description, bool was_ignored_by_handler) { bool is_main_frame = !render_frame_host->GetParent(); - Emit("did-fail-load", - error_code, - error_description, - validated_url, - is_main_frame); + Emit("did-fail-load", error_code, error_description, url, is_main_frame); } void WebContents::DidStartLoading() { diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index bc32161e77e..40efa77cda0 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -146,15 +146,6 @@ let wrapWebContents = function (webContents) { return menu.popup(params.x, params.y) }) - // This error occurs when host could not be found. - webContents.on('did-fail-provisional-load', function (...args) { - // Calling loadURL during this event might cause crash, so delay the event - // until next tick. - setImmediate(() => { - this.emit.apply(this, ['did-fail-load'].concat(args)) - }) - }) - // The devtools requests the webContents to reload. webContents.on('devtools-reload-page', function () { webContents.reload() From 0a39449694cf874c92a04d0b634d2dfe0627ac48 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 19:39:11 +0900 Subject: [PATCH 0478/1265] spec: loadUrl should not crash in did-fail-provisional-load handler --- spec/api-browser-window-spec.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 5775a89e294..f1dd24345de 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -153,6 +153,14 @@ describe('browser-window module', function () { }) w.loadURL('file://' + path.join(fixtures, 'api', 'did-fail-load-iframe.html')) }) + + it('does not crash in did-fail-provisional-load handler', function (done) { + w.webContents.once('did-fail-provisional-load', function () { + w.loadURL('http://somewhere-that-does-not.exist/') + done() + }) + w.loadURL('http://somewhere-that-does-not.exist/') + }) }) describe('BrowserWindow.show()', function () { From 65c612a66dc3af0ada41756777e4cb2348d5a875 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 19:55:59 +0900 Subject: [PATCH 0479/1265] Avoid external URLs --- spec/api-browser-window-spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index f1dd24345de..2a8d1295c7f 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -156,10 +156,10 @@ describe('browser-window module', function () { it('does not crash in did-fail-provisional-load handler', function (done) { w.webContents.once('did-fail-provisional-load', function () { - w.loadURL('http://somewhere-that-does-not.exist/') + w.loadURL('http://localhost:11111') done() }) - w.loadURL('http://somewhere-that-does-not.exist/') + w.loadURL('http://localhost:11111') }) }) From c3ac92b500aceb382f4e175fe81a9696b7677dbc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 20:13:45 +0900 Subject: [PATCH 0480/1265] Update brightray for the linux notification improvements --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index cedb1131662..79ceba8890c 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit cedb11316627ac0e01a5dcd38e75bd1c5a6afa17 +Subproject commit 79ceba8890c42b6dcd71c43dccf2c6653d69dede From 07a4c5291980f6d0d22ee7600911562bd5cf4e3d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 21:36:43 +0900 Subject: [PATCH 0481/1265] Reduces the IPC messages used for visibilityState --- lib/browser/api/browser-window.js | 47 ++++++++++++------------------- lib/renderer/override.js | 39 ++++++++----------------- 2 files changed, 29 insertions(+), 57 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 694cbf6d669..80c1f29eb28 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -78,19 +78,23 @@ BrowserWindow.prototype._init = function () { app.emit('browser-window-focus', event, this) }) - // Evented visibilityState changes - this.on('show', () => { - this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) - }) - this.on('hide', () => { - this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) - }) - this.on('minimize', () => { - this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) - }) - this.on('restore', () => { - this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', this.isVisible(), this.isMinimized()) - }) + // Subscribe to visibilityState changes and pass to renderer process. + let isVisible = false + let visibilityChanged = () => { + let newState = this.isVisible() && !this.isMinimized() + if (isVisible != newState) { + isVisible = newState + this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', isVisible ? 'visible' : 'hidden') + } + } + this.on('show', visibilityChanged) + this.on('hide', visibilityChanged) + this.on('minimize', visibilityChanged) + this.on('restore', visibilityChanged) + this.on('maximize', visibilityChanged) + + // Make renderer process have correct initial state. + visibilityChanged() // Notify the creation of the window. app.emit('browser-window-created', {}, this) @@ -105,6 +109,7 @@ BrowserWindow.prototype._init = function () { this.webContents.on('devtools-closed', () => { this.emit('devtools-closed') }) + Object.defineProperty(this, 'devToolsWebContents', { enumerable: true, configurable: false, @@ -195,37 +200,21 @@ BrowserWindow.prototype.inspectServiceWorker = function () { } // Deprecated. - deprecate.member(BrowserWindow, 'undo', 'webContents') - deprecate.member(BrowserWindow, 'redo', 'webContents') - deprecate.member(BrowserWindow, 'cut', 'webContents') - deprecate.member(BrowserWindow, 'copy', 'webContents') - deprecate.member(BrowserWindow, 'paste', 'webContents') - deprecate.member(BrowserWindow, 'selectAll', 'webContents') - deprecate.member(BrowserWindow, 'reloadIgnoringCache', 'webContents') - deprecate.member(BrowserWindow, 'isLoading', 'webContents') - deprecate.member(BrowserWindow, 'isWaitingForResponse', 'webContents') - deprecate.member(BrowserWindow, 'stop', 'webContents') - deprecate.member(BrowserWindow, 'isCrashed', 'webContents') - deprecate.member(BrowserWindow, 'print', 'webContents') - deprecate.member(BrowserWindow, 'printToPDF', 'webContents') - deprecate.rename(BrowserWindow, 'restart', 'reload') - deprecate.rename(BrowserWindow, 'loadUrl', 'loadURL') - deprecate.rename(BrowserWindow, 'getUrl', 'getURL') BrowserWindow.prototype.executeJavaScriptInDevTools = deprecate('executeJavaScriptInDevTools', 'devToolsWebContents.executeJavaScript', function (code) { diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 5f808d66300..ba46bdf51e6 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -3,17 +3,6 @@ const ipcRenderer = require('electron').ipcRenderer const remote = require('electron').remote -// Cache browser window visibility -var _isVisible = true -var _isMinimized = false -var initWindow = function initWindow () { - var currentWindow - currentWindow = remote.getCurrentWindow() - _isVisible = currentWindow.isVisible() - _isMinimized = currentWindow.isMinimized() -} -initWindow() - // Helper function to resolve relative url. var a = window.top.document.createElement('a') @@ -200,17 +189,6 @@ if (process.openerId != null) { window.opener = BrowserWindowProxy.getOrCreate(process.openerId) } -ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { - var hasChanged = _isVisible !== isVisible || _isMinimized !== isMinimized - - if (hasChanged) { - _isVisible = isVisible - _isMinimized = isMinimized - - document.dispatchEvent(new Event('visibilitychange')) - } -}) - ipcRenderer.on('ELECTRON_GUEST_WINDOW_POSTMESSAGE', function (event, sourceId, message, sourceOrigin) { // Manually dispatch event instead of using postMessage because we also need to // set event.source. @@ -249,19 +227,24 @@ Object.defineProperty(window.history, 'length', { } }) +// Subscribe to visibilityState changes. +let cachedVisibilityState = 'hidden' +ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, visibilityState) { + if (cachedVisibilityState != visibilityState) { + cachedVisibilityState = visibilityState + document.dispatchEvent(new Event('visibilitychange')) + } +}) + // Make document.hidden and document.visibilityState return the correct value. Object.defineProperty(document, 'hidden', { get: function () { - return _isMinimized || !_isVisible + return cachedVisibilityState != 'visible' } }) Object.defineProperty(document, 'visibilityState', { get: function () { - if (_isVisible && !_isMinimized) { - return 'visible' - } else { - return 'hidden' - } + return cachedVisibilityState } }) From 43c44da50bb2e0bf38a0c6af632533e14baef525 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 22:56:11 +0900 Subject: [PATCH 0482/1265] Correctly set initial visibilityState --- atom/browser/api/atom_api_web_contents.cc | 7 +++++++ atom/browser/api/atom_api_web_contents.h | 1 + atom/browser/web_contents_preferences.cc | 17 +++++++++++------ atom/common/options_switches.cc | 4 ++++ atom/common/options_switches.h | 2 ++ lib/browser/api/browser-window.js | 5 +++-- lib/renderer/init.js | 8 +++----- lib/renderer/override.js | 10 ++++++---- 8 files changed, 37 insertions(+), 17 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 81e2423a351..55300819617 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1127,6 +1127,12 @@ bool WebContents::IsGuest() const { return type_ == WEB_VIEW; } +void WebContents::MergeWebPreferences(const base::DictionaryValue& extend) { + WebContentsPreferences* web_preferences = + WebContentsPreferences::FromWebContents(web_contents()); + web_preferences->Merge(extend); +} + v8::Local WebContents::GetWebPreferences(v8::Isolate* isolate) { WebContentsPreferences* web_preferences = WebContentsPreferences::FromWebContents(web_contents()); @@ -1221,6 +1227,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("setSize", &WebContents::SetSize) .SetMethod("isGuest", &WebContents::IsGuest) + .SetMethod("mergeWebPreferences", &WebContents::MergeWebPreferences) .SetMethod("getWebPreferences", &WebContents::GetWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker) diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 0cb2a348e17..91b860bff9a 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -144,6 +144,7 @@ class WebContents : public mate::TrackableObject, WindowOpenDisposition disposition); // Returns the web preferences of current WebContents. + void MergeWebPreferences(const base::DictionaryValue& extend); v8::Local GetWebPreferences(v8::Isolate* isolate); // Returns the owner window. diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index f36e7c076dc..14bbf3e719a 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -131,20 +131,25 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( // --guest-instance-id, which is used to identify guest WebContents. int guest_instance_id; if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id)) - command_line->AppendSwitchASCII(switches::kGuestInstanceID, - base::IntToString(guest_instance_id)); + command_line->AppendSwitchASCII(switches::kGuestInstanceID, + base::IntToString(guest_instance_id)); // Pass the opener's window id. int opener_id; if (web_preferences.GetInteger(options::kOpenerID, &opener_id)) - command_line->AppendSwitchASCII(switches::kOpenerID, - base::IntToString(opener_id)); + command_line->AppendSwitchASCII(switches::kOpenerID, + base::IntToString(opener_id)); // Enable blink features. std::string blink_features; if (web_preferences.GetString(options::kBlinkFeatures, &blink_features)) - command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures, - blink_features); + command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures, + blink_features); + + // The initial visibility state. + std::string visibility; + if (web_preferences.GetString(options::kVisibilityState, &visibility)) + command_line->AppendSwitchASCII(switches::kVisibilityState, visibility); } // static diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index ce28cc98fac..bd9657eb372 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -106,6 +106,9 @@ const char kOpenerID[] = "openerId"; // Enable blink features. const char kBlinkFeatures[] = "blinkFeatures"; +// The initiali visibility state. +const char kVisibilityState[] = "visibilityState"; + } // namespace options namespace switches { @@ -149,6 +152,7 @@ const char kPreloadURL[] = "preload-url"; const char kNodeIntegration[] = "node-integration"; const char kGuestInstanceID[] = "guest-instance-id"; const char kOpenerID[] = "opener-id"; +const char kVisibilityState[] = "visibility-state"; // Widevine options // Path to Widevine CDM binaries. diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 52d64c00d51..f7548c5388d 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -56,6 +56,7 @@ extern const char kGuestInstanceID[]; extern const char kExperimentalFeatures[]; extern const char kExperimentalCanvasFeatures[]; extern const char kOpenerID[]; +extern const char kVisibilityState[]; extern const char kBlinkFeatures[]; } // namespace options @@ -83,6 +84,7 @@ extern const char kPreloadURL[]; extern const char kNodeIntegration[]; extern const char kGuestInstanceID[]; extern const char kOpenerID[]; +extern const char kVisibilityState[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 80c1f29eb28..5e95aa2e01c 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -79,7 +79,7 @@ BrowserWindow.prototype._init = function () { }) // Subscribe to visibilityState changes and pass to renderer process. - let isVisible = false + let isVisible = this.isVisible() && !this.isMinimized() let visibilityChanged = () => { let newState = this.isVisible() && !this.isMinimized() if (isVisible != newState) { @@ -94,7 +94,8 @@ BrowserWindow.prototype._init = function () { this.on('maximize', visibilityChanged) // Make renderer process have correct initial state. - visibilityChanged() + if (!isVisible) + this.webContents.mergeWebPreferences({visibilityState: 'hidden'}) // Notify the creation of the window. app.emit('browser-window-created', {}, this) diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 02ac36c28e1..689307ed684 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -47,11 +47,7 @@ electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (ev // Process command line arguments. var nodeIntegration = 'false' var preloadScript = null - -var ref = process.argv -var i, len, arg -for (i = 0, len = ref.length; i < len; i++) { - arg = ref[i] +for (let arg of process.argv) { if (arg.indexOf('--guest-instance-id=') === 0) { // This is a guest web view. process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1)) @@ -62,6 +58,8 @@ for (i = 0, len = ref.length; i < len; i++) { nodeIntegration = arg.substr(arg.indexOf('=') + 1) } else if (arg.indexOf('--preload=') === 0) { preloadScript = arg.substr(arg.indexOf('=') + 1) + } else if (arg.indexOf('--visibility-state=') === 0) { + process.visibilityState = arg.substr(arg.indexOf('=') + 1) } } diff --git a/lib/renderer/override.js b/lib/renderer/override.js index ba46bdf51e6..4b86a74de78 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -5,7 +5,6 @@ const remote = require('electron').remote // Helper function to resolve relative url. var a = window.top.document.createElement('a') - var resolveURL = function (url) { a.href = url return a.href @@ -160,8 +159,6 @@ window.alert = function (message, title) { title: title, buttons: buttons }) - -// Alert should always return undefined. } // And the confirm(). @@ -227,8 +224,13 @@ Object.defineProperty(window.history, 'length', { } }) +// The initial visibilityState. +let cachedVisibilityState = 'visible' +if (process.visibilityState) { + cachedVisibilityState = process.visibilityState +} + // Subscribe to visibilityState changes. -let cachedVisibilityState = 'hidden' ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, visibilityState) { if (cachedVisibilityState != visibilityState) { cachedVisibilityState = visibilityState From 8f0e594007b805b0641eeb57a89ac50aa0de4653 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 13 Apr 2016 23:10:31 +0900 Subject: [PATCH 0483/1265] Fix lint warnings --- lib/browser/api/browser-window.js | 5 +++-- lib/renderer/override.js | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 5e95aa2e01c..0524c43942c 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -82,7 +82,7 @@ BrowserWindow.prototype._init = function () { let isVisible = this.isVisible() && !this.isMinimized() let visibilityChanged = () => { let newState = this.isVisible() && !this.isMinimized() - if (isVisible != newState) { + if (isVisible !== newState) { isVisible = newState this.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', isVisible ? 'visible' : 'hidden') } @@ -94,8 +94,9 @@ BrowserWindow.prototype._init = function () { this.on('maximize', visibilityChanged) // Make renderer process have correct initial state. - if (!isVisible) + if (!isVisible) { this.webContents.mergeWebPreferences({visibilityState: 'hidden'}) + } // Notify the creation of the window. app.emit('browser-window-created', {}, this) diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 4b86a74de78..1d01d2b5b75 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -232,7 +232,7 @@ if (process.visibilityState) { // Subscribe to visibilityState changes. ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, visibilityState) { - if (cachedVisibilityState != visibilityState) { + if (cachedVisibilityState !== visibilityState) { cachedVisibilityState = visibilityState document.dispatchEvent(new Event('visibilitychange')) } @@ -241,7 +241,7 @@ ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, vi // Make document.hidden and document.visibilityState return the correct value. Object.defineProperty(document, 'hidden', { get: function () { - return cachedVisibilityState != 'visible' + return cachedVisibilityState !== 'visible' } }) From 3c6e9332315c94b933c63271059224bf7cb571d9 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Wed, 13 Apr 2016 15:39:05 -0700 Subject: [PATCH 0484/1265] :memo: Add Debugging Instructions for Windows Ref #5140 --- docs/README.md | 1 + .../development/debug-instructions-windows.md | 38 +++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 docs/development/debug-instructions-windows.md diff --git a/docs/README.md b/docs/README.md index 19ec51343d4..428d2f8bd7b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -89,4 +89,5 @@ an issue: * [Build Instructions (OS X)](development/build-instructions-osx.md) * [Build Instructions (Windows)](development/build-instructions-windows.md) * [Build Instructions (Linux)](development/build-instructions-linux.md) +* [Debug Instructions (Windows)](development/debug-instructions-windows.md) * [Setting Up Symbol Server in debugger](development/setting-up-symbol-server.md) diff --git a/docs/development/debug-instructions-windows.md b/docs/development/debug-instructions-windows.md new file mode 100644 index 00000000000..3070bf33443 --- /dev/null +++ b/docs/development/debug-instructions-windows.md @@ -0,0 +1,38 @@ +# Debugging Electron in Windows +If you experience crashes or issues in Electron that you believe are not caused by your JavaScript application, but instead by Electron itself, debugging can be a little bit tricky, especially for developers not used to native/C++ debugging. However, using Visual Studio, GitHub's hosted Electron Symbol Server, and the Electron source code, it is fairly easy to enable step-through debugging with breakpoints inside Electron's source code. + +### Requirements + * **A debug build of Electron**: The easiest way is usually building it yourself, using the tools and prerequisites listed in the [build instructions for Windows](build-instructions-osx.md). While you can easily attach to and debug Electron as you can download it directly, you will find that it is heavily optimized, making debugging substantially more difficult: The debugger will not be able to show you the content of all variables and the execution path can seem strange because of inlining, tail calls, and other compiler optimizations. + + * **Visual Studio with C++ Tools**: The free community editions of [Visual Studio 2013]() and [Visual Studio 2015]() both work. + + Once installed, [configure Visual Studio to use GitHub's Electron Symbol server](setting-up-symbol-server.md). It will enable Visual Studio to gain a better understanding of what happens inside Electron, making it easier to present variables in a human-readable format. + + * **ProcMon**: The [free SysInternals tool](https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx) allows you to inspect a processes parameters, file handles, and registry operations. + +# Attaching to and Debugging Electron +To start a debugging session, open up PowerShell/CMD and execute your debug build of Electron, using the application to open as a parameter. + +``` +./out/D/electron.exe ~/my-electron-app/ +``` + +## Setting Breakpoints +Then, open up Visual Studio. Electron is not built with Visual Studio and hence does not contain a project file - you can however open up the source code files "As File", meaning that Visual Studio will open them up by themselves. You can still set breakpoints - Visual Studio will automatically figure out that the source code matches the code running in the attached process and break accordingly. + +Relevant code files can be found in `./atom/` as well as in Brightray, found in `./vendor/brightray/browser` and `./vendor/brightray/common`. If you're hardcore, you can also debug Chromium directly, which is obviously found in `chromium_src`. + +## Attaching +You can attach the Visual Studio debugger to a running process on a local or remote computer. After the process is running, click Debug / Attach to Process (or press `CTRL+ALT+P`) to open the "Attach to Process" dialog box. You can use this capability to debug apps that are running on a local or remote computer, debug multiple processes simultaneously. + +If Electron is running under a different user account, select the `Show processes from all users` check box. Notice that depending on how many BrowserWindows your app opened, you will see multiple processes. A typical one-window app will result in Visual Studio presenting you with two `Electron.exe` entries - one for the main process and one for the renderer process. Since the list only gives you names, there's currently no reliable way of figuring out which is which. + +#### Which Process Should I Attach to? +Code executed within the main process (that is, code found in or eventually run by your main JavaScript file) as well as code called using the remote (`require('electron').remote`) will run inside the main process, while other code will execute inside its respective renderer process. + +You can be attached to multiple programs when you are debugging, but only one program is active in the debugger at any time. You can set the active program in the `Debug Location` toolbar or the `Processes window`. + +## Using ProcMon to Observe a Process +While Visual Studio is fantastic for inspecting specific code paths, ProcMon's strength is really in observing everything your application is doing with the operating system - it captures File, Registry, Network, Process, and Profiling details of processes. It attempts to log *all* events occurring and can be quite overwhelming, but if you seek to understand what and how your application is doing to the operating system, it can be a valuable resource. + +For an introduction to ProcMon's basic and advanced debugging features, go check out [this video tutorial](https://channel9.msdn.com/shows/defrag-tools/defrag-tools-4-process-monitor) provided by Microsoft. \ No newline at end of file From 31eb793fb00114e06efac10d38fd0798e65bde1b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 10:50:07 +0900 Subject: [PATCH 0485/1265] Avoid adding a new option to webPreferences --- atom/browser/api/atom_api_web_contents.cc | 7 ------- atom/browser/api/atom_api_web_contents.h | 1 - atom/browser/web_contents_preferences.cc | 10 +++++++--- atom/common/options_switches.cc | 4 ---- atom/common/options_switches.h | 2 -- lib/browser/api/browser-window.js | 5 ----- lib/renderer/init.js | 2 -- lib/renderer/override.js | 5 +---- 8 files changed, 8 insertions(+), 28 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 55300819617..81e2423a351 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1127,12 +1127,6 @@ bool WebContents::IsGuest() const { return type_ == WEB_VIEW; } -void WebContents::MergeWebPreferences(const base::DictionaryValue& extend) { - WebContentsPreferences* web_preferences = - WebContentsPreferences::FromWebContents(web_contents()); - web_preferences->Merge(extend); -} - v8::Local WebContents::GetWebPreferences(v8::Isolate* isolate) { WebContentsPreferences* web_preferences = WebContentsPreferences::FromWebContents(web_contents()); @@ -1227,7 +1221,6 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("setSize", &WebContents::SetSize) .SetMethod("isGuest", &WebContents::IsGuest) - .SetMethod("mergeWebPreferences", &WebContents::MergeWebPreferences) .SetMethod("getWebPreferences", &WebContents::GetWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker) diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 91b860bff9a..0cb2a348e17 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -144,7 +144,6 @@ class WebContents : public mate::TrackableObject, WindowOpenDisposition disposition); // Returns the web preferences of current WebContents. - void MergeWebPreferences(const base::DictionaryValue& extend); v8::Local GetWebPreferences(v8::Isolate* isolate); // Returns the owner window. diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 14bbf3e719a..05286a2d3ba 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -8,6 +8,7 @@ #include #include +#include "atom/browser/native_window.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/options_switches.h" #include "base/command_line.h" @@ -147,9 +148,12 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( blink_features); // The initial visibility state. - std::string visibility; - if (web_preferences.GetString(options::kVisibilityState, &visibility)) - command_line->AppendSwitchASCII(switches::kVisibilityState, visibility); + NativeWindow* window = NativeWindow::FromWebContents(web_contents); + if (window) { + bool visible = window->IsVisible() && !window->IsMinimized(); + if (!visible) // Default state is visible. + command_line->AppendSwitch("hidden-page"); + } } // static diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index bd9657eb372..ce28cc98fac 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -106,9 +106,6 @@ const char kOpenerID[] = "openerId"; // Enable blink features. const char kBlinkFeatures[] = "blinkFeatures"; -// The initiali visibility state. -const char kVisibilityState[] = "visibilityState"; - } // namespace options namespace switches { @@ -152,7 +149,6 @@ const char kPreloadURL[] = "preload-url"; const char kNodeIntegration[] = "node-integration"; const char kGuestInstanceID[] = "guest-instance-id"; const char kOpenerID[] = "opener-id"; -const char kVisibilityState[] = "visibility-state"; // Widevine options // Path to Widevine CDM binaries. diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index f7548c5388d..52d64c00d51 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -56,7 +56,6 @@ extern const char kGuestInstanceID[]; extern const char kExperimentalFeatures[]; extern const char kExperimentalCanvasFeatures[]; extern const char kOpenerID[]; -extern const char kVisibilityState[]; extern const char kBlinkFeatures[]; } // namespace options @@ -84,7 +83,6 @@ extern const char kPreloadURL[]; extern const char kNodeIntegration[]; extern const char kGuestInstanceID[]; extern const char kOpenerID[]; -extern const char kVisibilityState[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js index 0524c43942c..c9d63278f97 100644 --- a/lib/browser/api/browser-window.js +++ b/lib/browser/api/browser-window.js @@ -93,11 +93,6 @@ BrowserWindow.prototype._init = function () { this.on('restore', visibilityChanged) this.on('maximize', visibilityChanged) - // Make renderer process have correct initial state. - if (!isVisible) { - this.webContents.mergeWebPreferences({visibilityState: 'hidden'}) - } - // Notify the creation of the window. app.emit('browser-window-created', {}, this) diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 689307ed684..a9f4acc5cbf 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -58,8 +58,6 @@ for (let arg of process.argv) { nodeIntegration = arg.substr(arg.indexOf('=') + 1) } else if (arg.indexOf('--preload=') === 0) { preloadScript = arg.substr(arg.indexOf('=') + 1) - } else if (arg.indexOf('--visibility-state=') === 0) { - process.visibilityState = arg.substr(arg.indexOf('=') + 1) } } diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 1d01d2b5b75..db56eadd348 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -225,10 +225,7 @@ Object.defineProperty(window.history, 'length', { }) // The initial visibilityState. -let cachedVisibilityState = 'visible' -if (process.visibilityState) { - cachedVisibilityState = process.visibilityState -} +let cachedVisibilityState = process.argv.includes('--hidden-page') ? 'hidden' : 'visible' // Subscribe to visibilityState changes. ipcRenderer.on('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, visibilityState) { From cb2343c69eb36ef3ada3d5b4434d8d6642554747 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Thu, 14 Apr 2016 10:08:01 +0800 Subject: [PATCH 0486/1265] Update process.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit translation error, change "实效" to “失效". --- docs-translations/zh-CN/api/process.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/zh-CN/api/process.md b/docs-translations/zh-CN/api/process.md index d07741247aa..7e8173dfb3b 100644 --- a/docs-translations/zh-CN/api/process.md +++ b/docs-translations/zh-CN/api/process.md @@ -31,7 +31,7 @@ process.once('loaded', function() { ### `process.noAsar` -设置它为 `true` 可以使 `asar` 文件在node的内置模块中实效. +设置它为 `true` 可以使 `asar` 文件在node的内置模块中失效. ## 方法 @@ -45,4 +45,4 @@ process.once('loaded', function() { * `maxDescriptors` Integer -设置文件描述符软限制于 `maxDescriptors` 或硬限制与os, 无论它是否低于当前进程. \ No newline at end of file +设置文件描述符软限制于 `maxDescriptors` 或硬限制与os, 无论它是否低于当前进程. From b9ad09db9189c5b0f2c450fb1c0c94e312930541 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 17:14:45 +0900 Subject: [PATCH 0487/1265] Update libchromiumcontent with necessary headers and libs --- script/lib/config.py | 2 +- vendor/brightray | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/script/lib/config.py b/script/lib/config.py index 6cd31452caa..e01715ccffc 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '4e506867ad95907e0a9cbec4ab3ee0f84214de94' +LIBCHROMIUMCONTENT_COMMIT = '2da28b049031082ab9f76ac7f331276a5fa6ab46' PLATFORM = { 'cygwin': 'win32', diff --git a/vendor/brightray b/vendor/brightray index 79ceba8890c..528b38e866a 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 79ceba8890c42b6dcd71c43dccf2c6653d69dede +Subproject commit 528b38e866a3408d9c7a937b3e1818928185d224 From ae0d007c5e4060af55724bae36a704bd5a14ca35 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 17:15:20 +0900 Subject: [PATCH 0488/1265] Do no load PDF library from DLL We already have them compiled in. --- atom/app/atom_main_delegate.cc | 4 - atom/utility/atom_content_utility_client.cc | 9 +- atom/utility/atom_content_utility_client.h | 2 - .../chrome/utility/printing_handler_win.cc | 120 ++---------------- .../chrome/utility/printing_handler_win.h | 10 +- 5 files changed, 16 insertions(+), 129 deletions(-) diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index 221d59c1619..0a298308ad0 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -98,10 +98,6 @@ void AtomMainDelegate::PreSandboxStartup() { std::string process_type = command_line->GetSwitchValueASCII( switches::kProcessType); - if (process_type == switches::kUtilityProcess) { - AtomContentUtilityClient::PreSandboxStartup(); - } - // Only append arguments for browser process. if (!IsBrowserProcess(command_line)) return; diff --git a/atom/utility/atom_content_utility_client.cc b/atom/utility/atom_content_utility_client.cc index 2e591f2c6a8..aff567fbcaa 100644 --- a/atom/utility/atom_content_utility_client.cc +++ b/atom/utility/atom_content_utility_client.cc @@ -37,7 +37,7 @@ int64_t AtomContentUtilityClient::max_ipc_message_size_ = AtomContentUtilityClient::AtomContentUtilityClient() : filter_messages_(false) { #if defined(OS_WIN) - handlers_.push_back(new PrintingHandlerWin()); + handlers_.push_back(new printing::PrintingHandlerWin()); #endif } @@ -71,11 +71,4 @@ void AtomContentUtilityClient::OnStartupPing() { // Don't release the process, we assume further messages are on the way. } -// static -void AtomContentUtilityClient::PreSandboxStartup() { -#if defined(OS_WIN) - PrintingHandlerWin::PreSandboxStartup(); -#endif -} - } // namespace atom diff --git a/atom/utility/atom_content_utility_client.h b/atom/utility/atom_content_utility_client.h index 229ae3f9176..ba0fef471a1 100644 --- a/atom/utility/atom_content_utility_client.h +++ b/atom/utility/atom_content_utility_client.h @@ -31,8 +31,6 @@ class AtomContentUtilityClient : public content::ContentUtilityClient { void UtilityThreadStarted() override; bool OnMessageReceived(const IPC::Message& message) override; - static void PreSandboxStartup(); - static void set_max_ipc_message_size_for_test(int64_t max_message_size) { max_ipc_message_size_ = max_message_size; } diff --git a/chromium_src/chrome/utility/printing_handler_win.cc b/chromium_src/chrome/utility/printing_handler_win.cc index 805cd6e343c..b0bbac52367 100644 --- a/chromium_src/chrome/utility/printing_handler_win.cc +++ b/chromium_src/chrome/utility/printing_handler_win.cc @@ -10,11 +10,14 @@ #include "base/scoped_native_library.h" #include "chrome/common/print_messages.h" #include "content/public/utility/utility_thread.h" +#include "pdf/pdf.h" #include "printing/emf_win.h" #include "printing/page_range.h" #include "printing/pdf_render_settings.h" #include "ui/gfx/gdi_util.h" +namespace printing { + namespace { bool Send(IPC::Message* message) { @@ -25,114 +28,12 @@ void ReleaseProcessIfNeeded() { content::UtilityThread::Get()->ReleaseProcessIfNeeded(); } -class PdfFunctions { - public: - PdfFunctions() : get_pdf_doc_info_func_(NULL), - render_pdf_to_dc_func_(NULL) {} - - bool Init() { - base::FilePath module_path; - if (!PathService::Get(base::DIR_MODULE, &module_path)) - return false; - base::FilePath::StringType name(FILE_PATH_LITERAL("pdf.dll")); - pdf_lib_.Reset(base::LoadNativeLibrary(module_path.Append(name), NULL)); - if (!pdf_lib_.is_valid()) { - LOG(WARNING) << "Couldn't load PDF plugin"; - return false; - } - - get_pdf_doc_info_func_ = - reinterpret_cast( - pdf_lib_.GetFunctionPointer("GetPDFDocInfo")); - LOG_IF(WARNING, !get_pdf_doc_info_func_) << "Missing GetPDFDocInfo"; - - render_pdf_to_dc_func_ = - reinterpret_cast( - pdf_lib_.GetFunctionPointer("RenderPDFPageToDC")); - LOG_IF(WARNING, !render_pdf_to_dc_func_) << "Missing RenderPDFPageToDC"; - - if (!get_pdf_doc_info_func_ || !render_pdf_to_dc_func_) { - Reset(); - } - - return IsValid(); - } - - bool IsValid() const { - return pdf_lib_.is_valid(); - } - - void Reset() { - pdf_lib_.Reset(NULL); - } - - bool GetPDFDocInfo(const void* pdf_buffer, - int buffer_size, - int* page_count, - double* max_page_width) { - if (!get_pdf_doc_info_func_) - return false; - return get_pdf_doc_info_func_(pdf_buffer, buffer_size, page_count, - max_page_width); - } - - bool RenderPDFPageToDC(const void* pdf_buffer, - int buffer_size, - int page_number, - HDC dc, - int dpi, - int bounds_origin_x, - int bounds_origin_y, - int bounds_width, - int bounds_height, - bool fit_to_bounds, - bool stretch_to_bounds, - bool keep_aspect_ratio, - bool center_in_bounds, - bool autorotate) { - if (!render_pdf_to_dc_func_) - return false; - return render_pdf_to_dc_func_(pdf_buffer, buffer_size, page_number, - dc, dpi, bounds_origin_x, - bounds_origin_y, bounds_width, bounds_height, - fit_to_bounds, stretch_to_bounds, - keep_aspect_ratio, center_in_bounds, - autorotate); - } - - private: - // Exported by PDF plugin. - typedef bool (*GetPDFDocInfoProc)(const void* pdf_buffer, - int buffer_size, int* page_count, - double* max_page_width); - typedef bool (*RenderPDFPageToDCProc)( - const void* pdf_buffer, int buffer_size, int page_number, HDC dc, - int dpi, int bounds_origin_x, int bounds_origin_y, - int bounds_width, int bounds_height, bool fit_to_bounds, - bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds, - bool autorotate); - - RenderPDFPageToDCProc render_pdf_to_dc_func_; - GetPDFDocInfoProc get_pdf_doc_info_func_; - - base::ScopedNativeLibrary pdf_lib_; - - DISALLOW_COPY_AND_ASSIGN(PdfFunctions); -}; - -base::LazyInstance g_pdf_lib = LAZY_INSTANCE_INITIALIZER; - } // namespace PrintingHandlerWin::PrintingHandlerWin() {} PrintingHandlerWin::~PrintingHandlerWin() {} -// static -void PrintingHandlerWin::PreSandboxStartup() { - g_pdf_lib.Get().Init(); -} - bool PrintingHandlerWin::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintingHandlerWin, message) @@ -149,7 +50,7 @@ bool PrintingHandlerWin::OnMessageReceived(const IPC::Message& message) { void PrintingHandlerWin::OnRenderPDFPagesToMetafile( IPC::PlatformFileForTransit pdf_transit, - const printing::PdfRenderSettings& settings) { + const PdfRenderSettings& settings) { pdf_rendering_settings_ = settings; base::File pdf_file = IPC::PlatformFileForTransitToFile(pdf_transit); int page_count = LoadPDF(pdf_file.Pass()); @@ -174,9 +75,6 @@ void PrintingHandlerWin::OnRenderPDFPagesToMetafileStop() { } int PrintingHandlerWin::LoadPDF(base::File pdf_file) { - if (!g_pdf_lib.Get().IsValid()) - return 0; - int64_t length64 = pdf_file.GetLength(); if (length64 <= 0 || length64 > std::numeric_limits::max()) return 0; @@ -187,8 +85,8 @@ int PrintingHandlerWin::LoadPDF(base::File pdf_file) { return 0; int total_page_count = 0; - if (!g_pdf_lib.Get().GetPDFDocInfo( - &pdf_data_.front(), pdf_data_.size(), &total_page_count, NULL)) { + if (!chrome_pdf::GetPDFDocInfo(&pdf_data_.front(), pdf_data_.size(), + &total_page_count, nullptr)) { return 0; } return total_page_count; @@ -197,7 +95,7 @@ int PrintingHandlerWin::LoadPDF(base::File pdf_file) { bool PrintingHandlerWin::RenderPdfPageToMetafile(int page_number, base::File output_file, float* scale_factor) { - printing::Emf metafile; + Emf metafile; metafile.Init(); // We need to scale down DC to fit an entire page into DC available area. @@ -216,7 +114,7 @@ bool PrintingHandlerWin::RenderPdfPageToMetafile(int page_number, // The underlying metafile is of type Emf and ignores the arguments passed // to StartPage. metafile.StartPage(gfx::Size(), gfx::Rect(), 1); - if (!g_pdf_lib.Get().RenderPDFPageToDC( + if (!chrome_pdf::RenderPDFPageToDC( &pdf_data_.front(), pdf_data_.size(), page_number, @@ -237,3 +135,5 @@ bool PrintingHandlerWin::RenderPdfPageToMetafile(int page_number, metafile.FinishDocument(); return metafile.SaveTo(&output_file); } + +} // printing diff --git a/chromium_src/chrome/utility/printing_handler_win.h b/chromium_src/chrome/utility/printing_handler_win.h index 5b8c5e970f1..e7fcc5bed15 100644 --- a/chromium_src/chrome/utility/printing_handler_win.h +++ b/chromium_src/chrome/utility/printing_handler_win.h @@ -12,10 +12,10 @@ #include "printing/pdf_render_settings.h" namespace printing { + class PdfRenderSettings; struct PwgRasterSettings; struct PageRange; -} // Dispatches IPCs for printing. class PrintingHandlerWin : public UtilityMessageHandler { @@ -26,12 +26,10 @@ class PrintingHandlerWin : public UtilityMessageHandler { // IPC::Listener: bool OnMessageReceived(const IPC::Message& message) override; - static void PrintingHandlerWin::PreSandboxStartup(); - private: // IPC message handlers. void OnRenderPDFPagesToMetafile(IPC::PlatformFileForTransit pdf_transit, - const printing::PdfRenderSettings& settings); + const PdfRenderSettings& settings); void OnRenderPDFPagesToMetafileGetPage( int page_number, IPC::PlatformFileForTransit output_file); @@ -43,9 +41,11 @@ class PrintingHandlerWin : public UtilityMessageHandler { float* scale_factor); std::vector pdf_data_; - printing::PdfRenderSettings pdf_rendering_settings_; + PdfRenderSettings pdf_rendering_settings_; DISALLOW_COPY_AND_ASSIGN(PrintingHandlerWin); }; +} // namespace printing + #endif // CHROME_UTILITY_PRINTING_HANDLER_WIN_H_ From 7d4e0629d67f831bdeb834486d327842e0418675 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 18:22:29 +0900 Subject: [PATCH 0489/1265] Fix the link error --- script/lib/config.py | 2 +- vendor/brightray | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/script/lib/config.py b/script/lib/config.py index e01715ccffc..4b3f4ba6fb3 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '2da28b049031082ab9f76ac7f331276a5fa6ab46' +LIBCHROMIUMCONTENT_COMMIT = '1a4c5e51a670633ff3ecd4448ad01ba21b440542' PLATFORM = { 'cygwin': 'win32', diff --git a/vendor/brightray b/vendor/brightray index 528b38e866a..7b037805e0d 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 528b38e866a3408d9c7a937b3e1818928185d224 +Subproject commit 7b037805e0dbb5976bdca5808f0ef4c937db1f6e From 11ba1832d1c80eccf2935f2afa73f9dc9439d43c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 19:35:31 +0900 Subject: [PATCH 0490/1265] Only transparent window does not have background color --- atom/browser/native_window.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 9762351de22..d7ed86165b9 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -162,8 +162,8 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) { std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(color); - } else if (has_frame()) { - // For window with frame, use white as default background. + } else if (!transparent()) { + // For normal window, use white as default background. SetBackgroundColor("#FFFF"); } std::string title("Electron"); From 54545a8a6e2fd0d38ea68ef4271810d1f037adaf Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 11 Apr 2016 15:06:33 +0530 Subject: [PATCH 0491/1265] provide security style for devtools security panel --- atom/browser/api/atom_api_web_contents.cc | 3 + .../atom_security_state_model_client.cc | 105 +++++++++++++++++ .../atom_security_state_model_client.h | 42 +++++++ atom/browser/common_web_contents_delegate.cc | 107 ++++++++++++++++++ atom/browser/common_web_contents_delegate.h | 3 + atom/common/atom_constants.cc | 18 ++- atom/common/atom_constants.h | 12 +- filenames.gypi | 2 + 8 files changed, 290 insertions(+), 2 deletions(-) create mode 100644 atom/browser/atom_security_state_model_client.cc create mode 100644 atom/browser/atom_security_state_model_client.h diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 81e2423a351..02f3023bd17 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -13,6 +13,7 @@ #include "atom/browser/atom_browser_client.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" +#include "atom/browser/atom_security_state_model_client.h" #include "atom/browser/native_window.h" #include "atom/browser/net/atom_network_delegate.h" #include "atom/browser/web_contents_permission_helper.h" @@ -277,6 +278,8 @@ WebContents::WebContents(v8::Isolate* isolate, // Intialize permission helper. WebContentsPermissionHelper::CreateForWebContents(web_contents); + // Intialize security state client. + AtomSecurityStateModelClient::CreateForWebContents(web_contents); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); diff --git a/atom/browser/atom_security_state_model_client.cc b/atom/browser/atom_security_state_model_client.cc new file mode 100644 index 00000000000..911849c5c2d --- /dev/null +++ b/atom/browser/atom_security_state_model_client.cc @@ -0,0 +1,105 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/atom_security_state_model_client.h" + +#include "content/public/browser/cert_store.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/origin_util.h" +#include "content/public/common/ssl_status.h" +#include "net/cert/x509_certificate.h" + +DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::AtomSecurityStateModelClient); + +using security_state::SecurityStateModel; + +namespace atom { + +namespace { + +SecurityStateModel::SecurityLevel GetSecurityLevelForSecurityStyle( + content::SecurityStyle style) { + switch (style) { + case content::SECURITY_STYLE_UNKNOWN: + return SecurityStateModel::NONE; + case content::SECURITY_STYLE_UNAUTHENTICATED: + return SecurityStateModel::NONE; + case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: + return SecurityStateModel::SECURITY_ERROR; + case content::SECURITY_STYLE_WARNING: + return SecurityStateModel::SECURITY_WARNING; + case content::SECURITY_STYLE_AUTHENTICATED: + return SecurityStateModel::SECURE; + } + return SecurityStateModel::NONE; +} + +} // namespace + +AtomSecurityStateModelClient::AtomSecurityStateModelClient( + content::WebContents* web_contents) + : web_contents_(web_contents), + security_state_model_(new SecurityStateModel()) { + security_state_model_->SetClient(this); +} + +AtomSecurityStateModelClient::~AtomSecurityStateModelClient() { +} + +const SecurityStateModel::SecurityInfo& +AtomSecurityStateModelClient::GetSecurityInfo() const { + return security_state_model_->GetSecurityInfo(); +} + +bool AtomSecurityStateModelClient::RetrieveCert( + scoped_refptr* cert) { + content::NavigationEntry* entry = + web_contents_->GetController().GetVisibleEntry(); + if (!entry) + return false; + return content::CertStore::GetInstance()->RetrieveCert( + entry->GetSSL().cert_id, cert); +} + +bool AtomSecurityStateModelClient::UsedPolicyInstalledCertificate() { + return false; +} + +bool AtomSecurityStateModelClient::IsOriginSecure(const GURL& url) { + return content::IsOriginSecure(url); +} + +void AtomSecurityStateModelClient::GetVisibleSecurityState( + SecurityStateModel::VisibleSecurityState* state) { + content::NavigationEntry* entry = + web_contents_->GetController().GetVisibleEntry(); + if (!entry || + entry->GetSSL().security_style == content::SECURITY_STYLE_UNKNOWN) { + *state = SecurityStateModel::VisibleSecurityState(); + return; + } + + state->initialized = true; + state->url = entry->GetURL(); + const content::SSLStatus& ssl = entry->GetSSL(); + state->initial_security_level = + GetSecurityLevelForSecurityStyle(ssl.security_style); + state->cert_id = ssl.cert_id; + state->cert_status = ssl.cert_status; + state->connection_status = ssl.connection_status; + state->security_bits = ssl.security_bits; + state->sct_verify_statuses.clear(); + for (const auto& sct : ssl.signed_certificate_timestamp_ids) + state->sct_verify_statuses.push_back(sct.status); + state->displayed_mixed_content = + (ssl.content_status & content::SSLStatus::DISPLAYED_INSECURE_CONTENT) + ? true + : false; + state->ran_mixed_content = + (ssl.content_status & content::SSLStatus::RAN_INSECURE_CONTENT) ? true + : false; +} + +} // namespace atom diff --git a/atom/browser/atom_security_state_model_client.h b/atom/browser/atom_security_state_model_client.h new file mode 100644 index 00000000000..cc943eb7f94 --- /dev/null +++ b/atom/browser/atom_security_state_model_client.h @@ -0,0 +1,42 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_BROWSER_ATOM_SECURITY_STATE_MODEL_CLIENT_H_ +#define ATOM_BROWSER_ATOM_SECURITY_STATE_MODEL_CLIENT_H_ + +#include "components/security_state/security_state_model.h" +#include "components/security_state/security_state_model_client.h" +#include "content/public/browser/web_contents_user_data.h" + +namespace atom { + +class AtomSecurityStateModelClient + : public security_state::SecurityStateModelClient, + public content::WebContentsUserData { + public: + ~AtomSecurityStateModelClient() override; + + const security_state::SecurityStateModel::SecurityInfo& + GetSecurityInfo() const; + + // security_state::SecurityStateModelClient: + void GetVisibleSecurityState( + security_state::SecurityStateModel::VisibleSecurityState* state) override; + bool RetrieveCert(scoped_refptr* cert) override; + bool UsedPolicyInstalledCertificate() override; + bool IsOriginSecure(const GURL& url) override; + + private: + explicit AtomSecurityStateModelClient(content::WebContents* web_contents); + friend class content::WebContentsUserData; + + content::WebContents* web_contents_; + scoped_ptr security_state_model_; + + DISALLOW_COPY_AND_ASSIGN(AtomSecurityStateModelClient); +}; + +} // namespace atom + +#endif // ATOM_BROWSER_ATOM_SECURITY_STATE_MODEL_CLIENT_H_ diff --git a/atom/browser/common_web_contents_delegate.cc b/atom/browser/common_web_contents_delegate.cc index 62e854ac565..4bebf7480b8 100644 --- a/atom/browser/common_web_contents_delegate.cc +++ b/atom/browser/common_web_contents_delegate.cc @@ -10,9 +10,11 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_javascript_dialog_manager.h" +#include "atom/browser/atom_security_state_model_client.h" #include "atom/browser/native_window.h" #include "atom/browser/ui/file_dialog.h" #include "atom/browser/web_dialog_helper.h" +#include "atom/common/atom_constants.h" #include "base/files/file_util.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" @@ -25,6 +27,8 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" +#include "content/public/browser/security_style_explanation.h" +#include "content/public/browser/security_style_explanations.h" #include "storage/browser/fileapi/isolated_context.h" #if defined(TOOLKIT_VIEWS) @@ -36,6 +40,7 @@ #endif using content::BrowserThread; +using security_state::SecurityStateModel; namespace atom { @@ -140,6 +145,24 @@ std::set GetAddedFileSystemPaths( return result; } +content::SecurityStyle SecurityLevelToSecurityStyle( + SecurityStateModel::SecurityLevel security_level) { + switch (security_level) { + case SecurityStateModel::NONE: + return content::SECURITY_STYLE_UNAUTHENTICATED; + case SecurityStateModel::SECURITY_WARNING: + case SecurityStateModel::SECURITY_POLICY_WARNING: + return content::SECURITY_STYLE_WARNING; + case SecurityStateModel::EV_SECURE: + case SecurityStateModel::SECURE: + return content::SECURITY_STYLE_AUTHENTICATED; + case SecurityStateModel::SECURITY_ERROR: + return content::SECURITY_STYLE_AUTHENTICATION_BROKEN; + } + + return content::SECURITY_STYLE_UNKNOWN; +} + } // namespace CommonWebContentsDelegate::CommonWebContentsDelegate() @@ -265,6 +288,90 @@ bool CommonWebContentsDelegate::IsFullscreenForTabOrPending( return html_fullscreen_; } +content::SecurityStyle CommonWebContentsDelegate::GetSecurityStyle( + content::WebContents* web_contents, + content::SecurityStyleExplanations* explanations) { + auto model_client = + AtomSecurityStateModelClient::FromWebContents(web_contents); + + const SecurityStateModel::SecurityInfo& security_info = + model_client->GetSecurityInfo(); + + const content::SecurityStyle security_style = + SecurityLevelToSecurityStyle(security_info.security_level); + + explanations->ran_insecure_content_style = + SecurityLevelToSecurityStyle( + SecurityStateModel::kRanInsecureContentLevel); + explanations->displayed_insecure_content_style = + SecurityLevelToSecurityStyle( + SecurityStateModel::kDisplayedInsecureContentLevel); + + explanations->scheme_is_cryptographic = security_info.scheme_is_cryptographic; + if (!security_info.scheme_is_cryptographic) + return security_style; + + if (security_info.sha1_deprecation_status == + SecurityStateModel::DEPRECATED_SHA1_MAJOR) { + explanations->broken_explanations.push_back( + content::SecurityStyleExplanation( + kSHA1Certificate, + kSHA1MajorDescription, + security_info.cert_id)); + } else if (security_info.sha1_deprecation_status == + SecurityStateModel::DEPRECATED_SHA1_MINOR) { + explanations->unauthenticated_explanations.push_back( + content::SecurityStyleExplanation( + kSHA1Certificate, + kSHA1MinorDescription, + security_info.cert_id)); + } + + explanations->ran_insecure_content = + security_info.mixed_content_status == + SecurityStateModel::RAN_MIXED_CONTENT || + security_info.mixed_content_status == + SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT; + explanations->displayed_insecure_content = + security_info.mixed_content_status == + SecurityStateModel::DISPLAYED_MIXED_CONTENT || + security_info.mixed_content_status == + SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT; + + if (net::IsCertStatusError(security_info.cert_status)) { + std::string error_string = net::ErrorToString( + net::MapCertStatusToNetError(security_info.cert_status)); + + content::SecurityStyleExplanation explanation( + kCertificateError, + "There are issues with the site's certificate chain " + error_string, + security_info.cert_id); + + if (net::IsCertStatusMinorError(security_info.cert_status)) + explanations->unauthenticated_explanations.push_back(explanation); + else + explanations->broken_explanations.push_back(explanation); + } else { + if (security_info.sha1_deprecation_status == + SecurityStateModel::NO_DEPRECATED_SHA1) { + explanations->secure_explanations.push_back( + content::SecurityStyleExplanation( + kValidCertificate, + kValidCertificateDescription, + security_info.cert_id)); + } + } + + if (security_info.is_secure_protocol_and_ciphersuite) { + explanations->secure_explanations.push_back( + content::SecurityStyleExplanation( + kSecureProtocol, + kSecureProtocolDescription)); + } + + return security_style; +} + void CommonWebContentsDelegate::DevToolsSaveToFile( const std::string& url, const std::string& content, bool save_as) { base::FilePath path; diff --git a/atom/browser/common_web_contents_delegate.h b/atom/browser/common_web_contents_delegate.h index 61ff63793df..699d00e18bc 100644 --- a/atom/browser/common_web_contents_delegate.h +++ b/atom/browser/common_web_contents_delegate.h @@ -76,6 +76,9 @@ class CommonWebContentsDelegate void ExitFullscreenModeForTab(content::WebContents* source) override; bool IsFullscreenForTabOrPending( const content::WebContents* source) const override; + content::SecurityStyle GetSecurityStyle( + content::WebContents* web_contents, + content::SecurityStyleExplanations* explanations) override; // brightray::InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, diff --git a/atom/common/atom_constants.cc b/atom/common/atom_constants.cc index dacda3c816c..f66c947aa24 100644 --- a/atom/common/atom_constants.cc +++ b/atom/common/atom_constants.cc @@ -6,6 +6,22 @@ namespace atom { -const char* kCORSHeader = "Access-Control-Allow-Origin: *"; +const char kCORSHeader[] = "Access-Control-Allow-Origin: *"; + +const char kSHA1Certificate[] = "SHA-1 Certificate"; +const char kSHA1MajorDescription[] = + "The certificate for this site expires in 2017 or later, " + "and the certificate chain contains a certificate signed using SHA-1."; +const char kSHA1MinorDescription[] = + "The certificate for this site expires in 2016, " + "and the certificate chain contains a certificate signed using SHA-1."; +const char kCertificateError[] = "Certificate Error"; +const char kValidCertificate[] = "Valid Certificate"; +const char kValidCertificateDescription[] = + "The connection to this site is using a valid, trusted server certificate."; +const char kSecureProtocol[] = "Secure TLS connection"; +const char kSecureProtocolDescription[] = + "The connection to this site is using a strong protocol version " + "and cipher suite."; } // namespace atom diff --git a/atom/common/atom_constants.h b/atom/common/atom_constants.h index e0d42e83eef..b67b7b2e4ae 100644 --- a/atom/common/atom_constants.h +++ b/atom/common/atom_constants.h @@ -8,7 +8,17 @@ namespace atom { // Header to ignore CORS. -extern const char* kCORSHeader; +extern const char kCORSHeader[]; + +// Strings describing Chrome security policy for DevTools security panel. +extern const char kSHA1Certificate[]; +extern const char kSHA1MajorDescription[]; +extern const char kSHA1MinorDescription[]; +extern const char kCertificateError[]; +extern const char kValidCertificate[]; +extern const char kValidCertificateDescription[]; +extern const char kSecureProtocol[]; +extern const char kSecureProtocolDescription[]; } // namespace atom diff --git a/filenames.gypi b/filenames.gypi index 688886b5b9c..dd9edb409f5 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -157,6 +157,8 @@ 'atom/browser/atom_quota_permission_context.h', 'atom/browser/atom_resource_dispatcher_host_delegate.cc', 'atom/browser/atom_resource_dispatcher_host_delegate.h', + 'atom/browser/atom_security_state_model_client.cc', + 'atom/browser/atom_security_state_model_client.h', 'atom/browser/atom_speech_recognition_manager_delegate.cc', 'atom/browser/atom_speech_recognition_manager_delegate.h', 'atom/browser/bridge_task_runner.cc', From b84a178cebd3d193fa4cd9109855a9be7a2149f9 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 14 Apr 2016 21:52:17 +0900 Subject: [PATCH 0492/1265] Set the backgroundColor of RenderWidgetHostView --- atom/browser/api/atom_api_web_contents.cc | 14 +++++++++++--- atom/browser/native_window_mac.mm | 11 ++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 81e2423a351..6c9c1b58ea4 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -20,6 +20,7 @@ #include "atom/browser/web_view_guest_delegate.h" #include "atom/common/api/api_messages.h" #include "atom/common/api/event_emitter_caller.h" +#include "atom/common/color_util.h" #include "atom/common/mouse_util.h" #include "atom/common/native_mate_converters/blink_converter.h" #include "atom/common/native_mate_converters/callback.h" @@ -747,12 +748,19 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) { params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; web_contents()->GetController().LoadURLWithParams(params); - // Set the background color of RenderViewHost to transparent so it doesn't - // override the background color set by the user. + // Set the background color of RenderWidgetHostView. // We have to call it right after LoadURL because the RenderViewHost is only // created after loading a page. const auto view = web_contents()->GetRenderWidgetHostView(); - view->SetBackgroundColor(SK_ColorTRANSPARENT); + WebContentsPreferences* web_preferences = + WebContentsPreferences::FromWebContents(web_contents()); + std::string color_name; + if (web_preferences->web_preferences()->GetString(options::kBackgroundColor, + &color_name)) { + view->SetBackgroundColor(ParseHexColor(color_name)); + } else { + view->SetBackgroundColor(SK_ColorTRANSPARENT); + } // For the same reason we can only disable hidden here. const auto host = static_cast( diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 3c76cbe25a5..b24e828e578 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -807,9 +807,14 @@ bool NativeWindowMac::IsKiosk() { } void NativeWindowMac::SetBackgroundColor(const std::string& color_name) { - base::ScopedCFTypeRef color = - skia::CGColorCreateFromSkColor(ParseHexColor(color_name)); - [[[window_ contentView] layer] setBackgroundColor:color]; + SkColor color = ParseHexColor(color_name); + base::ScopedCFTypeRef cgcolor = + skia::CGColorCreateFromSkColor(color); + [[[window_ contentView] layer] setBackgroundColor:cgcolor]; + + const auto view = web_contents()->GetRenderWidgetHostView(); + if (view) + view->SetBackgroundColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { From b8e64ac40efc0a89fabd0da820a1a8beceaffd16 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 14 Apr 2016 22:55:09 +0900 Subject: [PATCH 0493/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/session.md | 3 +++ .../ko-KR/development/coding-style.md | 18 ++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index 5bb4867eda0..36907992a31 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -444,6 +444,9 @@ HTTP 요청을 보내기 전 요청 헤더를 사용할 수 있을 때 `listener * `cancel` Boolean * `responseHeaders` Object (optional) - 이 속성이 제공되면 서버는 이 헤더와 함께 응답합니다. + * `statusLine` String (optional) - `responseHeaders`를 덮어쓸 땐, 헤더의 상태를 + 변경하기 위해 반드시 지정되어야 합니다. 그렇지 않은 경우, 기존의 응답 헤더의 상태가 + 사용됩니다. #### `ses.webRequest.onResponseStarted([filter, ]listener)` diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index 9c15f677fe2..211eaa4cc0d 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -39,9 +39,19 @@ C++ 코드는 많은 Chromium의 추상화와 타입을 사용합니다. 따라 * [Template literals](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals) 는 `+`로 문자열을 합치는 대신 사용합니다. -## API 이름 +## 이름 짓기 -새로운 API를 만들 땐 getter, setter스타일 대신 jQuery의 one-function 스타일을 -사용해야 합니다. 예를 들어 `.getText()`와 `.setText(text)`대신에 `.text([text])` -형식으로 설계하면 됩니다. 포럼에 이 문제에 대한 [논의](https://github.com/electron/electron/issues/46)가 +Electron API는 Node.js와 비슷한 명명법을 사용합니다: + +- `BrowserWindow`와 같은 모듈 자체를 뜻하는 이름은, `CamelCase`를 사용합니다. +- `globalShortcut`과 같은 API의 세트일 땐, `mixedCase`를 사용합니다. +- API가 객체의 속성일 경우, 그리고 `win.webContents`와 같이 충분히 복잡하고 분리된 + 부분일 경우, `mixedCase`를 사용합니다. +- 다른 모듈이 아닌 API를 구현할 땐, ` Tag` 또는 `Process Object`와 같이 + 단순하고 자연스러운 제목을 사용합니다. + +새로운 API를 만들 땐 jQuery의 one-function 스타일 대신 getter, setter스타일을 +사용해야 합니다. 예를 들어 `.text([text])` 대신 `.getText()`와 `.setText(text)` +형식으로 함수를 설계하면 됩니다. 포럼에 이 문제에 대한 +[논의](https://github.com/electron/electron/issues/46)가 진행되고 있습니다. From 95a53fc832497a635c0a6f9fad5fbb71901f3c64 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 14 Apr 2016 22:56:56 +0900 Subject: [PATCH 0494/1265] :memo: Small fixes [ci skip] --- docs-translations/ko-KR/development/coding-style.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/ko-KR/development/coding-style.md b/docs-translations/ko-KR/development/coding-style.md index 211eaa4cc0d..ff162575d72 100644 --- a/docs-translations/ko-KR/development/coding-style.md +++ b/docs-translations/ko-KR/development/coding-style.md @@ -52,6 +52,6 @@ Electron API는 Node.js와 비슷한 명명법을 사용합니다: 새로운 API를 만들 땐 jQuery의 one-function 스타일 대신 getter, setter스타일을 사용해야 합니다. 예를 들어 `.text([text])` 대신 `.getText()`와 `.setText(text)` -형식으로 함수를 설계하면 됩니다. 포럼에 이 문제에 대한 +형식으로 함수를 설계하면 됩니다. 포럼에서 이 문제에 대한 [논의](https://github.com/electron/electron/issues/46)가 진행되고 있습니다. From 4708477f5a733e037c95a7b51b451e708b377f1f Mon Sep 17 00:00:00 2001 From: christoth Date: Thu, 14 Apr 2016 10:29:55 -0400 Subject: [PATCH 0495/1265] webview: add CSS styling notes Create a new section for CSS and add notes to avoid hiding the webview via hidden or display:none; and provide a recommended approach. --- docs/api/web-view-tag.md | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 8df8d29347c..cee06dfa35d 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -20,11 +20,6 @@ control the appearance of the `webview` container: ```html ``` -Please note that the `webview` tag's style uses `display:flex;` internally to -ensure the child `object` element fills the full height and width of its `webview` -container when used with traditional and flexbox layouts (since v0.36.11). Please -do not overwrite the default `display:flex;` CSS property, unless specifying -`display:inline-flex;` for inline layout. If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the @@ -50,6 +45,36 @@ and displays a "loading..." message during the load time: ``` +## CSS Styling Notes + +Please note that the `webview` tag's style uses `display:flex;` internally to +ensure the child `object` element fills the full height and width of its `webview` +container when used with traditional and flexbox layouts (since v0.36.11). Please +do not overwrite the default `display:flex;` CSS property, unless specifying +`display:inline-flex;` for inline layout. + +`webview` has issues being hidden using the `hidden` attribute or using `display: none;`. +It can cause unusual rendering behaviour within its child `browserplugin` object +and the web page is reloaded, when the `webview` is un-hidden, as opposed to just +becoming visible again. The recommended approach is to hide the `webview` using +CSS by zeroing the `width` & `height` and allowing the element to shrink to the 0px +dimensions via `flex`. + +```html + +``` + ## Tag Attributes The `webview` tag has the following attributes: From 7b56085a0ac8f2d8190922dfcd2fb951efd66581 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Thu, 14 Apr 2016 10:50:08 -0500 Subject: [PATCH 0496/1265] Update menu.md There was a missing reference to webContents. --- docs/api/menu.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/menu.md b/docs/api/menu.md index 2c1374fc888..cb5a0cbe2df 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -109,7 +109,7 @@ var template = [ })(), click: function(item, focusedWindow) { if (focusedWindow) - focusedWindow.toggleDevTools(); + focusedWindow.webContents.toggleDevTools(); } }, ] From a5b93211e6bff7f734564348b229b92d7d6be9a8 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Tue, 12 Apr 2016 18:09:46 -0700 Subject: [PATCH 0497/1265] AutoUpdate Windows: Don't spawn if running Previously, the auto updater would run as many squirrel processes as told. This introduces a little change where instead of spawning a second process, we attach to the already running process - or, if different arguments are passed, return and emit an error. This is not failsafe, but it ensures that we don't run into simple race condition crashes. Closes $5097 --- .../api/auto-updater/squirrel-update-win.js | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/browser/api/auto-updater/squirrel-update-win.js b/lib/browser/api/auto-updater/squirrel-update-win.js index da27e02aab6..0910c5f4efb 100644 --- a/lib/browser/api/auto-updater/squirrel-update-win.js +++ b/lib/browser/api/auto-updater/squirrel-update-win.js @@ -7,17 +7,34 @@ const appFolder = path.dirname(process.execPath) // i.e. my-app/Update.exe const updateExe = path.resolve(appFolder, '..', 'Update.exe') - const exeName = path.basename(process.execPath) +var spawnedArgs = [] +var spawnedProcess + +var isSameArgs = function (args) { + return (args.length === spawnedArgs.length) && args.every(function (e, i) { + return e === spawnedArgs[i] + }) +} // Spawn a command and invoke the callback when it completes with an error // and the output from standard out. var spawnUpdate = function (args, detached, callback) { - var error, errorEmitted, spawnedProcess, stderr, stdout + var error, errorEmitted, stderr, stdout + try { - spawnedProcess = spawn(updateExe, args, { - detached: detached - }) + // Ensure we don't spawn multiple squirrel processes + // Process spawned, same args: Attach events to alread running process + // Process spawned, different args: Return with error + // No process spawned: Spawn new process + if (spawnedProcess && !isSameArgs(args)) { + return callback('AutoUpdater process with arugments ' + args + ' is already running') + } else if (!spawnedProcess) { + spawnedProcess = spawn(updateExe, args, { + detached: detached + }) + spawnedArgs = args || [] + } } catch (error1) { error = error1 @@ -41,6 +58,9 @@ var spawnUpdate = function (args, detached, callback) { return callback(error) }) return spawnedProcess.on('exit', function (code, signal) { + spawnedProcess = undefined + spawnedArgs = [] + // We may have already emitted an error. if (errorEmitted) { return From 7d96f3d720f32b3bc6166c01cbe04152d93e8b39 Mon Sep 17 00:00:00 2001 From: Jessica Lord Date: Thu, 14 Apr 2016 15:53:34 -0700 Subject: [PATCH 0498/1265] Add new line so that the list is styled correctly on website --- docs/api/desktop-capturer.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index 7863622e372..3babe0e1638 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -65,6 +65,7 @@ Starts a request to get all desktop sources, `callback` will be called with The `sources` is an array of `Source` objects, each `Source` represents a captured screen or individual window, and has following properties: + * `id` String - The id of the captured window or screen used in `navigator.webkitGetUserMedia`. The format looks like `window:XX` or `screen:XX` where `XX` is a random generated number. From 1985e1b8e0dafaacc5790a8b14b006edb7ac45dc Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Fri, 15 Apr 2016 10:04:01 +0800 Subject: [PATCH 0499/1265] translation error in browser-window.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 'same-origin policy' means '同源策略' in Chinese --- docs-translations/zh-CN/api/browser-window.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/zh-CN/api/browser-window.md b/docs-translations/zh-CN/api/browser-window.md index 6e486406d63..aedc5f06a2c 100644 --- a/docs-translations/zh-CN/api/browser-window.md +++ b/docs-translations/zh-CN/api/browser-window.md @@ -99,7 +99,7 @@ win.show(); * `zoomFactor` Number - 界面默认缩放值, `3.0` 表示 `300%`. 默认 `1.0`. * `javascript` Boolean - 开启javascript支持. 默认为`true`. -* `webSecurity` Boolean - 当设置为 `false`, 它将禁用相同地方的规则 (通常测试服), 并且如果有2个非用户设置的参数,就设置 +* `webSecurity` Boolean - 当设置为 `false`, 它将禁用同源策略 (通常用来测试网站), 并且如果有2个非用户设置的参数,就设置 `allowDisplayingInsecureContent` 和 `allowRunningInsecureContent` 的值为 `true`. 默认为 `true`. * `allowDisplayingInsecureContent` Boolean -允许一个使用 https的界面来展示由 http URLs 传过来的资源. 默认`false`. @@ -758,4 +758,4 @@ windows上句柄类型为 `HWND` ,OS X `NSView*` , Linux `Window`. 忽略窗口的所有鼠标事件. -[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 \ No newline at end of file +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 From 4dd2716865f6944606f8dffd27ab68434f30643b Mon Sep 17 00:00:00 2001 From: Jessica Lord Date: Thu, 14 Apr 2016 20:55:43 -0700 Subject: [PATCH 0500/1265] Fix headers --- docs/api/session.md | 56 ++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/docs/api/session.md b/docs/api/session.md index 9cccefcbdb6..758082fa621 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -48,11 +48,11 @@ const session = require('electron').session; var ses = session.fromPartition('persist:name'); ``` -### Instance Events +## Instance Events The following events are available on instances of `Session`: -#### Event: 'will-download' +### Event: 'will-download' * `event` Event * `item` [DownloadItem](download-item.md) @@ -72,11 +72,11 @@ session.defaultSession.on('will-download', function(event, item, webContents) { }); ``` -### Instance Methods +## Instance Methods The following methods are available on instances of `Session`: -#### `ses.cookies` +### `session.cookies` The `cookies` gives you ability to query and modify cookies. For example: @@ -100,7 +100,7 @@ session.defaultSession.cookies.set(cookie, function(error) { }); ``` -#### `ses.cookies.get(filter, callback)` +### `session.cookies.get(filter, callback)` * `filter` Object * `url` String (optional) - Retrieves cookies which are associated with @@ -132,7 +132,7 @@ with `callback(error, cookies)` on complete. the number of seconds since the UNIX epoch. Not provided for session cookies. -#### `ses.cookies.set(details, callback)` +### `session.cookies.set(details, callback)` * `details` Object * `url` String - Retrieves cookies which are associated with `url` @@ -151,7 +151,7 @@ with `callback(error, cookies)` on complete. Sets the cookie with `details`, `callback` will be called with `callback(error)` on complete. -#### `ses.cookies.remove(url, name, callback)` +### `session.cookies.remove(url, name, callback)` * `url` String - The URL associated with the cookie. * `name` String - The name of cookie to remove. @@ -160,20 +160,20 @@ on complete. Removes the cookies matching `url` and `name`, `callback` will called with `callback()` on complete. -#### `ses.getCacheSize(callback)` +### `session.getCacheSize(callback)` * `callback` Function * `size` Integer - Cache size used in bytes. Returns the session's current cache size. -#### `ses.clearCache(callback)` +### `session.clearCache(callback)` * `callback` Function - Called when operation is done Clears the session’s HTTP cache. -#### `ses.clearStorageData([options, ]callback)` +### `session.clearStorageData([options, ]callback)` * `options` Object (optional) * `origin` String - Should follow `window.location.origin`’s representation @@ -187,11 +187,11 @@ Clears the session’s HTTP cache. Clears the data of web storages. -#### `ses.flushStorageData()` +### `session.flushStorageData()` Writes any unwritten DOMStorage data to disk. -#### `ses.setProxy(config, callback)` +### `session.setProxy(config, callback)` * `config` Object * `pacScript` String - The URL associated with the PAC file. @@ -228,7 +228,7 @@ For example: * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. -### `ses.resolveProxy(url, callback)` +### `session.resolveProxy(url, callback)` * `url` URL * `callback` Function @@ -236,14 +236,14 @@ For example: Resolves the proxy information for `url`. The `callback` will be called with `callback(proxy)` when the request is performed. -#### `ses.setDownloadPath(path)` +### `session.setDownloadPath(path)` * `path` String - The download location Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. -#### `ses.enableNetworkEmulation(options)` +### `session.enableNetworkEmulation(options)` * `options` Object * `offline` Boolean - Whether to emulate network outage. @@ -265,12 +265,12 @@ window.webContents.session.enableNetworkEmulation({ window.webContents.session.enableNetworkEmulation({offline: true}); ``` -#### `ses.disableNetworkEmulation()` +### `session.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. -#### `ses.setCertificateVerifyProc(proc)` +### `session.setCertificateVerifyProc(proc)` * `proc` Function @@ -291,7 +291,7 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c }); ``` -#### `ses.setPermissionRequestHandler(handler)` +### `session.setPermissionRequestHandler(handler)` * `handler` Function * `webContents` Object - [WebContents](web-contents.md) requesting the permission. @@ -314,13 +314,13 @@ session.fromPartition(partition).setPermissionRequestHandler(function(webContent }); ``` -#### `ses.clearHostResolverCache([callback])` +### `session.clearHostResolverCache([callback])` * `callback` Function (optional) - Called when operation is done. Clears the host resolver cache. -#### `ses.webRequest` +### `session.webRequest` The `webRequest` API set allows to intercept and modify contents of a request at various stages of its lifetime. @@ -349,7 +349,7 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, }); ``` -#### `ses.webRequest.onBeforeRequest([filter, ]listener)` +### `session.webRequest.onBeforeRequest([filter, ]listener)` * `filter` Object * `listener` Function @@ -379,7 +379,7 @@ The `callback` has to be called with an `response` object: * `redirectURL` String (optional) - The original request is prevented from being sent or completed, and is instead redirected to the given URL. -#### `ses.webRequest.onBeforeSendHeaders([filter, ]listener)` +### `session.webRequest.onBeforeSendHeaders([filter, ]listener)` * `filter` Object * `listener` Function @@ -404,7 +404,7 @@ The `callback` has to be called with an `response` object: * `requestHeaders` Object (optional) - When provided, request will be made with these headers. -#### `ses.webRequest.onSendHeaders([filter, ]listener)` +### `session.webRequest.onSendHeaders([filter, ]listener)` * `filter` Object * `listener` Function @@ -421,7 +421,7 @@ response are visible by the time this listener is fired. * `timestamp` Double * `requestHeaders` Object -#### `ses.webRequest.onHeadersReceived([filter,] listener)` +### `session.webRequest.onHeadersReceived([filter,] listener)` * `filter` Object * `listener` Function @@ -449,7 +449,7 @@ The `callback` has to be called with an `response` object: * `statusLine` String (optional) - Should be provided when overriding `responseHeaders` to change header status otherwise original response header's status will be used. -#### `ses.webRequest.onResponseStarted([filter, ]listener)` +### `session.webRequest.onResponseStarted([filter, ]listener)` * `filter` Object * `listener` Function @@ -470,7 +470,7 @@ and response headers are available. * `statusCode` Integer * `statusLine` String -#### `ses.webRequest.onBeforeRedirect([filter, ]listener)` +### `session.webRequest.onBeforeRedirect([filter, ]listener)` * `filter` Object * `listener` Function @@ -491,7 +491,7 @@ redirect is about to occur. * `fromCache` Boolean * `responseHeaders` Object -#### `ses.webRequest.onCompleted([filter, ]listener)` +### `session.webRequest.onCompleted([filter, ]listener)` * `filter` Object * `listener` Function @@ -510,7 +510,7 @@ completed. * `statusCode` Integer * `statusLine` String -#### `ses.webRequest.onErrorOccurred([filter, ]listener)` +### `session.webRequest.onErrorOccurred([filter, ]listener)` * `filter` Object * `listener` Function From 07346ae85869ce36c1feb0cf72f2f491fe2cdbc4 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Fri, 15 Apr 2016 14:10:11 +0800 Subject: [PATCH 0501/1265] Update sample code in online-offline-events.md change `ipc` to `ipcMain`/`ipcRenderer` --- .../zh-CN/tutorial/online-offline-events.md | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/docs-translations/zh-CN/tutorial/online-offline-events.md b/docs-translations/zh-CN/tutorial/online-offline-events.md index 7389afa4c9e..d61f7378b96 100644 --- a/docs-translations/zh-CN/tutorial/online-offline-events.md +++ b/docs-translations/zh-CN/tutorial/online-offline-events.md @@ -3,10 +3,11 @@ *main.js* ```javascript -var app = require('app'); -var BrowserWindow = require('browser-window'); -var onlineStatusWindow; +const electron = require('electron'); +const app = electron.app; +const BrowserWindow = electron.BrowserWindow; +var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html'); @@ -36,17 +37,18 @@ app.on('ready', function() { *main.js* ```javascript -var app = require('app'); -var ipc = require('ipc'); -var BrowserWindow = require('browser-window'); -var onlineStatusWindow; +const electron = require('electron'); +const app = electron.app; +const ipcMain = electron.ipcMain; +const BrowserWindow = electron.BrowserWindow; +var onlineStatusWindow; app.on('ready', function() { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow.loadURL('file://' + __dirname + '/online-status.html'); }); -ipc.on('online-status-changed', function(event, status) { +ipcMain.on('online-status-changed', function(event, status) { console.log(status); }); ``` @@ -57,9 +59,9 @@ ipc.on('online-status-changed', function(event, status) { ``` -또 하나의 예를 들자면 다음 예제는 랜더러 프로세스에서 template API를 사용하여 +또 하나의 예를 들자면 다음 예제는 렌더러 프로세스에서 template API를 사용하여 어플리케이션 메뉴를 만듭니다: ```javascript diff --git a/docs-translations/ko-KR/api/remote.md b/docs-translations/ko-KR/api/remote.md index ab05d838cc5..3265a795a07 100644 --- a/docs-translations/ko-KR/api/remote.md +++ b/docs-translations/ko-KR/api/remote.md @@ -1,15 +1,15 @@ # remote -`remote` 모듈은 메인 프로세스와 랜더러 프로세스(웹 페이지) 사이의 inter-process +`remote` 모듈은 메인 프로세스와 렌더러 프로세스(웹 페이지) 사이의 inter-process (IPC) 통신을 간단하게 추상화 한 모듈입니다. Electron의 메인 프로세스에선 GUI와 관련 있는(`dialog`, `menu`등) 모듈만 사용할 수 -있습니다. 랜더러 프로세스에서 이러한 모듈들을 사용하려면 `ipc` 모듈을 통해 메인 +있습니다. 렌더러 프로세스에서 이러한 모듈들을 사용하려면 `ipc` 모듈을 통해 메인 프로세스와 inter-process 통신을 해야 합니다. 또한, `remote` 모듈을 사용하면 inter-process 통신을 하지 않고도 간단한 API를 통해 직접 메인 프로세스의 모듈과 메서드를 사용할 수 있습니다. 이 개념은 Java의 [RMI][rmi]와 비슷합니다. -다음 예제는 랜더러 프로세스에서 브라우저 창을 만드는 예제입니다: +다음 예제는 렌더러 프로세스에서 브라우저 창을 만드는 예제입니다: ```javascript const remote = require('electron').remote; @@ -19,7 +19,7 @@ var win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL('https://github.com'); ``` -**참고:** 반대로 메인 프로세스에서 랜더러 프로세스에 접근 하려면 [webContents.executeJavascript](web-contents.md#webcontentsexecutejavascriptcode-usergesture) +**참고:** 반대로 메인 프로세스에서 렌더러 프로세스에 접근 하려면 [webContents.executeJavascript](web-contents.md#webcontentsexecutejavascriptcode-usergesture) 메서드를 사용하면 됩니다. ## Remote 객체 @@ -30,8 +30,8 @@ win.loadURL('https://github.com'); 동기형 inter-process 메시지를 보냅니다. 위의 예제에서 사용한 두 `BrowserWindow`와 `win`은 remote 객체입니다. 그리고 -`new BrowserWindow`이 생성하는 `BrowserWindow` 객체는 랜더러 프로세스에서 생성되지 -않습니다. 대신에 이 `BrowserWindow` 객체는 메인 프로세스에서 생성되며 랜더러 +`new BrowserWindow`이 생성하는 `BrowserWindow` 객체는 렌더러 프로세스에서 생성되지 +않습니다. 대신에 이 `BrowserWindow` 객체는 메인 프로세스에서 생성되며 렌더러 프로세스에 `win` 객체와 같이 이에 대응하는 remote 객체를 반환합니다. 참고로 remote를 통해선 [enumerable 속성](https://developer.mozilla.org/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)을 @@ -39,11 +39,11 @@ win.loadURL('https://github.com'); ## Remote 객체의 생명 주기 -Electron은 랜더러 프로세스의 remote 객체가 살아있는 한(다시 말해서 GC(garbage +Electron은 렌더러 프로세스의 remote 객체가 살아있는 한(다시 말해서 GC(garbage collection)가 일어나지 않습니다) 대응하는 메인 프로세스의 객체는 릴리즈되지 않습니다. Remote 객체가 GC 되려면 대응하는 메인 프로세스 내부 객체의 참조가 해제되어야만 합니다. -만약 remote 객체가 랜더러 프로세스에서 누수가 생겼다면 (예시: 맵에 저장하고 할당 +만약 remote 객체가 렌더러 프로세스에서 누수가 생겼다면 (예시: 맵에 저장하고 할당 해제하지 않음) 대응하는 메인 프로세스의 객체도 누수가 생깁니다. 그래서 remote 객체를 사용할 땐 메모리 누수가 생기지 않도록 매우 주의해서 사용해야 합니다. @@ -51,14 +51,14 @@ Remote 객체가 GC 되려면 대응하는 메인 프로세스 내부 객체의 ## 메인 프로세스로 콜백 넘기기 -메인 프로세스의 코드는 `remote` 모듈을 통해 랜더러 프로세스가 전달하는 콜백 함수를 +메인 프로세스의 코드는 `remote` 모듈을 통해 렌더러 프로세스가 전달하는 콜백 함수를 받을 수 있습니다. 하지만 이 작업은 반드시 주의를 기울여 사용해야 합니다. 첫째, 데드락을 피하기 위해 메인 프로세스로 전달된 콜백들은 비동기로 호출됩니다. 이러한 이유로 메인 프로세스로 전달된 콜백들의 반환 값을 내부 함수에서 언제나 정상적으로 받을 것이라고 예측해선 안됩니다. -예를 들어 메인 프로세스에서 `Array.map` 같은 메서드를 사용할 때 랜더러 프로세스에서 +예를 들어 메인 프로세스에서 `Array.map` 같은 메서드를 사용할 때 렌더러 프로세스에서 전달된 함수를 사용해선 안됩니다: ```javascript @@ -75,7 +75,7 @@ exports.withLocalCallback = function() { ``` ```javascript -// 랜더러 프로세스 +// 렌더러 프로세스 var mapNumbers = require("remote").require("./mapNumbers"); var withRendererCb = mapNumbers.withRendererCallback(function(x) { @@ -87,7 +87,7 @@ var withLocalCb = mapNumbers.withLocalCallback() console.log(withRendererCb, withLocalCb) // [true, true, true], [2, 3, 4] ``` -보다시피 랜더러 콜백의 동기 반환 값은 예상되지 않은 처리입니다. +보다시피 렌더러 콜백의 동기 반환 값은 예상되지 않은 처리입니다. 그리고 메인 프로세스에서 처리한 함수의 반환 값과 일치하지 않습니다. 둘째, 콜백들은 메인 프로세스로 전달, 호출된 이후에도 자동으로 함수의 참조가 릴리즈 되지 @@ -113,9 +113,9 @@ remote.getCurrentWindow().on('close', function() { 설상가상으로 이전에 설치된 콜백의 콘텍스트가 릴리즈 되고 난 후(예: 페이지 새로고침) `close` 이벤트가 발생하면 예외가 발생하고 메인 프로세스가 작동 중지됩니다. -이러한 문제를 피하려면 랜더러 프로세스에서 메인 프로세스로 넘긴 함수의 참조를 사용 후 +이러한 문제를 피하려면 렌더러 프로세스에서 메인 프로세스로 넘긴 함수의 참조를 사용 후 확실하게 제거해야 합니다. 작업 후 이벤트 콜백을 포함하여 책임 있게 함수의 참조를 -제거하거나 메인 프로세스에서 랜더러 프로세스가 종료될 때 내부적으로 함수 참조를 +제거하거나 메인 프로세스에서 렌더러 프로세스가 종료될 때 내부적으로 함수 참조를 제거하도록 설계해야 합니다. ## 메인 프로세스의 빌트인 모듈에 접근 diff --git a/docs-translations/ko-KR/api/screen.md b/docs-translations/ko-KR/api/screen.md index 6cc6535235b..ff57b02e4b2 100644 --- a/docs-translations/ko-KR/api/screen.md +++ b/docs-translations/ko-KR/api/screen.md @@ -6,7 +6,7 @@ `screen`은 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)를 상속 받았습니다. -**참고:** 랜더러 / DevTools에선 이미 DOM 속성이 `window.screen`을 가지고 있으므로 +**참고:** 렌더러 / DevTools에선 이미 DOM 속성이 `window.screen`을 가지고 있으므로 `screen = require('screen')` 형식으로 모듈을 사용할 수 없습니다. 아래의 예제와 같이 `electronScreen` 같은 이름으로 모듈 이름을 대체하여 사용해야 합니다. diff --git a/docs-translations/ko-KR/api/synopsis.md b/docs-translations/ko-KR/api/synopsis.md index 47771b23ceb..3493223cceb 100644 --- a/docs-translations/ko-KR/api/synopsis.md +++ b/docs-translations/ko-KR/api/synopsis.md @@ -5,12 +5,12 @@ node 모듈을 완벽하게 지원합니다. ([네이티브 모듈](../tutorial/ 포함) 또한 Electron은 네이티브 데스크톱 어플리케이션을 개발 할 수 있도록 추가적인 built-in -모듈을 제공합니다. 몇몇 모듈은 메인 프로세스에서만 사용할 수 있고 어떤 모듈은 랜더러 +모듈을 제공합니다. 몇몇 모듈은 메인 프로세스에서만 사용할 수 있고 어떤 모듈은 렌더러 프로세스(웹 페이지)에서만 사용할 수 있습니다. 또한 두 프로세스 모두 사용할 수 있는 모듈도 있습니다. 기본적인 규칙으로 [GUI][gui]와 저 수준 시스템에 관련된 모듈들은 오직 메인 -프로세스에서만 사용할 수 있습니다. [메인 프로세스 vs. 랜더러 프로세스](../tutorial/quick-start.md#메인-프로세스) +프로세스에서만 사용할 수 있습니다. [메인 프로세스 vs. 렌더러 프로세스](../tutorial/quick-start.md#메인-프로세스) 컨셉에 익숙해야 모듈을 다루기 쉬우므로 관련 문서를 읽어 보는 것을 권장합니다. 메인 프로세스 스크립트는 일반 Node.js 스크립트와 비슷합니다: @@ -28,7 +28,7 @@ app.on('ready', function() { }); ``` -랜더러 프로세스도 예외적인 node module들을 사용할 수 있다는 점을 제외하면 일반 웹 +렌더러 프로세스도 예외적인 node module들을 사용할 수 있다는 점을 제외하면 일반 웹 페이지와 크게 다를게 없습니다: ```html diff --git a/docs-translations/ko-KR/api/web-frame.md b/docs-translations/ko-KR/api/web-frame.md index f77ed68f907..292f7d81420 100644 --- a/docs-translations/ko-KR/api/web-frame.md +++ b/docs-translations/ko-KR/api/web-frame.md @@ -1,6 +1,6 @@ # webFrame -`web-frame` 모듈은 현재 웹 페이지의 랜더링 상태를 설정 할 수 있도록 관련 유틸리티를 +`web-frame` 모듈은 현재 웹 페이지의 렌더링 상태를 설정 할 수 있도록 관련 유틸리티를 제공하는 모듈입니다. 다음 예제는 현재 페이지를 200% 줌 합니다: diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index 314cc344976..c47c270d24f 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -149,7 +149,7 @@ API를 사용할 수 있습니다. 이를 지정하면 내부에서 로우레벨 동일한 세션을 공유할 수 있도록 할 수 있습니다. 만약 `partition`이 지정되지 않으면 앱의 기본 세션을 사용합니다. -이 값은 첫 탐색 이전에만 지정할 수 있습니다. 즉. 작동중인 랜더러 프로세스의 세션은 +이 값은 첫 탐색 이전에만 지정할 수 있습니다. 즉. 작동중인 렌더러 프로세스의 세션은 변경할 수 없습니다. 이후 이 값을 바꾸려고 시도하면 DOM 예외를 발생시킵니다. ### `allowpopups` @@ -263,7 +263,7 @@ Webview에 웹 페이지 `url`을 로드합니다. `url`은 `http://`, `file://` ### `.isCrashed()` -랜더러 프로세스가 크래시 됬는지 확인합니다. +렌더러 프로세스가 크래시 됬는지 확인합니다. ### `.setUserAgent(userAgent)` @@ -423,8 +423,8 @@ Webview 페이지를 PDF 형식으로 인쇄합니다. * `channel` String * `args` (optional) -`channel`을 통해 랜더러 프로세스로 비동기 메시지를 보냅니다. 또한 `args`를 지정하여 -임의의 인자를 보낼 수도 있습니다. 랜더러 프로세스는 `ipcRenderer` 모듈의 `channel` +`channel`을 통해 렌더러 프로세스로 비동기 메시지를 보냅니다. 또한 `args`를 지정하여 +임의의 인자를 보낼 수도 있습니다. 렌더러 프로세스는 `ipcRenderer` 모듈의 `channel` 이벤트로 이 메시지를 받아 처리할 수 있습니다. 예제는 [webContents.send](web-contents.md#webcontentssendchannel-args)를 참고하세요. @@ -696,7 +696,7 @@ ipcRenderer.on('ping', function() { ### Event: 'crashed' -랜더러 프로세스가 크래시 되었을 때 발생하는 이벤트입니다. +렌더러 프로세스가 크래시 되었을 때 발생하는 이벤트입니다. ### Event: 'gpu-crashed' diff --git a/docs-translations/ko-KR/development/source-code-directory-structure.md b/docs-translations/ko-KR/development/source-code-directory-structure.md index 7450b3b3e9e..47410b8ec2c 100644 --- a/docs-translations/ko-KR/development/source-code-directory-structure.md +++ b/docs-translations/ko-KR/development/source-code-directory-structure.md @@ -13,7 +13,7 @@ Electron ├── atom - C++ 소스 코드. | ├── app - 시스템 엔트리 코드. | ├── browser - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 -| | 코드와 랜더러 및 웹 페이지 관리 관련 코드. +| | 코드와 렌더러 및 웹 페이지 관리 관련 코드. | | ├── ui - 서로 다른 플랫폼에 대한 UI 관련 구현 코드. | | | ├── cocoa - Cocoa 특정 소스 코드. | | | ├── gtk - GTK+ 특정 소스 코드. @@ -22,9 +22,9 @@ Electron | | ├── net - 네트워킹 관련 코드. | | ├── mac - Mac 특정 Objective-C 소스 코드. | | └── resources - 아이콘들, 플랫폼 종속성 파일들, 기타 등등.. -| ├── renderer - 랜더러 프로세스에서 작동하는 코드. -| | └── api - 랜더러 프로세스 API의 구현. -| └── common - 메인과 랜더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 +| ├── renderer - 렌더러 프로세스에서 작동하는 코드. +| | └── api - 렌더러 프로세스 API의 구현. +| └── common - 메인과 렌더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 | 함수들이 포함되어 있고 node의 메시지 루프와 Chromium의 메시지 루프를 통합. | └── api - 공통 API 구현들, 기초 Electron 빌트-인 모듈들. ├── chromium_src - Chromium에서 복사하여 가져온 소스코드. @@ -33,9 +33,9 @@ Electron ├── lib - JavaScript 소스 코드. | ├── browser - Javascript 메인 프로세스 초기화 코드. | | └── api - Javascript API 구현 코드. -| ├── common - 메인과 랜더러 프로세스에서 모두 사용하는 JavaScript +| ├── common - 메인과 렌더러 프로세스에서 모두 사용하는 JavaScript | | └── api - Javascript API 구현 코드. -| └── renderer - Javascript 랜더러 프로세스 초기화 코드. +| └── renderer - Javascript 렌더러 프로세스 초기화 코드. | └── api - Javascript API 구현 코드. ├── spec - 자동화 테스트. ├── atom.gyp - Electron의 빌드 규칙. diff --git a/docs-translations/ko-KR/faq/electron-faq.md b/docs-translations/ko-KR/faq/electron-faq.md index 5382372bfbb..a038142c5ae 100644 --- a/docs-translations/ko-KR/faq/electron-faq.md +++ b/docs-translations/ko-KR/faq/electron-faq.md @@ -20,13 +20,13 @@ Node.js의 새로운 기능은 보통 V8 업그레이드에서 가져옵니다. ## 어떻게 웹 페이지 간에 데이터를 공유할 수 있나요? -두 웹페이지 간에 (랜더러 프로세스) 데이터를 공유하려면 간단히 이미 모든 브라우저에서 +두 웹페이지 간에 (렌더러 프로세스) 데이터를 공유하려면 간단히 이미 모든 브라우저에서 사용할 수 있는 HTML5 API들을 사용하면 됩니다. 가장 좋은 후보는 [Storage API][storage], [`localStorage`][local-storage], [`sessionStorage`][session-storage], 그리고 [IndexedDB][indexed-db]가 있습니다. 또는 Electron에서만 사용할 수 있는 IPC 시스템을 사용하여 메인 프로세스의 global -변수에 데이터를 저장한 후 다음과 같이 랜더러 프로세스에서 `remote` 모듈을 사용하여 +변수에 데이터를 저장한 후 다음과 같이 렌더러 프로세스에서 `remote` 모듈을 사용하여 접근할 수 있습니다: ```javascript @@ -141,7 +141,7 @@ npm uninstall -g electron 그런데 여전히 빌트인 모듈이 계속해서 문제를 발생시키는 경우, 아마 모듈을 잘못 사용하고 있을 가능성이 큽니다. 예를 들면 `electron.app`은 메인 프로세스에서만 사용할 수 있는 -모듈이며, 반면 `electron.webFrame` 모듈은 랜더러 프로세스에서만 사용할 수 있는 +모듈이며, 반면 `electron.webFrame` 모듈은 렌더러 프로세스에서만 사용할 수 있는 모듈입니다. [memory-management]: https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management diff --git a/docs-translations/ko-KR/styleguide.md b/docs-translations/ko-KR/styleguide.md index 91aa233dd4d..ec57970e513 100644 --- a/docs-translations/ko-KR/styleguide.md +++ b/docs-translations/ko-KR/styleguide.md @@ -18,7 +18,7 @@ Electron 문서를 작성하는 규칙은 다음과 같습니다. 추가합니다. - 메서드 헤더는 `code backtick` 으로 표시합니다. - 이벤트 헤더는 한 '따옴표'로 표시합니다. -- 리스트를 2 단계 이상 중첩하지 않습니다. (안타깝게도 markdown 랜더러가 이를 지원하지 +- 리스트를 2 단계 이상 중첩하지 않습니다. (안타깝게도 markdown 렌더러가 이를 지원하지 않습니다) - 섹션에 대한 제목을 추가합니다. Events, Class 메서드 그리고 인스턴스 메서드 등 - 어떤 '것'의 사용 결과를 설명할 때 '될 것입니다' 형식을 사용하여 설명합니다. diff --git a/docs-translations/ko-KR/tutorial/debugging-main-process.md b/docs-translations/ko-KR/tutorial/debugging-main-process.md index 58c671f132e..339c28daab7 100644 --- a/docs-translations/ko-KR/tutorial/debugging-main-process.md +++ b/docs-translations/ko-KR/tutorial/debugging-main-process.md @@ -1,6 +1,6 @@ # 메인 프로세스 디버깅하기 -브라우저 창의 개발자 도구는 웹 페이지 같은 랜더러 프로세스의 스크립트만 디버깅이 +브라우저 창의 개발자 도구는 웹 페이지 같은 렌더러 프로세스의 스크립트만 디버깅이 가능합니다. 대신 Electron은 메인 프로세스의 디버깅을 위해 `--debug` 과 `--debug-brk` 스위치들을 제공합니다. diff --git a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md index 91b906c0a19..961bfc83076 100644 --- a/docs-translations/ko-KR/tutorial/desktop-environment-integration.md +++ b/docs-translations/ko-KR/tutorial/desktop-environment-integration.md @@ -14,7 +14,7 @@ Windows, Linux, OS X 운영체제 모두 기본적으로 어플리케이션에 통해 개발자가 편리하게 데스크톱 알림을 사용할 수 있는 기능을 제공합니다. 데스크톱 알림은 운영체제의 네이티브 알림 API를 사용하여 표시합니다. -**참고:** 이 API는 HTML5 API이기 때문에 랜더러 프로세스에서만 사용할 수 있습니다. +**참고:** 이 API는 HTML5 API이기 때문에 렌더러 프로세스에서만 사용할 수 있습니다. ```javascript var myNotification = new Notification('Title', { diff --git a/docs-translations/ko-KR/tutorial/online-offline-events.md b/docs-translations/ko-KR/tutorial/online-offline-events.md index f66e2e2bbb5..5b91fc61bd5 100644 --- a/docs-translations/ko-KR/tutorial/online-offline-events.md +++ b/docs-translations/ko-KR/tutorial/online-offline-events.md @@ -1,6 +1,6 @@ # 온라인/오프라인 이벤트 감지 -온라인/오프라인 이벤트는 다음 예제와 같이 랜더러 프로세스에서 표준 HTML5 API를 이용하여 +온라인/오프라인 이벤트는 다음 예제와 같이 렌더러 프로세스에서 표준 HTML5 API를 이용하여 구현할 수 있습니다. _main.js_ diff --git a/docs-translations/ko-KR/tutorial/quick-start.md b/docs-translations/ko-KR/tutorial/quick-start.md index d13e22351bc..eb95232a06f 100644 --- a/docs-translations/ko-KR/tutorial/quick-start.md +++ b/docs-translations/ko-KR/tutorial/quick-start.md @@ -16,23 +16,23 @@ Electron은 실행될 때 __메인 프로세스__ 로 불리는 `package.json` 호출합니다. 이 스크립트는 메인 프로세스에서 작동합니다. GUI 컴포넌트를 조작하거나 웹 페이지 창을 생성할 수 있습니다. -### 랜더러 프로세스 +### 렌더러 프로세스 Electron이 웹페이지를 보여줄 때 Chromium의 multi-processes 구조도 같이 사용됩니다. -Electron 프로세스 내에서 작동하는 웹 페이지를 __랜더러 프로세스__ 라고 불립니다. +Electron 프로세스 내에서 작동하는 웹 페이지를 __렌더러 프로세스__ 라고 불립니다. 보통 일반 브라우저의 웹 페이지들은 샌드박스가 적용된 환경에서 작동하며 네이티브 리소스에는 접근할 수 없도록 되어 있습니다. 하지만 Electron은 웹 페이지 내에서 Node.js API를 사용하여 low-level 수준으로 운영체제와 상호작용할 수 있습니다. -### 메인 프로세스와 랜더러 프로세스의 차이점 +### 메인 프로세스와 렌더러 프로세스의 차이점 메인 프로세스는 `BrowserWindow` Class를 사용하여 새로운 창을 만들 수 있습니다. -`BrowserWindow` 인스턴스는 따로 분리된 프로세스에서 랜더링 되며 이 프로세스를 랜더러 -프로세스라고 합니다. `BrowserWindow` 인스턴스가 소멸할 때 그 창의 랜더러 프로세스도 +`BrowserWindow` 인스턴스는 따로 분리된 프로세스에서 렌더링 되며 이 프로세스를 렌더러 +프로세스라고 합니다. `BrowserWindow` 인스턴스가 소멸할 때 그 창의 렌더러 프로세스도 같이 소멸합니다. -메인 프로세스는 모든 웹 페이지와 랜더러 프로세스를 관리하며 랜더러 프로세스는 각각의 +메인 프로세스는 모든 웹 페이지와 렌더러 프로세스를 관리하며 렌더러 프로세스는 각각의 프로세스에 고립되며 웹 페이지의 작동에만 영향을 끼칩니다. 웹 페이지 내에선 기본적으로 네이티브 GUI와 관련된 API를 호출할 수 없도록 설계 되어 @@ -40,7 +40,7 @@ API를 사용하여 low-level 수준으로 운영체제와 상호작용할 수 리소스를 누수시킬 수 있기 때문입니다. 꼭 웹 페이지 내에서 API를 사용해야 한다면 메인 프로세스에서 그 작업을 처리할 수 있도록 메인 프로세스와 통신을 해야 합니다. -Electron에는 메인 프로세스와 랜더러 프로세스 사이에 통신을 할 수 있도록 +Electron에는 메인 프로세스와 렌더러 프로세스 사이에 통신을 할 수 있도록 [ipc](../api/ipc-renderer.md) 모듈을 제공하고 있습니다. 또는 [remote](../api/remote.md) 모듈을 사용하여 RPC 스타일로 통신할 수도 있습니다. 또한 FAQ에서 [다양한 객체를 공유하는 방법](share-data)도 소개하고 있습니다. From 0bf1e561561d87fb1ba9a4af418a1f74306e353a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 18 Apr 2016 13:59:15 +0900 Subject: [PATCH 0511/1265] Update brightray for electron/brightray#212 --- atom/browser/api/atom_api_session.cc | 26 +++++++++----------------- atom/browser/api/atom_api_session.h | 3 +++ vendor/brightray | 2 +- 3 files changed, 13 insertions(+), 18 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 0f104c76072..2b352e52f7c 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -23,12 +23,13 @@ #include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/node_includes.h" #include "base/files/file_path.h" +#include "base/guid.h" #include "base/prefs/pref_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" #include "brightray/browser/net/devtools_network_conditions.h" -#include "brightray/browser/net/devtools_network_controller.h" +#include "brightray/browser/net/devtools_network_controller_handle.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" @@ -288,7 +289,8 @@ void ClearHostResolverCacheInIO( } // namespace Session::Session(AtomBrowserContext* browser_context) - : browser_context_(browser_context) { + : devtools_network_emulation_client_id_(base::GenerateGUID()), + browser_context_(browser_context) { AttachAsUserData(browser_context); // Observe DownloadManger to get download notifications. @@ -381,25 +383,15 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) { download_throughput, upload_throughput)); } - auto controller = browser_context_->GetDevToolsNetworkController(); - BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, - base::Bind(&brightray::DevToolsNetworkController::SetNetworkState, - base::Unretained(controller), - std::string(), - base::Passed(&conditions))); + browser_context_->network_controller_handle()->SetNetworkState( + devtools_network_emulation_client_id_, std::move(conditions)); } void Session::DisableNetworkEmulation() { - scoped_ptr conditions( - new brightray::DevToolsNetworkConditions(false)); - auto controller = browser_context_->GetDevToolsNetworkController(); - - BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, - base::Bind(&brightray::DevToolsNetworkController::SetNetworkState, - base::Unretained(controller), - std::string(), - base::Passed(&conditions))); + scoped_ptr conditions; + browser_context_->network_controller_handle()->SetNetworkState( + devtools_network_emulation_client_id_, std::move(conditions)); } void Session::SetCertVerifyProc(v8::Local val, diff --git a/atom/browser/api/atom_api_session.h b/atom/browser/api/atom_api_session.h index 02d8ba5cdec..7da01acdaaa 100644 --- a/atom/browser/api/atom_api_session.h +++ b/atom/browser/api/atom_api_session.h @@ -86,6 +86,9 @@ class Session: public mate::TrackableObject, v8::Global cookies_; v8::Global web_request_; + // The X-DevTools-Emulate-Network-Conditions-Client-Id. + std::string devtools_network_emulation_client_id_; + scoped_refptr browser_context_; DISALLOW_COPY_AND_ASSIGN(Session); diff --git a/vendor/brightray b/vendor/brightray index 79b80e83f4a..bc9c496a618 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 79b80e83f4a64790e51ad2fc44b0a56bdb3d7ef3 +Subproject commit bc9c496a6185e37e792c10bfc5b49ea779b27cd3 From fcf04377d7e69877db4f6fca3d2e7b35e4241074 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 14 Apr 2016 08:27:27 +0530 Subject: [PATCH 0512/1265] set network emulation client id in request headers --- atom/browser/api/atom_api_session.cc | 10 ++++++++++ atom/browser/net/atom_network_delegate.cc | 8 ++++++++ atom/common/options_switches.cc | 4 ++++ atom/common/options_switches.h | 2 ++ 4 files changed, 24 insertions(+) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 2b352e52f7c..c6ef6619034 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -22,6 +22,8 @@ #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/node_includes.h" +#include "atom/common/options_switches.h" +#include "base/command_line.h" #include "base/files/file_path.h" #include "base/guid.h" #include "base/prefs/pref_service.h" @@ -286,6 +288,12 @@ void ClearHostResolverCacheInIO( } } +void SetDevToolsNetworkEmulationClientId(const std::string& id) { + auto cmd_line = base::CommandLine::ForCurrentProcess(); + cmd_line->AppendSwitchASCII( + switches::kDevToolsEmulateNetworkConditionsClientId, id); +} + } // namespace Session::Session(AtomBrowserContext* browser_context) @@ -386,12 +394,14 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) { browser_context_->network_controller_handle()->SetNetworkState( devtools_network_emulation_client_id_, std::move(conditions)); + SetDevToolsNetworkEmulationClientId(devtools_network_emulation_client_id_); } void Session::DisableNetworkEmulation() { scoped_ptr conditions; browser_context_->network_controller_handle()->SetNetworkState( devtools_network_emulation_client_id_, std::move(conditions)); + SetDevToolsNetworkEmulationClientId(std::string()); } void Session::SetCertVerifyProc(v8::Local val, diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 86bfe12079a..cb602c4b362 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -8,6 +8,8 @@ #include #include "atom/common/native_mate_converters/net_converter.h" +#include "atom/common/options_switches.h" +#include "base/command_line.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "content/public/browser/browser_thread.h" @@ -241,6 +243,12 @@ int AtomNetworkDelegate::OnBeforeSendHeaders( net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers) { + auto cmd_line = base::CommandLine::ForCurrentProcess(); + auto client_id = cmd_line->GetSwitchValueASCII( + switches::kDevToolsEmulateNetworkConditionsClientId); + if (!client_id.empty()) + headers->SetHeader( + switches::kDevToolsEmulateNetworkConditionsClientId, client_id); if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders)) return brightray::NetworkDelegate::OnBeforeSendHeaders( request, callback, headers); diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index ce28cc98fac..b4c5c4ef831 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -156,6 +156,10 @@ const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; +// Client id for devtools network emulation. +const char kDevToolsEmulateNetworkConditionsClientId[] = + "X-DevTools-Emulate-Network-Conditions-Client-Id"; + } // namespace switches } // namespace atom diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 52d64c00d51..e05be3b4359 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -87,6 +87,8 @@ extern const char kOpenerID[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; +extern const char kDevToolsEmulateNetworkConditionsClientId[]; + } // namespace switches } // namespace atom From e81cec40589aff1688917306ea0c57b3e85016d8 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 10:41:31 +0530 Subject: [PATCH 0513/1265] app: api to import client certificate --- atom/browser/api/atom_api_app.cc | 69 ++++++- atom/browser/api/atom_api_app.h | 11 ++ atom/browser/atom_browser_client.cc | 30 --- .../browser/certificate_manager_model.cc | 177 ++++++++++++++++++ .../browser/certificate_manager_model.h | 116 ++++++++++++ filenames.gypi | 2 + 6 files changed, 374 insertions(+), 31 deletions(-) create mode 100644 chromium_src/chrome/browser/certificate_manager_model.cc create mode 100644 chromium_src/chrome/browser/certificate_manager_model.h diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 52d6ec3d338..4cbae0885e9 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -24,6 +24,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/path_service.h" #include "brightray/browser/brightray_paths.h" #include "chrome/common/chrome_paths.h" @@ -157,6 +158,43 @@ void PassLoginInformation(scoped_refptr login_handler, login_handler->CancelAuth(); } +net::CertificateList ImportCertsFromFile( + const base::FilePath& path) { + net::CertificateList certs; + if (path.empty()) + return certs; + + std::string cert_data; + if (!base::ReadFileToString(path, &cert_data)) + return certs; + + certs = net::X509Certificate::CreateCertificateListFromBytes( + cert_data.data(), cert_data.size(), + net::X509Certificate::FORMAT_AUTO); + + return certs; +} + +int ImportCertificateIntoCertStore( + CertificateManagerModel* model, + const base::FilePath& path, + const base::FilePath& ca_path, + const base::string16& password) { + LOG(WARNING) << "importing ...."; + + std::string file_data; + int result = -1; + net::CertificateList ca_certs; + net::NSSCertDatabase::ImportCertFailureList not_imported; + auto module = model->cert_db()->GetPublicModule(); + if (base::ReadFileToString(path, &file_data)) { + result &= model->ImportFromPKCS12(module, file_data, password, true); + ca_certs = ImportCertsFromFile(ca_path); + result &= model->ImportCACerts(ca_certs, net::NSSCertDatabase::TRUST_DEFAULT, ¬_imported); + } + return result; +} + } // namespace App::App() { @@ -369,6 +407,34 @@ bool App::MakeSingleInstance( } } +void App::ImportClientCertificate( + const base::FilePath& path, + const base::FilePath& ca_path, + + const base::string16& password, + const net::CompletionCallback& callback) { + auto browser_context = AtomBrowserMainParts::Get()->browser_context(); + if (!certificate_manager_model_) { + CertificateManagerModel::Create(browser_context, base::Bind(&App::OnCertificateManagerModelCreated, base::Unretained(this), path, ca_path, password, callback)); + return; + } + + int rv = ImportCertificateIntoCertStore(certificate_manager_model_.get(), path, ca_path, password); + callback.Run(rv); +} + +void App::OnCertificateManagerModelCreated( + const base::FilePath& path, + const base::FilePath& ca_path, + const base::string16& password, + const net::CompletionCallback& callback, + scoped_ptr model) { + certificate_manager_model_ = std::move(model); + + int rv = ImportCertificateIntoCertStore(certificate_manager_model_.get(), path, ca_path, password); + callback.Run(rv); +} + mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( v8::Isolate* isolate) { auto browser = base::Unretained(Browser::Get()); @@ -408,7 +474,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( .SetMethod("allowNTLMCredentialsForAllDomains", &App::AllowNTLMCredentialsForAllDomains) .SetMethod("getLocale", &App::GetLocale) - .SetMethod("makeSingleInstance", &App::MakeSingleInstance); + .SetMethod("makeSingleInstance", &App::MakeSingleInstance) + .SetMethod("importClientCertificate", &App::ImportClientCertificate); } // static diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 5025a3869dd..b5c797df003 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -11,9 +11,11 @@ #include "atom/browser/atom_browser_client.h" #include "atom/browser/browser_observer.h" #include "atom/common/native_mate_converters/callback.h" +#include "chrome/browser/certificate_manager_model.h" #include "chrome/browser/process_singleton.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "native_mate/handle.h" +#include "net/base/completion_callback.h" namespace base { class FilePath; @@ -41,6 +43,13 @@ class App : public AtomBrowserClient::Delegate, int render_process_id, int render_frame_id); + void OnCertificateManagerModelCreated( + const base::FilePath& path, + const base::FilePath& ca_path, + const base::string16& password, + const net::CompletionCallback& callback, + scoped_ptr model); + protected: App(); virtual ~App(); @@ -97,12 +106,14 @@ class App : public AtomBrowserClient::Delegate, bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); std::string GetLocale(); + void ImportClientCertificate(const base::FilePath& path, const base::FilePath& ca_path, const base::string16& password, const net::CompletionCallback& callback); #if defined(OS_WIN) bool IsAeroGlassEnabled(); #endif scoped_ptr process_singleton_; + scoped_ptr certificate_manager_model_; DISALLOW_COPY_AND_ASSIGN(App); }; diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index 9a59c3f9d41..ddefd0688a2 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -55,26 +55,6 @@ std::string g_custom_schemes = ""; // Custom schemes to be registered to handle service worker. std::string g_custom_service_worker_schemes = ""; -scoped_refptr ImportCertFromFile( - const base::FilePath& path) { - if (path.empty()) - return nullptr; - - std::string cert_data; - if (!base::ReadFileToString(path, &cert_data)) - return nullptr; - - net::CertificateList certs = - net::X509Certificate::CreateCertificateListFromBytes( - cert_data.data(), cert_data.size(), - net::X509Certificate::FORMAT_AUTO); - - if (certs.empty()) - return nullptr; - - return certs[0]; -} - } // namespace // static @@ -242,16 +222,6 @@ void AtomBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, scoped_ptr delegate) { - // --client-certificate=`path` - auto cmd = base::CommandLine::ForCurrentProcess(); - if (cmd->HasSwitch(switches::kClientCertificate)) { - auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate); - auto certificate = ImportCertFromFile(cert_path); - if (certificate.get()) - delegate->ContinueWithCertificate(certificate.get()); - return; - } - if (!cert_request_info->client_certs.empty() && delegate_) { delegate_->SelectClientCertificate( web_contents, cert_request_info, std::move(delegate)); diff --git a/chromium_src/chrome/browser/certificate_manager_model.cc b/chromium_src/chrome/browser/certificate_manager_model.cc new file mode 100644 index 00000000000..83ab12af760 --- /dev/null +++ b/chromium_src/chrome/browser/certificate_manager_model.cc @@ -0,0 +1,177 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/certificate_manager_model.h" + +#include + +#include "base/bind.h" +#include "base/i18n/time_formatting.h" +#include "base/logging.h" +#include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/resource_context.h" +#include "crypto/nss_util.h" +#include "crypto/nss_util_internal.h" +#include "net/base/crypto_module.h" +#include "net/base/net_errors.h" +#include "net/cert/nss_cert_database.h" +#include "net/cert/x509_certificate.h" +#include "ui/base/l10n/l10n_util.h" + +using content::BrowserThread; + +namespace { + +net::NSSCertDatabase* g_nss_cert_database = nullptr; + +net::NSSCertDatabase* GetNSSCertDatabaseForResourceContext( + content::ResourceContext* context, + const base::Callback& callback) { + // This initialization is not thread safe. This CHECK ensures that this code + // is only run on a single thread. + CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); + if (!g_nss_cert_database) { + // Linux has only a single persistent slot compared to ChromeOS's separate + // public and private slot. + // Redirect any slot usage to this persistent slot on Linux. + g_nss_cert_database = new net::NSSCertDatabase( + crypto::ScopedPK11Slot( + crypto::GetPersistentNSSKeySlot()) /* public slot */, + crypto::ScopedPK11Slot( + crypto::GetPersistentNSSKeySlot()) /* private slot */); + } + return g_nss_cert_database; +} + +} // namespace + +// CertificateManagerModel is created on the UI thread. It needs a +// NSSCertDatabase handle (and on ChromeOS it needs to get the TPM status) which +// needs to be done on the IO thread. +// +// The initialization flow is roughly: +// +// UI thread IO Thread +// +// CertificateManagerModel::Create +// \--------------------------------------v +// CertificateManagerModel::GetCertDBOnIOThread +// | +// GetNSSCertDatabaseForResourceContext +// | +// CertificateManagerModel::DidGetCertDBOnIOThread +// | +// crypto::IsTPMTokenEnabledForNSS +// v--------------------------------------/ +// CertificateManagerModel::DidGetCertDBOnUIThread +// | +// new CertificateManagerModel +// | +// callback + +// static +void CertificateManagerModel::Create( + content::BrowserContext* browser_context, + const CreationCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind(&CertificateManagerModel::GetCertDBOnIOThread, + browser_context->GetResourceContext(), + callback)); +} + +CertificateManagerModel::CertificateManagerModel( + net::NSSCertDatabase* nss_cert_database, + bool is_user_db_available) + : cert_db_(nss_cert_database), + is_user_db_available_(is_user_db_available) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +CertificateManagerModel::~CertificateManagerModel() { +} + +int CertificateManagerModel::ImportFromPKCS12(net::CryptoModule* module, + const std::string& data, + const base::string16& password, + bool is_extractable) { + return cert_db_->ImportFromPKCS12(module, data, password, + is_extractable, NULL); +} + +int CertificateManagerModel::ImportUserCert(const std::string& data) { + return cert_db_->ImportUserCert(data); +} + +bool CertificateManagerModel::ImportCACerts( + const net::CertificateList& certificates, + net::NSSCertDatabase::TrustBits trust_bits, + net::NSSCertDatabase::ImportCertFailureList* not_imported) { + return cert_db_->ImportCACerts(certificates, trust_bits, not_imported); +} + +bool CertificateManagerModel::ImportServerCert( + const net::CertificateList& certificates, + net::NSSCertDatabase::TrustBits trust_bits, + net::NSSCertDatabase::ImportCertFailureList* not_imported) { + return cert_db_->ImportServerCert(certificates, trust_bits, + not_imported); +} + +bool CertificateManagerModel::SetCertTrust( + const net::X509Certificate* cert, + net::CertType type, + net::NSSCertDatabase::TrustBits trust_bits) { + return cert_db_->SetCertTrust(cert, type, trust_bits); +} + +bool CertificateManagerModel::Delete(net::X509Certificate* cert) { + return cert_db_->DeleteCertAndKey(cert); +} + +// static +void CertificateManagerModel::DidGetCertDBOnUIThread( + net::NSSCertDatabase* cert_db, + bool is_user_db_available, + const CreationCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + scoped_ptr model(new CertificateManagerModel( + cert_db, is_user_db_available)); + callback.Run(std::move(model)); +} + +// static +void CertificateManagerModel::DidGetCertDBOnIOThread( + const CreationCallback& callback, + net::NSSCertDatabase* cert_db) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + + bool is_user_db_available = !!cert_db->GetPublicSlot(); + BrowserThread::PostTask( + BrowserThread::UI, + FROM_HERE, + base::Bind(&CertificateManagerModel::DidGetCertDBOnUIThread, + cert_db, + is_user_db_available, + callback)); +} + +// static +void CertificateManagerModel::GetCertDBOnIOThread( + content::ResourceContext* context, + const CreationCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + net::NSSCertDatabase* cert_db = GetNSSCertDatabaseForResourceContext( + context, + base::Bind(&CertificateManagerModel::DidGetCertDBOnIOThread, + callback)); + if (cert_db) + DidGetCertDBOnIOThread(callback, cert_db); +} diff --git a/chromium_src/chrome/browser/certificate_manager_model.h b/chromium_src/chrome/browser/certificate_manager_model.h new file mode 100644 index 00000000000..bd0d5ddfb29 --- /dev/null +++ b/chromium_src/chrome/browser/certificate_manager_model.h @@ -0,0 +1,116 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CERTIFICATE_MANAGER_MODEL_H_ +#define CHROME_BROWSER_CERTIFICATE_MANAGER_MODEL_H_ + +#include +#include + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/strings/string16.h" +#include "net/cert/nss_cert_database.h" + +namespace content { +class BrowserContext; +class ResourceContext; +} // namespace content + +// CertificateManagerModel provides the data to be displayed in the certificate +// manager dialog, and processes changes from the view. +class CertificateManagerModel { + public: + typedef base::Callback)> + CreationCallback; + + // Creates a CertificateManagerModel. The model will be passed to the callback + // when it is ready. The caller must ensure the model does not outlive the + // |browser_context|. + static void Create(content::BrowserContext* browser_context, + const CreationCallback& callback); + + ~CertificateManagerModel(); + + bool is_user_db_available() const { return is_user_db_available_; } + + // Accessor for read-only access to the underlying NSSCertDatabase. + const net::NSSCertDatabase* cert_db() const { return cert_db_; } + + // Import private keys and certificates from PKCS #12 encoded + // |data|, using the given |password|. If |is_extractable| is false, + // mark the private key as unextractable from the module. + // Returns a net error code on failure. + int ImportFromPKCS12(net::CryptoModule* module, const std::string& data, + const base::string16& password, bool is_extractable); + + // Import user certificate from DER encoded |data|. + // Returns a net error code on failure. + int ImportUserCert(const std::string& data); + + // Import CA certificates. + // Tries to import all the certificates given. The root will be trusted + // according to |trust_bits|. Any certificates that could not be imported + // will be listed in |not_imported|. + // |trust_bits| should be a bit field of TRUST* values from NSSCertDatabase. + // Returns false if there is an internal error, otherwise true is returned and + // |not_imported| should be checked for any certificates that were not + // imported. + bool ImportCACerts(const net::CertificateList& certificates, + net::NSSCertDatabase::TrustBits trust_bits, + net::NSSCertDatabase::ImportCertFailureList* not_imported); + + // Import server certificate. The first cert should be the server cert. Any + // additional certs should be intermediate/CA certs and will be imported but + // not given any trust. + // Any certificates that could not be imported will be listed in + // |not_imported|. + // |trust_bits| can be set to explicitly trust or distrust the certificate, or + // use TRUST_DEFAULT to inherit trust as normal. + // Returns false if there is an internal error, otherwise true is returned and + // |not_imported| should be checked for any certificates that were not + // imported. + bool ImportServerCert( + const net::CertificateList& certificates, + net::NSSCertDatabase::TrustBits trust_bits, + net::NSSCertDatabase::ImportCertFailureList* not_imported); + + // Set trust values for certificate. + // |trust_bits| should be a bit field of TRUST* values from NSSCertDatabase. + // Returns true on success or false on failure. + bool SetCertTrust(const net::X509Certificate* cert, + net::CertType type, + net::NSSCertDatabase::TrustBits trust_bits); + + // Delete the cert. Returns true on success. |cert| is still valid when this + // function returns. + bool Delete(net::X509Certificate* cert); + + private: + CertificateManagerModel(net::NSSCertDatabase* nss_cert_database, + bool is_user_db_available); + + // Methods used during initialization, see the comment at the top of the .cc + // file for details. + static void DidGetCertDBOnUIThread( + net::NSSCertDatabase* cert_db, + bool is_user_db_available, + const CreationCallback& callback); + static void DidGetCertDBOnIOThread( + const CreationCallback& callback, + net::NSSCertDatabase* cert_db); + static void GetCertDBOnIOThread(content::ResourceContext* context, + const CreationCallback& callback); + + net::NSSCertDatabase* cert_db_; + // Whether the certificate database has a public slot associated with the + // profile. If not set, importing certificates is not allowed with this model. + bool is_user_db_available_; + + DISALLOW_COPY_AND_ASSIGN(CertificateManagerModel); +}; + +#endif // CHROME_BROWSER_CERTIFICATE_MANAGER_MODEL_H_ diff --git a/filenames.gypi b/filenames.gypi index dd9edb409f5..4de1b366b4f 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -390,6 +390,8 @@ 'atom/utility/atom_content_utility_client.h', 'chromium_src/chrome/browser/browser_process.cc', 'chromium_src/chrome/browser/browser_process.h', + 'chromium_src/chrome/browser/certificate_manager_model.cc', + 'chromium_src/chrome/browser/certificate_manager_model.h', 'chromium_src/chrome/browser/chrome_process_finder_win.cc', 'chromium_src/chrome/browser/chrome_process_finder_win.h', 'chromium_src/chrome/browser/chrome_notification_types.h', From 34319abf4a87ed9979bf1de0d868ca1b76a3c257 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 18 Apr 2016 14:52:03 +0900 Subject: [PATCH 0514/1265] Initialize the embedder_ member data Otherwise it is going to be some random value and bite us. --- atom/browser/api/atom_api_web_contents.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index abad4add4fb..64a76d57e65 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -217,6 +217,7 @@ content::ServiceWorkerContext* GetServiceWorkerContext( WebContents::WebContents(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), + embedder_(nullptr), type_(REMOTE), request_id_(0), background_throttling_(true) { From 12483486c06ef72a0286f0088b49b80112a805a0 Mon Sep 17 00:00:00 2001 From: Andrew Dassonville Date: Sun, 17 Apr 2016 23:04:02 -0700 Subject: [PATCH 0515/1265] Update link to setFeatureEnabledFromString --- docs/api/browser-window.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 877a6d0f745..b1b6cf130f7 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -912,4 +912,4 @@ Returns whether the window is visible on all workspaces. Ignore all moused events that happened in the window. -[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=576 From b8e04f4947698cb2694317f2cd8227580fff2040 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 11:35:24 +0530 Subject: [PATCH 0516/1265] set client id on AtomNetworkDelegate instead of cmd line switch --- atom/browser/api/atom_api_session.cc | 14 ++++---------- atom/browser/net/atom_network_delegate.cc | 18 ++++++++++-------- atom/browser/net/atom_network_delegate.h | 6 ++++++ atom/common/options_switches.cc | 4 ---- atom/common/options_switches.h | 2 -- 5 files changed, 20 insertions(+), 24 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index c6ef6619034..222591e92e9 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -22,8 +22,6 @@ #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/node_includes.h" -#include "atom/common/options_switches.h" -#include "base/command_line.h" #include "base/files/file_path.h" #include "base/guid.h" #include "base/prefs/pref_service.h" @@ -288,12 +286,6 @@ void ClearHostResolverCacheInIO( } } -void SetDevToolsNetworkEmulationClientId(const std::string& id) { - auto cmd_line = base::CommandLine::ForCurrentProcess(); - cmd_line->AppendSwitchASCII( - switches::kDevToolsEmulateNetworkConditionsClientId, id); -} - } // namespace Session::Session(AtomBrowserContext* browser_context) @@ -394,14 +386,16 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) { browser_context_->network_controller_handle()->SetNetworkState( devtools_network_emulation_client_id_, std::move(conditions)); - SetDevToolsNetworkEmulationClientId(devtools_network_emulation_client_id_); + browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId( + devtools_network_emulation_client_id_); } void Session::DisableNetworkEmulation() { scoped_ptr conditions; browser_context_->network_controller_handle()->SetNetworkState( devtools_network_emulation_client_id_, std::move(conditions)); - SetDevToolsNetworkEmulationClientId(std::string()); + browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId( + std::string()); } void Session::SetCertVerifyProc(v8::Local val, diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index cb602c4b362..6ef5ac22807 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -4,17 +4,16 @@ #include "atom/browser/net/atom_network_delegate.h" -#include #include #include "atom/common/native_mate_converters/net_converter.h" -#include "atom/common/options_switches.h" -#include "base/command_line.h" #include "base/stl_util.h" #include "base/strings/string_util.h" +#include "brightray/browser/net/devtools_network_transaction.h" #include "content/public/browser/browser_thread.h" #include "net/url_request/url_request.h" +using brightray::DevToolsNetworkTransaction; using content::BrowserThread; namespace atom { @@ -228,6 +227,11 @@ void AtomNetworkDelegate::SetResponseListenerInIO( response_listeners_[type] = { patterns, callback }; } +void AtomNetworkDelegate::SetDevToolsNetworkEmulationClientId( + const std::string& client_id) { + client_id_ = client_id; +} + int AtomNetworkDelegate::OnBeforeURLRequest( net::URLRequest* request, const net::CompletionCallback& callback, @@ -243,12 +247,10 @@ int AtomNetworkDelegate::OnBeforeSendHeaders( net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers) { - auto cmd_line = base::CommandLine::ForCurrentProcess(); - auto client_id = cmd_line->GetSwitchValueASCII( - switches::kDevToolsEmulateNetworkConditionsClientId); - if (!client_id.empty()) + if (!client_id_.empty()) headers->SetHeader( - switches::kDevToolsEmulateNetworkConditionsClientId, client_id); + DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId, + client_id_); if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders)) return brightray::NetworkDelegate::OnBeforeSendHeaders( request, callback, headers); diff --git a/atom/browser/net/atom_network_delegate.h b/atom/browser/net/atom_network_delegate.h index ee159df60f1..e0b41eb4589 100644 --- a/atom/browser/net/atom_network_delegate.h +++ b/atom/browser/net/atom_network_delegate.h @@ -7,6 +7,7 @@ #include #include +#include #include "brightray/browser/network_delegate.h" #include "base/callback.h" @@ -68,6 +69,8 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate { const URLPatterns& patterns, const ResponseListener& callback); + void SetDevToolsNetworkEmulationClientId(const std::string& client_id); + protected: // net::NetworkDelegate: int OnBeforeURLRequest(net::URLRequest* request, @@ -116,6 +119,9 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate { std::map response_listeners_; std::map callbacks_; + // Client id for devtools network emulation. + std::string client_id_; + DISALLOW_COPY_AND_ASSIGN(AtomNetworkDelegate); }; diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index b4c5c4ef831..ce28cc98fac 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -156,10 +156,6 @@ const char kWidevineCdmPath[] = "widevine-cdm-path"; // Widevine CDM version. const char kWidevineCdmVersion[] = "widevine-cdm-version"; -// Client id for devtools network emulation. -const char kDevToolsEmulateNetworkConditionsClientId[] = - "X-DevTools-Emulate-Network-Conditions-Client-Id"; - } // namespace switches } // namespace atom diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index e05be3b4359..52d64c00d51 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -87,8 +87,6 @@ extern const char kOpenerID[]; extern const char kWidevineCdmPath[]; extern const char kWidevineCdmVersion[]; -extern const char kDevToolsEmulateNetworkConditionsClientId[]; - } // namespace switches } // namespace atom From 142300aeb9a6939591093bf489b845e6425df1b9 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Mon, 18 Apr 2016 22:38:15 +0800 Subject: [PATCH 0517/1265] Create frameless-window.md Translate `frameless-window.md` to Chinese. And I'm not sure that the `non-client frame`'s translation is accurate. --- .../zh-CN/api/frameless-window.md | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 docs-translations/zh-CN/api/frameless-window.md diff --git a/docs-translations/zh-CN/api/frameless-window.md b/docs-translations/zh-CN/api/frameless-window.md new file mode 100644 index 00000000000..1916c6a929b --- /dev/null +++ b/docs-translations/zh-CN/api/frameless-window.md @@ -0,0 +1,87 @@ +# 无边框窗口 + +无边框窗口指的是不包含除页面本身以外任何其它可视部分的窗口([chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome))。 +像工具栏,是窗口的一部分,但并不属于页面。这些是[`BrowserWindow`](browser-window.md) 类的选项。 + +## 创建无边框窗口 + +为了创建一个无边框窗口,你需要设置[BrowserWindow](browser-window.md)的`frame`为`false`: + + + +```javascript +const BrowserWindow = require('electron').BrowserWindow; +var win = new BrowserWindow({ width: 800, height: 600, frame: false }); +``` + +### OS X上的替代方案 + +在Mac OS X 10.10 Yosemite或者更新的版本中,有一个替代方案去生成一个无边框窗口。 +不同于设置`frame`为`false`会隐藏标题栏以及失去对窗口的控制,你可能想隐藏标题栏使你的页面内容显示在整个窗口上 +,同时又想保持对窗口的控制("traffic lights")。你可以通过指定`titleBarStyle`这一新选项达到目标: + +```javascript +var win = new BrowserWindow({ 'titleBarStyle': 'hidden' }); +``` + +## 透明窗口 + +通过设置`transparent` 选项为 `true`,你能使无边框窗口透明: + +```javascript +var win = new BrowserWindow({ transparent: true, frame: false }); +``` + +### 限制 + +* 你无法点击透明的区域。我们正在采用一个新的API去设置窗口的外形以解决这个问题, + 详见[our issue](https://github.com/electron/electron/issues/1335)。 +* 透明窗口是不可调整大小的。在某些平台上,设置`resizable`为`true`也许会造成这个透明窗口停止工作。 +* `blur`滤光器器只适用于网页,所以没法将模糊效果用于窗口之下(i.e. 其它在用户的系统中打开的应用)。 +* 在Windows系统中,当DWM被禁用时透明窗口不会工作。 +* Linux用户需要在命令行中输入`--enable-transparent-visuals --disable-gpu` + 去禁用GPU以及允许ARGB去渲染透明窗口,这是由于一个Linux上的上游bug[alpha channel doesn't work on some + NVidia drivers](https://code.google.com/p/chromium/issues/detail?id=369209)造成的 +* 在Mac上,透明窗口的阴影不会显示出来. + +## 可拖动区域 + +默认情况下,无边框窗口是不可拖动的。应用在CSS中设置`-webkit-app-region: drag` +告诉Electron哪个区域是可拖动的(比如系统标准的标题栏),应用也可以设置`-webkit-app-region: no-drag` +在可拖动区域中排除不可拖动的区域。需要注意的是,目前只支持矩形区域。 + +为了让整个窗口可拖动,你可以在`body`的样式中添加`-webkit-app-region: drag`: + +```html + + +``` + +另外需要注意的是,如果你设置了整个窗口可拖动,你必须标记按钮为不可拖动的(non-draggable), +否则用户不能点击它们: + +```css +button { + -webkit-app-region: no-drag; +} +``` + +如果你设置一个自定义的标题栏可拖动,你同样需要设置标题栏中所有的按钮为不可拖动(non-draggable)。 + +## 文本选择 + +在一个无边框窗口中,拖动动作会与文本选择发生冲突。比如,当你拖动标题栏,偶尔会选中标题栏上的文本。 +为了防止这种情况发生,你需要向下面这样在一个可拖动区域中禁用文本选择: + +```css +.titlebar { + -webkit-user-select: none; + -webkit-app-region: drag; +} +``` + +## 上下文菜单 + +在一些平台上,可拖动区域会被认为是非客户端框架(non-client frame),所有当你点击右键时,一个系统菜单会弹出。 +为了保证上下文菜单在所有平台下正确的显示,你不应该在可拖动区域使用自定义上下文菜单。 + From 1240c83e40c925d643af7f20f6cc137a092f7ddb Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 21:05:33 +0530 Subject: [PATCH 0518/1265] set trust bits for CA certs --- atom/browser/api/atom_api_app.cc | 89 +++++++++---------- atom/browser/api/atom_api_app.h | 7 +- atom/browser/atom_browser_client.cc | 1 - .../browser/certificate_manager_model.cc | 12 +-- .../browser/certificate_manager_model.h | 7 +- 5 files changed, 55 insertions(+), 61 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 4cbae0885e9..1446d44ad00 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -15,10 +15,11 @@ #include "atom/browser/browser.h" #include "atom/browser/login_handler.h" #include "atom/common/native_mate_converters/callback.h" -#include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/image_converter.h" +#include "atom/common/native_mate_converters/net_converter.h" +#include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/node_includes.h" #include "atom/common/options_switches.h" #include "base/command_line.h" @@ -158,41 +159,35 @@ void PassLoginInformation(scoped_refptr login_handler, login_handler->CancelAuth(); } -net::CertificateList ImportCertsFromFile( - const base::FilePath& path) { - net::CertificateList certs; - if (path.empty()) - return certs; - - std::string cert_data; - if (!base::ReadFileToString(path, &cert_data)) - return certs; - - certs = net::X509Certificate::CreateCertificateListFromBytes( - cert_data.data(), cert_data.size(), - net::X509Certificate::FORMAT_AUTO); - - return certs; -} - -int ImportCertificateIntoCertStore( +int ImportIntoCertStore( CertificateManagerModel* model, - const base::FilePath& path, - const base::FilePath& ca_path, - const base::string16& password) { - LOG(WARNING) << "importing ...."; + const base::DictionaryValue& options) { + std::string file_data, cert_path; + base::string16 password; + net::CertificateList imported_certs; + int rv; + options.GetString("clientCertificate", &cert_path); + options.GetString("password", &password); - std::string file_data; - int result = -1; - net::CertificateList ca_certs; - net::NSSCertDatabase::ImportCertFailureList not_imported; - auto module = model->cert_db()->GetPublicModule(); - if (base::ReadFileToString(path, &file_data)) { - result &= model->ImportFromPKCS12(module, file_data, password, true); - ca_certs = ImportCertsFromFile(ca_path); - result &= model->ImportCACerts(ca_certs, net::NSSCertDatabase::TRUST_DEFAULT, ¬_imported); + if (!cert_path.empty()) { + if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) { + auto module = model->cert_db()->GetPublicModule(); + rv = model->ImportFromPKCS12(module, + file_data, + password, + true, + &imported_certs); + if (imported_certs.size() > 1) { + auto it = imported_certs.begin(); + ++it; // skip first which would be the client certificate. + for (; it != imported_certs.end(); ++it) + rv &= model->SetCertTrust(it->get(), + net::CA_CERT, + net::NSSCertDatabase::TRUSTED_SSL); + } + } } - return result; + return rv; } } // namespace @@ -408,30 +403,30 @@ bool App::MakeSingleInstance( } void App::ImportClientCertificate( - const base::FilePath& path, - const base::FilePath& ca_path, - - const base::string16& password, + const base::DictionaryValue& options, const net::CompletionCallback& callback) { auto browser_context = AtomBrowserMainParts::Get()->browser_context(); if (!certificate_manager_model_) { - CertificateManagerModel::Create(browser_context, base::Bind(&App::OnCertificateManagerModelCreated, base::Unretained(this), path, ca_path, password, callback)); + scoped_ptr copy = options.CreateDeepCopy(); + CertificateManagerModel::Create(browser_context, + base::Bind(&App::OnCertificateManagerModelCreated, + base::Unretained(this), + base::Passed(©), + callback)); return; } - int rv = ImportCertificateIntoCertStore(certificate_manager_model_.get(), path, ca_path, password); + int rv = ImportIntoCertStore(certificate_manager_model_.get(), options); callback.Run(rv); } void App::OnCertificateManagerModelCreated( - const base::FilePath& path, - const base::FilePath& ca_path, - const base::string16& password, + scoped_ptr options, const net::CompletionCallback& callback, scoped_ptr model) { certificate_manager_model_ = std::move(model); - - int rv = ImportCertificateIntoCertStore(certificate_manager_model_.get(), path, ca_path, password); + int rv = ImportIntoCertStore(certificate_manager_model_.get(), + *(options.get())); callback.Run(rv); } @@ -474,8 +469,10 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( .SetMethod("allowNTLMCredentialsForAllDomains", &App::AllowNTLMCredentialsForAllDomains) .SetMethod("getLocale", &App::GetLocale) - .SetMethod("makeSingleInstance", &App::MakeSingleInstance) - .SetMethod("importClientCertificate", &App::ImportClientCertificate); +#if defined(OS_LINUX) + .SetMethod("importClientCertificate", &App::ImportClientCertificate) +#endif + .SetMethod("makeSingleInstance", &App::MakeSingleInstance); } // static diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index b5c797df003..ce66daedf10 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -44,9 +44,7 @@ class App : public AtomBrowserClient::Delegate, int render_frame_id); void OnCertificateManagerModelCreated( - const base::FilePath& path, - const base::FilePath& ca_path, - const base::string16& password, + scoped_ptr options, const net::CompletionCallback& callback, scoped_ptr model); @@ -106,7 +104,8 @@ class App : public AtomBrowserClient::Delegate, bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); std::string GetLocale(); - void ImportClientCertificate(const base::FilePath& path, const base::FilePath& ca_path, const base::string16& password, const net::CompletionCallback& callback); + void ImportClientCertificate(const base::DictionaryValue& options, + const net::CompletionCallback& callback); #if defined(OS_WIN) bool IsAeroGlassEnabled(); diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index ddefd0688a2..f4add58e3a8 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -37,7 +37,6 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" -#include "net/cert/x509_certificate.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" diff --git a/chromium_src/chrome/browser/certificate_manager_model.cc b/chromium_src/chrome/browser/certificate_manager_model.cc index 83ab12af760..b0db6edc357 100644 --- a/chromium_src/chrome/browser/certificate_manager_model.cc +++ b/chromium_src/chrome/browser/certificate_manager_model.cc @@ -7,10 +7,8 @@ #include #include "base/bind.h" -#include "base/i18n/time_formatting.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" -#include "build/build_config.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_context.h" @@ -20,7 +18,6 @@ #include "net/base/net_errors.h" #include "net/cert/nss_cert_database.h" #include "net/cert/x509_certificate.h" -#include "ui/base/l10n/l10n_util.h" using content::BrowserThread; @@ -64,8 +61,6 @@ net::NSSCertDatabase* GetNSSCertDatabaseForResourceContext( // GetNSSCertDatabaseForResourceContext // | // CertificateManagerModel::DidGetCertDBOnIOThread -// | -// crypto::IsTPMTokenEnabledForNSS // v--------------------------------------/ // CertificateManagerModel::DidGetCertDBOnUIThread // | @@ -100,9 +95,10 @@ CertificateManagerModel::~CertificateManagerModel() { int CertificateManagerModel::ImportFromPKCS12(net::CryptoModule* module, const std::string& data, const base::string16& password, - bool is_extractable) { + bool is_extractable, + net::CertificateList* imported_certs) { return cert_db_->ImportFromPKCS12(module, data, password, - is_extractable, NULL); + is_extractable, imported_certs); } int CertificateManagerModel::ImportUserCert(const std::string& data) { @@ -121,7 +117,7 @@ bool CertificateManagerModel::ImportServerCert( net::NSSCertDatabase::TrustBits trust_bits, net::NSSCertDatabase::ImportCertFailureList* not_imported) { return cert_db_->ImportServerCert(certificates, trust_bits, - not_imported); + not_imported); } bool CertificateManagerModel::SetCertTrust( diff --git a/chromium_src/chrome/browser/certificate_manager_model.h b/chromium_src/chrome/browser/certificate_manager_model.h index bd0d5ddfb29..1eb35087680 100644 --- a/chromium_src/chrome/browser/certificate_manager_model.h +++ b/chromium_src/chrome/browser/certificate_manager_model.h @@ -44,8 +44,11 @@ class CertificateManagerModel { // |data|, using the given |password|. If |is_extractable| is false, // mark the private key as unextractable from the module. // Returns a net error code on failure. - int ImportFromPKCS12(net::CryptoModule* module, const std::string& data, - const base::string16& password, bool is_extractable); + int ImportFromPKCS12(net::CryptoModule* module, + const std::string& data, + const base::string16& password, + bool is_extractable, + net::CertificateList* imported_certs); // Import user certificate from DER encoded |data|. // Returns a net error code on failure. From 5a9b86dd051c761473e192a1ab8ee681da28c79a Mon Sep 17 00:00:00 2001 From: Ray Booysen Date: Mon, 18 Apr 2016 17:04:47 +0100 Subject: [PATCH 0519/1265] Update screen.md --- docs/api/screen.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/screen.md b/docs/api/screen.md index 61210c9e119..4d12f1359f7 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -1,8 +1,8 @@ # screen The `screen` module retrieves information about screen size, displays, cursor -position, etc. You should not use this module until the `ready` event of the -`app` module is emitted. +position, etc. You cannot not use this module until the `ready` event of the +`app` module is emitted (by invoking or requiring it). `screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). From 2ddac9352f48aa6ae386f8b1d001fe4b6c2ff2fd Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 21:53:44 +0530 Subject: [PATCH 0520/1265] add spec --- spec/api-app-spec.js | 61 +++++++++ spec/fixtures/certificates/certs.cnf | 68 ++++++++++ spec/fixtures/certificates/client.p12 | Bin 0 -> 4149 bytes spec/fixtures/certificates/generate_certs.sh | 127 ++++++++++++++++++ spec/fixtures/certificates/intermediateCA.pem | 78 +++++++++++ spec/fixtures/certificates/rootCA.pem | 19 +++ spec/fixtures/certificates/server.key | 27 ++++ spec/fixtures/certificates/server.pem | 88 ++++++++++++ 8 files changed, 468 insertions(+) create mode 100644 spec/fixtures/certificates/certs.cnf create mode 100644 spec/fixtures/certificates/client.p12 create mode 100755 spec/fixtures/certificates/generate_certs.sh create mode 100644 spec/fixtures/certificates/intermediateCA.pem create mode 100644 spec/fixtures/certificates/rootCA.pem create mode 100644 spec/fixtures/certificates/server.key create mode 100644 spec/fixtures/certificates/server.pem diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index c237ef17238..1f5452713bc 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -1,5 +1,7 @@ const assert = require('assert') const ChildProcess = require('child_process') +const https = require('https') +const fs = require('fs') const path = require('path') const remote = require('electron').remote @@ -87,6 +89,65 @@ describe('app module', function () { }) }) + describe('app.importClientCertificate', function () { + if (process.platform !== 'linux') + return + + this.timeout(5000) + + var port + var w = null + var certPath = path.join(__dirname, 'fixtures', 'certificates') + var options = { + key: fs.readFileSync(path.join(certPath, 'server.key')), + cert: fs.readFileSync(path.join(certPath, 'server.pem')), + ca: [ + fs.readFileSync(path.join(certPath, 'rootCA.pem')), + fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) + ], + requestCert: true, + rejectUnauthorized: false + } + + var server = https.createServer(options, function (req, res) { + if (req.client.authorized) { + res.writeHead(200); + res.end('authorized'); + } + }) + server.listen(0, '127.0.0.1', function () { + port = server.address().port + }) + + afterEach(function () { + if (w != null) { + w.destroy() + } + w = null + }) + + it('can import certificate into platform cert store', function (done) { + let options = { + clientCertificate: path.join(certPath, 'client.p12'), + password: 'electron' + } + + w = new BrowserWindow({ + show: false + }) + + w.webContents.on('did-finish-load', function () { + server.close() + done() + }) + + app.importClientCertificate(options, function (result) { + assert(!result) + w.loadURL(`https://127.0.0.1:${port}`) + }) + }) + }) + describe('BrowserWindow events', function () { var w = null diff --git a/spec/fixtures/certificates/certs.cnf b/spec/fixtures/certificates/certs.cnf new file mode 100644 index 00000000000..d8b5c66e13a --- /dev/null +++ b/spec/fixtures/certificates/certs.cnf @@ -0,0 +1,68 @@ +ID=1 +CA_DIR=out + +[ca] +default_ca = ca_settings + +[ca_settings] +dir = ${ENV::CA_DIR} +database = $dir/${ENV::ID}-index.txt +new_certs_dir = $dir +serial = $dir/${ENV::ID}-serial +certificate = $dir/${ENV::ID}.pem +private_key = $dir/${ENV::ID}.key +RANDFILE = $dir/rand +default_md = sha256 +default_days = 3650 +policy = policy_anything +preserve = no + +[policy_anything] +# Default signing policy +countryName = optional +stateOrProvinceName = optional +localityName = optional +organizationName = optional +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +[req] +default_bits = 2048 +default_md = sha256 +string_mask = utf8only +distinguished_name = req_env_dn +prompt = no + +[user_cert] +basicConstraints = CA:FALSE +nsCertType = client +nsComment = "OpenSSL Generated Client Certificate" +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer +keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment +extendedKeyUsage = clientAuth, emailProtection + +[server_cert] +basicConstraints = CA:FALSE +nsCertType = server +nsComment = "OpenSSL Generated Server Certificate" +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid,issuer:always +keyUsage = critical, digitalSignature, keyEncipherment +extendedKeyUsage = serverAuth + +[ca_cert] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical, CA:true +keyUsage = critical, digitalSignature, cRLSign, keyCertSign + +[ca_intermediate_cert] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical, CA:true, pathlen:0 +keyUsage = critical, digitalSignature, cRLSign, keyCertSign + +[req_env_dn] +commonName = ${ENV::COMMON_NAME} diff --git a/spec/fixtures/certificates/client.p12 b/spec/fixtures/certificates/client.p12 new file mode 100644 index 0000000000000000000000000000000000000000..7543c7d38904f15708eae001c285f1ab6be1e6e1 GIT binary patch literal 4149 zcmV-55X$c`f)FtR0Ru3C5BCNMDuzgg_YDCD0ic2p=mdffE{;4p#;mj($chDe6@ z4FLxRpn?jBFoFt%0s#Opf(m^G2`Yw2hW8Bt2LUh~1_~;MNQUF3F= zrMuDyw~)Pkq#adbSV(Y%UB63E+6)h}f>+2?;YYypermyCaxN<2p&&1cl7kL+XSsN< z+e6Ls9-OsIq1WTd*QkEiWo?SXhH>Em>lchy(B7e*fujcM8dCH#8LZ{t9n)&!g+)wk z?}NBil+rq<$zgZL7S`@RY1?XZ8C_>ERVa0D;|2u!N}pQs3m2r^E4~Lx2-kcb?Axh| zC;+s!kzZ~53{w54{3IAuOK2yn(FwSOB$qU}X8CkSBOj4X1k8E0gzXI>hD2y45T^@`sA472*6o%ZEea212_5>qYA_6ho%C# z7aTh~b&UXJroNwL-%5&YkPa5e%GTSw5GYHL-OAL$*XB@9ciJHKpqVRoth|ZvI^OAk&P2=D8Dl72|)3|y@gD>kJ;vk2sOe-7zR=zg zt056nJ#HEV?6&}iE^s{rgzBg2Q<}JXr;*KVg;-KjEDda~==?G^(|w5CqXJ`9VbV7v zaYPVc@fC>Ei|vxAN(3oAo!+IrQ;+2rNVonPDd=>t_0!n#Bolh`uA_x8hhgPaZgDtfIfpgE3 zD3MF#m1*04>{BvMHp1$AQB|<{DnnIQE6hX7u5~tR6Ro#lzVXa3RCezu>-5z==awi% z3OgbvC2BU?*l8-Ca3voL;0y?JEzSkLSmVfJ3xn$(!J)x(>+1iEfTQv5w+)VvU@;zt zuzp~|FEaJ!v>etO;jfKUH!4o(63t^}GrcAv$HY}Wq#(C$Saqk5u= zSOs0A*_u_qSmnjEYA+$l;OIlk@`ofo{KUf#)y>bCM`(Jvh0CpjZvck@x|qfF7ZeWI zC(G2wert-(Ix>8?`XS2oYJyDXiK|YHH;U=w98a{C0S#R11cYRPle^+z=1Df&V6!aU z9%2VdDhy`n+gk%K*V#tTA#lZ~8b1i#V} zIbWHdm&YPMs(PIAyUN}USC^SoUzVXwPz#CrUzc56B!X(m-MzPi-lqA}n%$-Ow;?lO zHsZ5M-lNjpQfTC7qT+mqM4O(rCbTTSIX_6D2-L9tEOD_3;^vI)Vg=1hP|qJS3#H=3ZobI=kBB$u@m+t+;}{B3}s8?SvHs9*CsbO#*~u6vO^hTs0u zYtB8#r2PTRl-PS|@MyJvzJN1nM4eW@kk2awF7%QExl>A23CN+I z#E`3|1*hbizIPds&K@|Wep(X^420H@kijXtuI*6=#kjrFj$T^cfu66H+xC4-O622G#dguYNyN;biZ;*)&&H%P^!m#T59hD~-=!+c zxZOxy#sLY5PnTHdPh+%c8)Hx&ck80v&J@Q1BwZ-bzt_DF=)S_0VLAy$-J1i1*1!aJ zI`B&5wDs*sKgRIAeB#?!XdOqW3@PuP0esQ> zX9&wYN~}98A1%=AY?l!09Xkj|Hrxv;*VP6)ITD+Afpjjy=K~sxfsZTSyFYR~txkG! zh|e3%0=?Fs>k*Ou!4~RuE+T@|4&l?gh)m`{T6c=Mj8G_95@D;QN;7|OlxRC))#+pH z2o*2KSl;B{oSZ;A+#JJP#%=f0Mv#YB=&uA3r4)Yi_MUBnC%QSrZe4n0K;k(gv}o6> zpk>3qg7{VpA3ZwKHUXR74pY{kT+MO(+xAPEATo&LNQUKp6Pi^FD$P3Fi?OyZYbezlXv^f$?3z{m3aiG#2rl8ouugO* zQYs5CT~wtC3Ot2W%thvfckvV}$+4p$EOb08US5h1 zz3yqKHxK-m56o&ZAb?UE5Rt+YEFuSOnCTe&AevZ7pnCcjs3b=kiu`=tnBuBhh!N`9 z9R(J9h471>P_paPON$I>5loSmmM85b(*WOLDiwE)DA?(GC`R}!I&rf0Yc)DTBPxKC z=uqK19;q^VPqGOmdFOc#8>kvkWwE^9FXH3x@7w=2 z6DDu>eAM|Z%Sf|g6Y-f&)m3_WQ^dJjPe7po&D8{@1M(GFI-1;THI@MMecA(WfRf3f zLGW_?-8qsa5;1gkL9~q?3UKuYk+9{Ok!+l~5Rzp1o`Sgd>IY_d^@g8vS%)+q z0*URWNp2tE<^R_)%#V)ycU#*KCKUq^dR!?wSH7`^x4YK!a~^D`5$!swtI4=mjfcNq zv=?Fz80Zr7pXZ@>C{x3Wv@NNU{4L5WBL$LkG3^EN)#z0 z=4>sCn5!SBJ+|SfV&@T|9E3C4bJyTaGMdDOa_x9MI>2(@-xynmt8U#8_pYw?M&9aN zU6FUL$hhlMbmC1X91%l0dGapPmtsXtVr_yamKbb7*w*3BpL|nk@mX-4-;S#;%Lnv= zPsNabwpH`wRm_XGsF=I$WR2`YUDmB28j`ffR|kh`<4~fM+{qd{w?w8v#cz6Q$Erhx z!JLOo!`XkWKH|~YGVN%6bqQ+aB|kcpJ`J-csOTxYl!mGht3DIGO~_f|W@m`Tmr#6RI<4Bw4~jT|l++n;ecj`%>P%6n_{8wU(vT^9~kE zHwpcuLy1S%X0@2W-ou5*Ed8oXUNVPdD3%;^p1Q{K0<=Ctcmze&+_9(O2J5(otJp?C z*|c`bW^7+i;qQ!(joO9W++koYlK``1rz@DgU)crV#M-Sq7vnXG^qger%!&2LG3I!lhBm&3@t6*}QAA zKfRYWMvfRx=Wai4>hLm7^li2$9th`-zBy*pUBNeoV|A6;TU-a%FQblv`u};DsTQ^+ zFq5B5Yz}S0i@m$~19<2hlw>kk<4X4bb| zcJUWZRB3q);`E^S(#0h%S;0&YH zivvjX{?rw0OCm8PFe3&DDuzgg_YDCF6)_eB6p+0r>6Y%e B -> C (self-signed root) +# 2. D (end-entity) -> B -> C (self-signed root) + +try () { + echo "$@" + "$@" || exit 1 +} + +try mkdir out + +echo Create the serial number files and indices. +serial=1000 +for i in B C +do + try /bin/sh -c "echo $serial > out/$i-serial" + serial=$(expr $serial + 1) + touch out/$i-index.txt + touch out/$i-index.txt.attr +done + +echo Generate the keys. +for i in A B C D +do + try openssl genrsa -out out/$i.key 2048 +done + +echo Generate the C CSR +COMMON_NAME="Root CA" \ + CA_DIR=out \ + ID=C \ + try openssl req \ + -new \ + -key out/C.key \ + -out out/C.csr \ + -config certs.cnf + +echo C signs itself. +COMMON_NAME="Root CA" \ + CA_DIR=out \ + ID=C \ + try openssl x509 \ + -req -days 3650 \ + -in out/C.csr \ + -extensions ca_cert \ + -extfile certs.cnf \ + -signkey out/C.key \ + -out out/C.pem + +echo Generate the intermediates +COMMON_NAME="Intermediate CA" \ + CA_DIR=out \ + ID=B \ + try openssl req \ + -new \ + -key out/B.key \ + -out out/B.csr \ + -config certs.cnf + +COMMON_NAME="Root CA" \ + CA_DIR=out \ + ID=C \ + try openssl ca \ + -batch \ + -extensions ca_intermediate_cert \ + -in out/B.csr \ + -out out/B.pem \ + -config certs.cnf + +echo Generate the leaf certs +COMMON_NAME="Client Cert" \ + ID=A \ + try openssl req \ + -new \ + -key out/A.key \ + -out out/A.csr \ + -config certs.cnf + +echo B signs A +COMMON_NAME="Intermediate CA" \ + CA_DIR=out \ + ID=B \ + try openssl ca \ + -batch \ + -extensions user_cert \ + -in out/A.csr \ + -out out/A.pem \ + -config certs.cnf + +COMMON_NAME="localhost" \ + ID=D \ + try openssl req \ + -new \ + -key out/D.key \ + -out out/D.csr \ + -config certs.cnf + +echo B signs D +COMMON_NAME="Intermediate CA" \ + CA_DIR=out \ + ID=B \ + try openssl ca \ + -batch \ + -extensions server_cert \ + -in out/D.csr \ + -out out/D.pem \ + -config certs.cnf + +echo Package the client cert and private key into PKCS12 file +try /bin/sh -c "cat out/A.pem out/A.key out/B.pem out/C.pem > out/A-chain.pem" + +try openssl pkcs12 \ + -in out/A-chain.pem \ + -out client.p12 \ + -export \ + -passout pass:electron + +echo Package the certs +try cp out/C.pem rootCA.pem +try cp out/B.pem intermediateCA.pem +try cp out/D.key server.key +try cp out/D.pem server.pem + +try rm -rf out diff --git a/spec/fixtures/certificates/intermediateCA.pem b/spec/fixtures/certificates/intermediateCA.pem new file mode 100644 index 00000000000..58293f76da0 --- /dev/null +++ b/spec/fixtures/certificates/intermediateCA.pem @@ -0,0 +1,78 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 4097 (0x1001) + Signature Algorithm: sha256WithRSAEncryption + Issuer: CN=Root CA + Validity + Not Before: Apr 18 16:14:29 2016 GMT + Not After : Apr 16 16:14:29 2026 GMT + Subject: CN=Intermediate CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:b6:42:02:13:25:40:13:a6:05:99:69:da:0c:c9: + a8:bf:86:3b:fc:c6:51:ba:64:65:7e:33:11:31:d5: + 03:45:30:4c:ca:49:d2:96:42:52:2f:f9:e6:6c:9a: + 50:1c:fe:fa:e2:e8:63:36:14:47:f7:49:9f:78:28: + 5e:1f:0b:9d:9e:f8:d3:33:77:06:4d:6d:14:c0:57: + 01:83:2b:ef:99:06:48:21:ec:c1:d7:05:48:2c:ea: + 83:06:6a:20:df:73:ce:8a:a5:e4:81:00:41:84:cf: + 89:81:78:2e:3a:bd:1b:fd:3e:96:08:8d:44:1b:00: + c8:d6:4e:7a:6a:75:c0:9b:3c:e0:fa:aa:3a:82:5b: + 3c:39:32:ca:4a:ba:82:bc:60:47:6f:e4:4a:fd:dc: + a0:72:8a:1b:fe:cd:2e:10:f4:27:4c:08:4e:d1:ed: + dc:08:b0:f8:1f:e4:fc:45:72:43:58:6e:dd:05:37: + 8c:04:a1:fb:64:f4:3f:90:bb:85:f2:4c:97:46:fd: + 1f:29:e5:19:d0:0f:24:fd:d1:00:c5:b6:be:da:84: + 62:77:be:db:67:f6:ec:98:5d:97:f5:df:0a:bd:b8: + 07:7f:0a:d5:92:29:1f:c4:b0:97:4f:e4:87:d7:a9: + 00:c9:61:d5:6c:cd:6a:fc:56:c3:f3:b7:ca:53:70: + 02:3f + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + A9:75:99:CF:9C:92:54:A4:4B:65:CD:3D:FC:93:98:8D:9E:09:1F:47 + X509v3 Authority Key Identifier: + keyid:E3:51:87:E3:CD:7A:B3:26:9F:8F:EC:62:D1:0E:15:0C:39:36:47:4F + + X509v3 Basic Constraints: critical + CA:TRUE, pathlen:0 + X509v3 Key Usage: critical + Digital Signature, Certificate Sign, CRL Sign + Signature Algorithm: sha256WithRSAEncryption + 55:69:d6:1d:33:ad:ab:40:46:fd:34:02:c1:43:50:7b:90:ea: + f3:5f:4f:b6:2c:28:aa:72:e0:4b:36:2e:8f:44:93:15:52:14: + f6:61:b3:50:e0:ba:43:91:ba:a9:5d:ac:43:b7:52:ca:91:a3: + d7:0e:ac:a7:9e:ee:28:7f:2d:0f:93:b5:d9:23:35:68:54:29: + 2a:e7:3a:4c:41:24:d0:5e:2d:f3:1e:b9:52:f1:3e:16:76:93: + 89:6d:a1:4c:63:f5:4a:cc:08:36:61:29:0a:29:5f:f4:5a:55: + 98:10:b3:de:b3:90:f9:03:e5:bd:1b:61:01:a7:22:03:ae:0f: + 77:c4:a8:bf:31:b4:af:c8:c7:e3:25:a1:2b:b9:43:37:3b:08: + ea:c4:46:60:b8:5f:ee:2a:0d:ce:18:75:63:ba:32:28:84:f4: + 56:95:1b:c5:f9:46:7e:14:2e:83:5e:a9:ff:b2:80:ca:25:fd: + 22:90:b5:de:bd:e6:f1:0c:ee:7e:09:71:0d:82:6a:ca:2f:9c: + 96:45:73:3a:65:bc:d8:9d:e0:61:01:5d:a8:de:de:61:8c:82: + 52:0c:ef:97:39:b3:13:c6:7d:d0:c0:f5:6d:c8:70:5b:96:e8: + 99:31:d8:75:3a:21:58:ab:01:21:9e:38:8e:53:ff:f8:48:a7: + af:01:9a:93 +-----BEGIN CERTIFICATE----- +MIIDDjCCAfagAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHUm9v +dCBDQTAeFw0xNjA0MTgxNjE0MjlaFw0yNjA0MTYxNjE0MjlaMBoxGDAWBgNVBAMM +D0ludGVybWVkaWF0ZSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALZCAhMlQBOmBZlp2gzJqL+GO/zGUbpkZX4zETHVA0UwTMpJ0pZCUi/55myaUBz+ ++uLoYzYUR/dJn3goXh8LnZ740zN3Bk1tFMBXAYMr75kGSCHswdcFSCzqgwZqIN9z +zoql5IEAQYTPiYF4Ljq9G/0+lgiNRBsAyNZOemp1wJs84PqqOoJbPDkyykq6grxg +R2/kSv3coHKKG/7NLhD0J0wITtHt3Aiw+B/k/EVyQ1hu3QU3jASh+2T0P5C7hfJM +l0b9HynlGdAPJP3RAMW2vtqEYne+22f27Jhdl/XfCr24B38K1ZIpH8Swl0/kh9ep +AMlh1WzNavxWw/O3ylNwAj8CAwEAAaNmMGQwHQYDVR0OBBYEFKl1mc+cklSkS2XN +PfyTmI2eCR9HMB8GA1UdIwQYMBaAFONRh+PNerMmn4/sYtEOFQw5NkdPMBIGA1Ud +EwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4IB +AQBVadYdM62rQEb9NALBQ1B7kOrzX0+2LCiqcuBLNi6PRJMVUhT2YbNQ4LpDkbqp +XaxDt1LKkaPXDqynnu4ofy0Pk7XZIzVoVCkq5zpMQSTQXi3zHrlS8T4WdpOJbaFM +Y/VKzAg2YSkKKV/0WlWYELPes5D5A+W9G2EBpyIDrg93xKi/MbSvyMfjJaEruUM3 +OwjqxEZguF/uKg3OGHVjujIohPRWlRvF+UZ+FC6DXqn/soDKJf0ikLXevebxDO5+ +CXENgmrKL5yWRXM6ZbzYneBhAV2o3t5hjIJSDO+XObMTxn3QwPVtyHBbluiZMdh1 +OiFYqwEhnjiOU//4SKevAZqT +-----END CERTIFICATE----- diff --git a/spec/fixtures/certificates/rootCA.pem b/spec/fixtures/certificates/rootCA.pem new file mode 100644 index 00000000000..5c77fe61cd0 --- /dev/null +++ b/spec/fixtures/certificates/rootCA.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCjCCAfKgAwIBAgIJAOcWbv0WHll0MA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNV +BAMMB1Jvb3QgQ0EwHhcNMTYwNDE4MTYxNDI5WhcNMjYwNDE2MTYxNDI5WjASMRAw +DgYDVQQDDAdSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +0iZvelv6MjxqdmQsAmKqIfc5gvQjYB3CqWlEH3g5czPFBMMtmOI9czlk+0jc1VEf +t1SKst7zwe1rpxFArgudV45NBHQH3ZlzkLeO7Ol2kPzlyMHNJ70vT3CBitKnLl4B +bg7xf6kDQQlC3/QeWxvbR5cvp131uwcpXKdJ9k4dwpfS2BKiRb5Uk46DgX5kGaka +q/tQ2F7b6AlAoTq608tZBuOInkg2tTbGe9PDWSL8oMZRwCSbF543SAR45zjWBa0k +ymY31VvlYbEd/3lfE5Mrn/JwZQpTKOfcOI//kUkcClJVpSMObh4eiy1oNjqcJ4KR +/4hkY7oTQCA7zWD34jQpkQIDAQABo2MwYTAdBgNVHQ4EFgQU41GH4816syafj+xi +0Q4VDDk2R08wHwYDVR0jBBgwFoAU41GH4816syafj+xi0Q4VDDk2R08wDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggEBADrt +1bSbOYxDmB1x9KaHNFVSzs0XsipsbZW/XTqtNMPMFXh+I57NVptVanCwcfU5zmOF +AjL+R8v0NkPU9+6nSM2PYqWxEavf0f6pkxIj+ThFwtVwXEKocPG9RFUvZNZv+rSH +yAnzuAzFI71EsT9VgJGHI0pgPjrGbSlNfb0OJFOlwtbGWGofmg+N6hHcx5nVKlgL +ZWLtYT+/mT2pSGuIpJtdnuUv0vcrRa4mxAa8NPF4+Qpi6yErkfogE+T4RYf2L4rp +CaRIFicLoNUmwK0nCerJaPFLwGkiNGNX81CHnw3+xLisSPvxze2ZRA0DhUWUGInq +grjWDMO9P1hPWu5jmbo= +-----END CERTIFICATE----- diff --git a/spec/fixtures/certificates/server.key b/spec/fixtures/certificates/server.key new file mode 100644 index 00000000000..719bfc8797d --- /dev/null +++ b/spec/fixtures/certificates/server.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAuByk7Ib6anz0xOFRqyogGsTTEAAGduquIckVFajDHrk7vdq+ +TflkDp+UhbISqu1rj0OuaqODxiPSSw5fHClqNKpjhHS1ry86knS847BGwrByY0oa +zBdN0UgtWiXOK+iCuSI9p0KSIORJ3Y70pUZmm12EHRwb0tANv4ogYxjAxwnyqYgn +PnrDsoyCh/Cb4Fu8XucrnepYbInXi6yOdwTuivTx9qy7tlQzvYJ2LLEUIJdBtCUZ +dZkxky9CJUbfu5rm6PFvbLII5YCSlpXLxg9bumZCR1z9IXE6rLYcJIp3HIquR2cN +tAs9M8OHuR5V6vhUG51bP3aTkg3asJVdUe10dwIDAQABAoIBAQCJGINSwZv86blW +VbX7r+2iIUhNVMd7i3tJGzQBId7RpPswf49P/tIb9YaiG5y8/PgoAS0CqWn5hDkW +vMfj747vUqWyPzn/DjseTaFOJrg6RyuWddsIeJ3wpj9nLlmc5pFZDH8+alrn9TZv +rgDMhWTocjVre7/YNibWpyNAx3DdhG5DzNVLnu1R68d5k3JutQVqm01xCAV9ne9n +xE1RB5Z1xLvpQfW2qLYT0yFB7Xxw8awGyzVesPhGW1aa5F4urQjdCt2baa06Xolu +T3wXJ6wA9BuF2KOCi8DxELDaXoB//+82HafgWbOWIhJFOzEZaMNqZkfS/GbCgpEr +mE2r8zGBAoGBAOHNcUPgnIIeGdgFZZvL3Ge3Hp5mi2Vd2KBkAPNCjVSXeCu57yRC +SetlYuZlIhd7o+wdxUmWtg73DU19eDXJsOjXgNAoJfT9Zsyi4RClmJ0FRcSzvFU/ +m/TKrBbnFFAI+1pKwDnQ7envuRiTECFSsvKqdr8hddx0cPCgDtbe+75BAoGBANC7 +4ozkgsUTtdojz0DYBYBwUjN1gUETIhl91tt+48hmmEedROWDQDCT9gJfpAVFe1I6 +RyKKJnBcgNDJ7mqPUB1f5xb5rtaZS1owPNYTi3GrdVVg3lAf0j5ch8XoRJn/plnL +M0Sj5lLMviHJjyk8CPHbnE2k2vERAW4/SgzfA3S3AoGAHx55Jamm6CfN1/+maTpH +PeP2zE3FmEq+uBwQJXZek/HsFdqiIpUgKtjmMGpvsFzR0pCnx+SFYrqZkrxf/Mm3 +H9/TWNyvnnvt1vX7npez2LAJVXqP0g/aJnpoDR/7pKwYN/FlXJJ2t27aS5C5AF6t +WtQzWVP7Mk654e+tG9/PQgECgYEAiTCT7EpccK9NvLwAgfv5UbuBK3U1qNGsfdip +mMZDa/mSaK9DEx462DLHZDP8F8LdFORc0KTAMuV5fMDbxInA/C2GMyGT+lPypKpD +sehSpDku+xiZxUvE4VvrmPXZ8OWILkhRv/GBdjY/WPGi+FUPA/d1Ocr6Y6rrp8xN +HTyOhu0CgYBKxTSH6RCQsm8Q8uqmcP7cwe6fciTC0c2CRRqlzuXeseG72MBRDk/8 +P1jtOIlIsax/8NwNm5ReAiLgVn/h6/YgN4fpMkV1XIaH4j7HiGf5CWgOTWxS9jWA +cV09H22BaNkT0fZ71IlXQI11cVRodX0g4cJXeuyTxY9OkMd6cGs8+A== +-----END RSA PRIVATE KEY----- diff --git a/spec/fixtures/certificates/server.pem b/spec/fixtures/certificates/server.pem new file mode 100644 index 00000000000..117be807e52 --- /dev/null +++ b/spec/fixtures/certificates/server.pem @@ -0,0 +1,88 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 4097 (0x1001) + Signature Algorithm: sha256WithRSAEncryption + Issuer: CN=Intermediate CA + Validity + Not Before: Apr 18 16:14:29 2016 GMT + Not After : Apr 16 16:14:29 2026 GMT + Subject: CN=localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:b8:1c:a4:ec:86:fa:6a:7c:f4:c4:e1:51:ab:2a: + 20:1a:c4:d3:10:00:06:76:ea:ae:21:c9:15:15:a8: + c3:1e:b9:3b:bd:da:be:4d:f9:64:0e:9f:94:85:b2: + 12:aa:ed:6b:8f:43:ae:6a:a3:83:c6:23:d2:4b:0e: + 5f:1c:29:6a:34:aa:63:84:74:b5:af:2f:3a:92:74: + bc:e3:b0:46:c2:b0:72:63:4a:1a:cc:17:4d:d1:48: + 2d:5a:25:ce:2b:e8:82:b9:22:3d:a7:42:92:20:e4: + 49:dd:8e:f4:a5:46:66:9b:5d:84:1d:1c:1b:d2:d0: + 0d:bf:8a:20:63:18:c0:c7:09:f2:a9:88:27:3e:7a: + c3:b2:8c:82:87:f0:9b:e0:5b:bc:5e:e7:2b:9d:ea: + 58:6c:89:d7:8b:ac:8e:77:04:ee:8a:f4:f1:f6:ac: + bb:b6:54:33:bd:82:76:2c:b1:14:20:97:41:b4:25: + 19:75:99:31:93:2f:42:25:46:df:bb:9a:e6:e8:f1: + 6f:6c:b2:08:e5:80:92:96:95:cb:c6:0f:5b:ba:66: + 42:47:5c:fd:21:71:3a:ac:b6:1c:24:8a:77:1c:8a: + ae:47:67:0d:b4:0b:3d:33:c3:87:b9:1e:55:ea:f8: + 54:1b:9d:5b:3f:76:93:92:0d:da:b0:95:5d:51:ed: + 74:77 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + Netscape Cert Type: + SSL Server + Netscape Comment: + OpenSSL Generated Server Certificate + X509v3 Subject Key Identifier: + 1D:60:82:FA:3A:EC:27:91:BA:8D:F5:ED:B2:E3:85:0B:22:5A:8E:38 + X509v3 Authority Key Identifier: + keyid:A9:75:99:CF:9C:92:54:A4:4B:65:CD:3D:FC:93:98:8D:9E:09:1F:47 + DirName:/CN=Root CA + serial:10:01 + + X509v3 Key Usage: critical + Digital Signature, Key Encipherment + X509v3 Extended Key Usage: + TLS Web Server Authentication + Signature Algorithm: sha256WithRSAEncryption + 89:90:3d:2c:b8:0d:36:63:68:9a:cd:f9:14:56:94:d9:18:11: + b5:08:35:af:f9:34:cd:70:db:7d:66:06:e3:57:9b:06:8f:11: + d6:ea:ac:a6:07:db:ae:a2:c0:66:69:84:d8:2d:3c:cc:d7:4d: + 3c:75:60:4f:98:fc:56:df:30:39:c6:55:2c:73:92:9e:0c:b5: + 7c:75:40:5d:21:aa:01:c1:8a:03:86:eb:d7:02:7d:f5:7b:12: + cc:18:90:23:ad:8f:d7:05:18:6d:f0:11:a8:6b:27:fd:4c:07: + 07:53:f5:7f:f7:a2:e5:18:1e:4e:90:1b:10:5f:f3:5c:cb:c7: + 37:63:d0:d5:1d:3a:65:66:24:ee:0e:ce:7f:b1:fb:ee:17:d0: + b5:4d:64:2f:5a:9c:bc:7a:1c:c0:b4:0f:32:c9:a9:5c:cb:57: + 26:fd:49:39:8d:f2:89:54:c4:92:b5:35:ec:fe:cf:87:07:a6: + 84:01:98:00:e4:2a:44:26:b7:48:00:11:d3:e4:5a:c1:ad:46: + 36:53:f9:28:b7:e4:c5:bb:66:88:ab:8e:cc:30:d0:96:aa:3e: + c1:12:6a:8f:fa:6d:19:15:f4:90:66:54:62:84:97:06:2d:5c: + b9:18:71:90:f4:ca:4c:8c:a5:8b:32:14:93:89:f1:93:f4:00: + bd:1d:42:4f +-----BEGIN CERTIFICATE----- +MIIDgjCCAmqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwGjEYMBYGA1UEAwwPSW50 +ZXJtZWRpYXRlIENBMB4XDTE2MDQxODE2MTQyOVoXDTI2MDQxNjE2MTQyOVowFDES +MBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAuByk7Ib6anz0xOFRqyogGsTTEAAGduquIckVFajDHrk7vdq+TflkDp+UhbIS +qu1rj0OuaqODxiPSSw5fHClqNKpjhHS1ry86knS847BGwrByY0oazBdN0UgtWiXO +K+iCuSI9p0KSIORJ3Y70pUZmm12EHRwb0tANv4ogYxjAxwnyqYgnPnrDsoyCh/Cb +4Fu8XucrnepYbInXi6yOdwTuivTx9qy7tlQzvYJ2LLEUIJdBtCUZdZkxky9CJUbf +u5rm6PFvbLII5YCSlpXLxg9bumZCR1z9IXE6rLYcJIp3HIquR2cNtAs9M8OHuR5V +6vhUG51bP3aTkg3asJVdUe10dwIDAQABo4HXMIHUMAkGA1UdEwQCMAAwEQYJYIZI +AYb4QgEBBAQDAgZAMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBT +ZXJ2ZXIgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFB1ggvo67CeRuo317bLjhQsiWo44 +MDsGA1UdIwQ0MDKAFKl1mc+cklSkS2XNPfyTmI2eCR9HoRakFDASMRAwDgYDVQQD +DAdSb290IENBggIQATAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUH +AwEwDQYJKoZIhvcNAQELBQADggEBAImQPSy4DTZjaJrN+RRWlNkYEbUINa/5NM1w +231mBuNXmwaPEdbqrKYH266iwGZphNgtPMzXTTx1YE+Y/FbfMDnGVSxzkp4MtXx1 +QF0hqgHBigOG69cCffV7EswYkCOtj9cFGG3wEahrJ/1MBwdT9X/3ouUYHk6QGxBf +81zLxzdj0NUdOmVmJO4Ozn+x++4X0LVNZC9anLx6HMC0DzLJqVzLVyb9STmN8olU +xJK1Nez+z4cHpoQBmADkKkQmt0gAEdPkWsGtRjZT+Si35MW7Zoirjsww0JaqPsES +ao/6bRkV9JBmVGKElwYtXLkYcZD0ykyMpYsyFJOJ8ZP0AL0dQk8= +-----END CERTIFICATE----- From 919be67cd2ad481668815d065174c88fff9e2343 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 22:26:37 +0530 Subject: [PATCH 0521/1265] remove --client-certificate flag --- atom/browser/api/atom_api_app.cc | 7 +++---- atom/common/options_switches.cc | 3 --- atom/common/options_switches.h | 1 - docs/api/chrome-command-line-switches.md | 4 ---- 4 files changed, 3 insertions(+), 12 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 1446d44ad00..d6afbb366e0 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -179,11 +179,11 @@ int ImportIntoCertStore( &imported_certs); if (imported_certs.size() > 1) { auto it = imported_certs.begin(); - ++it; // skip first which would be the client certificate. + ++it; // skip first which would be the client certificate. for (; it != imported_certs.end(); ++it) rv &= model->SetCertTrust(it->get(), - net::CA_CERT, - net::NSSCertDatabase::TRUSTED_SSL); + net::CA_CERT, + net::NSSCertDatabase::TRUSTED_SSL); } } } @@ -491,7 +491,6 @@ void AppendSwitch(const std::string& switch_string, mate::Arguments* args) { auto command_line = base::CommandLine::ForCurrentProcess(); if (switch_string == atom::switches::kPpapiFlashPath || - switch_string == atom::switches::kClientCertificate || switch_string == switches::kLogNetLog) { base::FilePath path; args->GetNext(&path); diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index ce28cc98fac..562171d51f2 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -119,9 +119,6 @@ const char kPpapiFlashPath[] = "ppapi-flash-path"; // Ppapi Flash version. const char kPpapiFlashVersion[] = "ppapi-flash-version"; -// Path to client certificate. -const char kClientCertificate[] = "client-certificate"; - // Disable HTTP cache. const char kDisableHttpCache[] = "disable-http-cache"; diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 52d64c00d51..5746a7bbfe5 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -68,7 +68,6 @@ namespace switches { extern const char kEnablePlugins[]; extern const char kPpapiFlashPath[]; extern const char kPpapiFlashVersion[]; -extern const char kClientCertificate[]; extern const char kDisableHttpCache[]; extern const char kRegisterStandardSchemes[]; extern const char kRegisterServiceWorkerSchemes[]; diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index 65f096eac6e..8e8aa38e62d 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -15,10 +15,6 @@ app.on('ready', function() { }); ``` -## --client-certificate=`path` - -Sets the `path` of client certificate file. - ## --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. From 2c0494dcef0b483061bbdf07f09e39d1774d20a0 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 18 Apr 2016 22:57:37 +0530 Subject: [PATCH 0522/1265] fix spec --- spec/api-app-spec.js | 15 ++++++++++----- spec/fixtures/certificates/certs.cnf | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 1f5452713bc..8923d2d214f 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -95,7 +95,6 @@ describe('app module', function () { this.timeout(5000) - var port var w = null var certPath = path.join(__dirname, 'fixtures', 'certificates') var options = { @@ -115,9 +114,6 @@ describe('app module', function () { res.end('authorized'); } }) - server.listen(0, '127.0.0.1', function () { - port = server.address().port - }) afterEach(function () { if (w != null) { @@ -141,9 +137,18 @@ describe('app module', function () { done() }) + app.on('select-client-certificate', function (event, webContents, url, list, callback) { + assert.equal(list.length, 1) + assert.equal(list[0].issuerName, 'Intermediate CA') + callback(list[0]) + }) + app.importClientCertificate(options, function (result) { assert(!result) - w.loadURL(`https://127.0.0.1:${port}`) + server.listen(0, '127.0.0.1', function () { + var port = server.address().port + w.loadURL(`https://127.0.0.1:${port}`) + }) }) }) }) diff --git a/spec/fixtures/certificates/certs.cnf b/spec/fixtures/certificates/certs.cnf index d8b5c66e13a..76ef8d073f9 100644 --- a/spec/fixtures/certificates/certs.cnf +++ b/spec/fixtures/certificates/certs.cnf @@ -15,7 +15,7 @@ RANDFILE = $dir/rand default_md = sha256 default_days = 3650 policy = policy_anything -preserve = no +preserve = no [policy_anything] # Default signing policy @@ -32,7 +32,7 @@ default_bits = 2048 default_md = sha256 string_mask = utf8only distinguished_name = req_env_dn -prompt = no +prompt = no [user_cert] basicConstraints = CA:FALSE From 3a9bbe30ac3a45748dbc4796ab4f2f51558be2f2 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Mon, 18 Apr 2016 10:33:56 -0700 Subject: [PATCH 0523/1265] Test for #5183 - webContents.executeJavaScript hangs on subframe load. --- spec/api-browser-window-spec.js | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 2a8d1295c7f..26d4ff4af35 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -4,6 +4,7 @@ const assert = require('assert') const fs = require('fs') const path = require('path') const os = require('os') +const http = require('http') const remote = require('electron').remote const screen = require('electron').screen @@ -785,6 +786,14 @@ describe('browser-window module', function () { describe('window.webContents.executeJavaScript', function () { var expected = 'hello, world!' var code = '(() => "' + expected + '")()' + var server + + afterEach(function () { + if (server) { + server.close() + server = null + } + }) it('doesnt throw when no calback is provided', function () { const result = ipcRenderer.sendSync('executeJavaScript', code, false) @@ -798,6 +807,31 @@ describe('browser-window module', function () { done() }) }) + + it('works after page load and during subframe load', function (done) { + var url + // a slow server, guaranteeing time to execute code during loading + server = http.createServer(function (req, res) { + setTimeout(function() { res.end('') }, 200) + }); + server.listen(0, '127.0.0.1', function () { + url = 'http://127.0.0.1:' + server.address().port + w.loadURL('file://' + path.join(fixtures, 'pages', 'base-page.html')) + }) + + w.webContents.once('did-finish-load', function() { + // initiate a sub-frame load, then try and execute script during it + w.webContents.executeJavaScript(` + var iframe = document.createElement('iframe') + iframe.src = '${url}' + document.body.appendChild(iframe) + `, function() { + w.webContents.executeJavaScript(`console.log('hello')`, function() { + done() + }) + }) + }) + }) }) describe('deprecated options', function () { From 64a84dee3bdcc81819733fb7f3e266e8e0bb5709 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Mon, 18 Apr 2016 10:37:08 -0700 Subject: [PATCH 0524/1265] =?UTF-8?q?Add=20`isLoadingMainFrame`=20method?= =?UTF-8?q?=20to=20WebContents.=20Also=20switch=20`webContents.executeJava?= =?UTF-8?q?Script`=20to=20check=20it=20instead=20of=20`isLoading`.=20There?= =?UTF-8?q?=20doesn=E2=80=99t=20seem=20to=20be=20a=20reasonable=20public?= =?UTF-8?q?=20way=20to=20get=20this=20information=20out=20of=20Chromium,?= =?UTF-8?q?=20so=20it=E2=80=99s=20synthesized=20here=20based=20on=20WebCon?= =?UTF-8?q?tentsObserver=20callbacks.=20Fixes=20#5183.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- atom/browser/api/atom_api_web_contents.cc | 33 +++++++++++++++++++++-- atom/browser/api/atom_api_web_contents.h | 11 ++++++++ lib/browser/api/web-contents.js | 2 +- lib/renderer/web-view/web-view.js | 1 + 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 64a76d57e65..c6943d506e6 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -220,7 +220,8 @@ WebContents::WebContents(content::WebContents* web_contents) embedder_(nullptr), type_(REMOTE), request_id_(0), - background_throttling_(true) { + background_throttling_(true), + is_loading_main_frame_(false) { AttachAsUserData(web_contents); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); } @@ -229,7 +230,8 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options) : embedder_(nullptr), request_id_(0), - background_throttling_(true) { + background_throttling_(true), + is_loading_main_frame_(false) { // Read options. options.Get("backgroundThrottling", &background_throttling_); @@ -543,12 +545,32 @@ void WebContents::DocumentLoadedInFrame( void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); + if (is_main_frame) + is_loading_main_frame_ = false; + Emit("did-frame-finish-load", is_main_frame); if (is_main_frame) Emit("did-finish-load"); } +void WebContents::DidStartProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& url, + bool is_error_page, + bool is_iframe_srcdoc) { + if (!render_frame_host->GetParent()) + is_loading_main_frame_ = true; +} + +void WebContents::DidCommitProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& url, + ui::PageTransition transition_type) { + if (!render_frame_host->GetParent()) + is_loading_main_frame_ = true; +} + void WebContents::DidFailProvisionalLoad( content::RenderFrameHost* render_frame_host, const GURL& url, @@ -556,6 +578,8 @@ void WebContents::DidFailProvisionalLoad( const base::string16& description, bool was_ignored_by_handler) { bool is_main_frame = !render_frame_host->GetParent(); + if (is_main_frame) + is_loading_main_frame_ = false; Emit("did-fail-provisional-load", code, description, url, is_main_frame); Emit("did-fail-load", code, description, url, is_main_frame); } @@ -792,6 +816,10 @@ base::string16 WebContents::GetTitle() const { bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } + +bool WebContents::IsLoadingMainFrame() const { + return is_loading_main_frame_; +} bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); @@ -1189,6 +1217,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, .SetMethod("_getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) + .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("_stop", &WebContents::Stop) .SetMethod("_goBack", &WebContents::GoBack) diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 0cb2a348e17..7e4bd693536 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -62,6 +62,7 @@ class WebContents : public mate::TrackableObject, GURL GetURL() const; base::string16 GetTitle() const; bool IsLoading() const; + bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); void ReloadIgnoringCache(); @@ -228,6 +229,13 @@ class WebContents : public mate::TrackableObject, int error_code, const base::string16& error_description, bool was_ignored_by_handler) override; + void DidStartProvisionalLoadForFrame(content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + bool is_error_page, + bool is_iframe_srcdoc) override; + void DidCommitProvisionalLoadForFrame(content::RenderFrameHost* render_frame_host, + const GURL& url, + ui::PageTransition transition_type) override; void DidStartLoading() override; void DidStopLoading() override; void DidGetResourceResponseStart( @@ -302,6 +310,9 @@ class WebContents : public mate::TrackableObject, // Whether background throttling is disabled. bool background_throttling_; + // Whether the main frame (not just a sub-frame) is currently loading. + bool is_loading_main_frame_; + DISALLOW_COPY_AND_ASSIGN(WebContents); }; diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 40efa77cda0..dfacf6a02cf 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -116,7 +116,7 @@ let wrapWebContents = function (webContents) { callback = hasUserGesture hasUserGesture = false } - if (this.getURL() && !this.isLoading()) { + if (this.getURL() && !this.isLoadingMainFrame()) { return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture) } else { return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)) diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 974d5c6608d..20f5f07465b 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -335,6 +335,7 @@ var registerWebViewElement = function () { 'loadURL', 'getTitle', 'isLoading', + 'isLoadingMainFrame', 'isWaitingForResponse', 'stop', 'reload', From c3200ba7f6f4c9c53167baffde764ffc00c42eaa Mon Sep 17 00:00:00 2001 From: Jessica Lord Date: Mon, 18 Apr 2016 18:00:32 -0700 Subject: [PATCH 0525/1265] Revert "Fix headers" This reverts commit 4dd2716865f6944606f8dffd27ab68434f30643b. --- docs/api/session.md | 56 ++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/docs/api/session.md b/docs/api/session.md index 758082fa621..9cccefcbdb6 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -48,11 +48,11 @@ const session = require('electron').session; var ses = session.fromPartition('persist:name'); ``` -## Instance Events +### Instance Events The following events are available on instances of `Session`: -### Event: 'will-download' +#### Event: 'will-download' * `event` Event * `item` [DownloadItem](download-item.md) @@ -72,11 +72,11 @@ session.defaultSession.on('will-download', function(event, item, webContents) { }); ``` -## Instance Methods +### Instance Methods The following methods are available on instances of `Session`: -### `session.cookies` +#### `ses.cookies` The `cookies` gives you ability to query and modify cookies. For example: @@ -100,7 +100,7 @@ session.defaultSession.cookies.set(cookie, function(error) { }); ``` -### `session.cookies.get(filter, callback)` +#### `ses.cookies.get(filter, callback)` * `filter` Object * `url` String (optional) - Retrieves cookies which are associated with @@ -132,7 +132,7 @@ with `callback(error, cookies)` on complete. the number of seconds since the UNIX epoch. Not provided for session cookies. -### `session.cookies.set(details, callback)` +#### `ses.cookies.set(details, callback)` * `details` Object * `url` String - Retrieves cookies which are associated with `url` @@ -151,7 +151,7 @@ with `callback(error, cookies)` on complete. Sets the cookie with `details`, `callback` will be called with `callback(error)` on complete. -### `session.cookies.remove(url, name, callback)` +#### `ses.cookies.remove(url, name, callback)` * `url` String - The URL associated with the cookie. * `name` String - The name of cookie to remove. @@ -160,20 +160,20 @@ on complete. Removes the cookies matching `url` and `name`, `callback` will called with `callback()` on complete. -### `session.getCacheSize(callback)` +#### `ses.getCacheSize(callback)` * `callback` Function * `size` Integer - Cache size used in bytes. Returns the session's current cache size. -### `session.clearCache(callback)` +#### `ses.clearCache(callback)` * `callback` Function - Called when operation is done Clears the session’s HTTP cache. -### `session.clearStorageData([options, ]callback)` +#### `ses.clearStorageData([options, ]callback)` * `options` Object (optional) * `origin` String - Should follow `window.location.origin`’s representation @@ -187,11 +187,11 @@ Clears the session’s HTTP cache. Clears the data of web storages. -### `session.flushStorageData()` +#### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. -### `session.setProxy(config, callback)` +#### `ses.setProxy(config, callback)` * `config` Object * `pacScript` String - The URL associated with the PAC file. @@ -228,7 +228,7 @@ For example: * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. -### `session.resolveProxy(url, callback)` +### `ses.resolveProxy(url, callback)` * `url` URL * `callback` Function @@ -236,14 +236,14 @@ For example: Resolves the proxy information for `url`. The `callback` will be called with `callback(proxy)` when the request is performed. -### `session.setDownloadPath(path)` +#### `ses.setDownloadPath(path)` * `path` String - The download location Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. -### `session.enableNetworkEmulation(options)` +#### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` Boolean - Whether to emulate network outage. @@ -265,12 +265,12 @@ window.webContents.session.enableNetworkEmulation({ window.webContents.session.enableNetworkEmulation({offline: true}); ``` -### `session.disableNetworkEmulation()` +#### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. -### `session.setCertificateVerifyProc(proc)` +#### `ses.setCertificateVerifyProc(proc)` * `proc` Function @@ -291,7 +291,7 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c }); ``` -### `session.setPermissionRequestHandler(handler)` +#### `ses.setPermissionRequestHandler(handler)` * `handler` Function * `webContents` Object - [WebContents](web-contents.md) requesting the permission. @@ -314,13 +314,13 @@ session.fromPartition(partition).setPermissionRequestHandler(function(webContent }); ``` -### `session.clearHostResolverCache([callback])` +#### `ses.clearHostResolverCache([callback])` * `callback` Function (optional) - Called when operation is done. Clears the host resolver cache. -### `session.webRequest` +#### `ses.webRequest` The `webRequest` API set allows to intercept and modify contents of a request at various stages of its lifetime. @@ -349,7 +349,7 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, }); ``` -### `session.webRequest.onBeforeRequest([filter, ]listener)` +#### `ses.webRequest.onBeforeRequest([filter, ]listener)` * `filter` Object * `listener` Function @@ -379,7 +379,7 @@ The `callback` has to be called with an `response` object: * `redirectURL` String (optional) - The original request is prevented from being sent or completed, and is instead redirected to the given URL. -### `session.webRequest.onBeforeSendHeaders([filter, ]listener)` +#### `ses.webRequest.onBeforeSendHeaders([filter, ]listener)` * `filter` Object * `listener` Function @@ -404,7 +404,7 @@ The `callback` has to be called with an `response` object: * `requestHeaders` Object (optional) - When provided, request will be made with these headers. -### `session.webRequest.onSendHeaders([filter, ]listener)` +#### `ses.webRequest.onSendHeaders([filter, ]listener)` * `filter` Object * `listener` Function @@ -421,7 +421,7 @@ response are visible by the time this listener is fired. * `timestamp` Double * `requestHeaders` Object -### `session.webRequest.onHeadersReceived([filter,] listener)` +#### `ses.webRequest.onHeadersReceived([filter,] listener)` * `filter` Object * `listener` Function @@ -449,7 +449,7 @@ The `callback` has to be called with an `response` object: * `statusLine` String (optional) - Should be provided when overriding `responseHeaders` to change header status otherwise original response header's status will be used. -### `session.webRequest.onResponseStarted([filter, ]listener)` +#### `ses.webRequest.onResponseStarted([filter, ]listener)` * `filter` Object * `listener` Function @@ -470,7 +470,7 @@ and response headers are available. * `statusCode` Integer * `statusLine` String -### `session.webRequest.onBeforeRedirect([filter, ]listener)` +#### `ses.webRequest.onBeforeRedirect([filter, ]listener)` * `filter` Object * `listener` Function @@ -491,7 +491,7 @@ redirect is about to occur. * `fromCache` Boolean * `responseHeaders` Object -### `session.webRequest.onCompleted([filter, ]listener)` +#### `ses.webRequest.onCompleted([filter, ]listener)` * `filter` Object * `listener` Function @@ -510,7 +510,7 @@ completed. * `statusCode` Integer * `statusLine` String -### `session.webRequest.onErrorOccurred([filter, ]listener)` +#### `ses.webRequest.onErrorOccurred([filter, ]listener)` * `filter` Object * `listener` Function From 916114dd2820b0fda8636d9f50d57e1ae6fed4e3 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Mon, 18 Apr 2016 20:23:11 -0700 Subject: [PATCH 0526/1265] :memo: keeping submodules up to date --- .../source-code-directory-structure.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/development/source-code-directory-structure.md b/docs/development/source-code-directory-structure.md index 998280a3705..1c9e8c2b774 100644 --- a/docs/development/source-code-directory-structure.md +++ b/docs/development/source-code-directory-structure.md @@ -62,3 +62,30 @@ Electron when creating a distribution. * **external_binaries** - Downloaded binaries of third-party frameworks which do not support building with `gyp`. + +## Keeping Git Submodules Up to Date + +The Electron repository has a few vendored dependencies, found in the +[/vendor](/vendor) directory. Occasionally you might see a message like this +when running `git status`: + +```sh +$ git status + + modified: vendor/brightray (new commits) + modified: vendor/node (new commits) +``` + +To update these vendored dependencies, run the following command: + +```sh +git submodule update --init --recursive +``` + +If you find yourself running this command often, you can create an alias for it +in your `~/.gitconfig` file: + +``` +[alias] + su = git submodule update --init --recursive +``` From fcad4ee1867659c7b6e3d0a63393c65bae773ff5 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Tue, 19 Apr 2016 11:58:58 +0800 Subject: [PATCH 0527/1265] Create download-item.md --- docs-translations/zh-CN/api/download-item.md | 96 ++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 docs-translations/zh-CN/api/download-item.md diff --git a/docs-translations/zh-CN/api/download-item.md b/docs-translations/zh-CN/api/download-item.md new file mode 100644 index 00000000000..a8ed266479d --- /dev/null +++ b/docs-translations/zh-CN/api/download-item.md @@ -0,0 +1,96 @@ +# DownloadItem + +`DownloadItem`(下载项)是一个在Electron中展示下载项的 +[EventEmitter](https://github.com/nodejs/node/blob/master/doc/api/events.markdown)(nodejs)。 +它被用于`Session`模块中的`will-download`事件,允许用户去控制下载项。 + +```javascript +// In the main process. +win.webContents.session.on('will-download', function(event, item, webContents) { + // Set the save path, making Electron not to prompt a save dialog. + item.setSavePath('/tmp/save.pdf'); + console.log(item.getMimeType()); + console.log(item.getFilename()); + console.log(item.getTotalBytes()); + item.on('updated', function() { + console.log('Received bytes: ' + item.getReceivedBytes()); + }); + item.on('done', function(e, state) { + if (state == "completed") { + console.log("Download successfully"); + } else { + console.log("Download is cancelled or interrupted that can't be resumed"); + } + }); +``` + +## 事件 + +### 事件: 'updated' + +当`downloadItem`获得更新时发射。 + +### 事件: 'done' + +* `event` Event +* `state` String + * `completed` - 下载成功完成。 + * `cancelled` - 下载被取消。 + * `interrupted` - 与文件服务器错误的中断连接。 + +当下载处于一个终止状态时发射。这包括了一个完成的下载,一个被取消的下载(via `downloadItem.cancel()`), +和一个被意外中断的下载(无法恢复)。 + +## 方法 + +`downloadItem`对象有以下一些方法: + +### `downloadItem.setSavePath(path)` + +* `path` String - 设置下载项的保存文件路径. + +这个API仅仅在`session`的`will-download`回调函数中可用。 +如果用户没有这个API去设置保存路径,Electron会用原始程序去确定保存路径(通常提示一个保存对话框)。 + +### `downloadItem.pause()` + +暂停下载。 + +### `downloadItem.resume()` + +恢复被暂停的下载。 + +### `downloadItem.cancel()` + +取消下载操作。 + +### `downloadItem.getURL()` + +以`String`形式返回一个该下载项的下载源url。 + +### `downloadItem.getMimeType()` + +返回一个表示mime类型的`String`。 + +### `downloadItem.hasUserGesture()` + +返回一个`Boolean`表示下载是否有用户动作。 + +### `downloadItem.getFilename()` + +返回一个表示下载项文件名的`String`。 + +**Note:** 此文件名不一定总是保存在本地硬盘上的实际文件名。 +如果用户在下载保存对话框中修改了文件名,保存的文件的实际名称会与`downloadItem.getFilename()`方法返回的文件名不同。 + +### `downloadItem.getTotalBytes()` + +返回一个表示下载项总字节数大小的`Integer`。如果大小未知,返回0。 + +### `downloadItem.getReceivedBytes()` + +返回一个表示下载项已经接收的字节数大小的`Integer`。 + +### `downloadItem.getContentDisposition()` + +以`String`形式返回响应头(response header)中的`Content-Disposition`域。 From 591f8fed883ae1fd71866088f5266be97789caeb Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Tue, 19 Apr 2016 12:03:34 +0800 Subject: [PATCH 0528/1265] Update frameless-window.md --- docs-translations/zh-CN/api/frameless-window.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/api/frameless-window.md b/docs-translations/zh-CN/api/frameless-window.md index 1916c6a929b..833f070ad27 100644 --- a/docs-translations/zh-CN/api/frameless-window.md +++ b/docs-translations/zh-CN/api/frameless-window.md @@ -1,4 +1,4 @@ -# 无边框窗口 +# Frameless Window 无边框窗口指的是不包含除页面本身以外任何其它可视部分的窗口([chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome))。 像工具栏,是窗口的一部分,但并不属于页面。这些是[`BrowserWindow`](browser-window.md) 类的选项。 From ddf962c6eae0aa44b61112e1e7ee6ab8c89137db Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Tue, 19 Apr 2016 10:01:38 +0530 Subject: [PATCH 0529/1265] client_id is accessed on different threads --- atom/browser/net/atom_network_delegate.cc | 11 +++++++++-- atom/browser/net/atom_network_delegate.h | 2 ++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/atom/browser/net/atom_network_delegate.cc b/atom/browser/net/atom_network_delegate.cc index 6ef5ac22807..3143cd3b257 100644 --- a/atom/browser/net/atom_network_delegate.cc +++ b/atom/browser/net/atom_network_delegate.cc @@ -229,6 +229,7 @@ void AtomNetworkDelegate::SetResponseListenerInIO( void AtomNetworkDelegate::SetDevToolsNetworkEmulationClientId( const std::string& client_id) { + base::AutoLock auto_lock(lock_); client_id_ = client_id; } @@ -247,10 +248,16 @@ int AtomNetworkDelegate::OnBeforeSendHeaders( net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers) { - if (!client_id_.empty()) + std::string client_id; + { + base::AutoLock auto_lock(lock_); + client_id = client_id_; + } + + if (!client_id.empty()) headers->SetHeader( DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId, - client_id_); + client_id); if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders)) return brightray::NetworkDelegate::OnBeforeSendHeaders( request, callback, headers); diff --git a/atom/browser/net/atom_network_delegate.h b/atom/browser/net/atom_network_delegate.h index e0b41eb4589..92ea6415e69 100644 --- a/atom/browser/net/atom_network_delegate.h +++ b/atom/browser/net/atom_network_delegate.h @@ -11,6 +11,7 @@ #include "brightray/browser/network_delegate.h" #include "base/callback.h" +#include "base/synchronization/lock.h" #include "base/values.h" #include "extensions/common/url_pattern.h" #include "net/base/net_errors.h" @@ -119,6 +120,7 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate { std::map response_listeners_; std::map callbacks_; + base::Lock lock_; // Client id for devtools network emulation. std::string client_id_; From 8f89cd2d5988bd1ffa31d0144b4fe3033a0bdbb1 Mon Sep 17 00:00:00 2001 From: Ben Gotow Date: Mon, 18 Apr 2016 22:39:12 -0700 Subject: [PATCH 0530/1265] Move "setSheetOffset" to the BrowserWindow --- atom/browser/api/atom_api_dialog.cc | 5 ----- atom/browser/api/atom_api_window.cc | 5 +++++ atom/browser/api/atom_api_window.h | 1 + atom/browser/native_window.cc | 16 ++++++++-------- docs/api/browser-window.md | 11 +++++++++++ docs/api/dialog.md | 18 ++---------------- lib/browser/api/dialog.js | 4 ---- 7 files changed, 27 insertions(+), 33 deletions(-) diff --git a/atom/browser/api/atom_api_dialog.cc b/atom/browser/api/atom_api_dialog.cc index 965b9287835..0a544c56468 100644 --- a/atom/browser/api/atom_api_dialog.cc +++ b/atom/browser/api/atom_api_dialog.cc @@ -66,10 +66,6 @@ void ShowMessageBox(int type, } } -void SetSheetOffset(atom::NativeWindow* window, const double offset) { - window->SetSheetOffset(offset); -} - void ShowOpenDialog(const std::string& title, const base::FilePath& default_path, const file_dialog::Filters& filters, @@ -116,7 +112,6 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("showMessageBox", &ShowMessageBox); dict.SetMethod("showErrorBox", &atom::ShowErrorBox); dict.SetMethod("showOpenDialog", &ShowOpenDialog); - dict.SetMethod("setSheetOffset", &SetSheetOffset); dict.SetMethod("showSaveDialog", &ShowSaveDialog); } diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index fd9dd94458c..07cee2af2d3 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -514,6 +514,10 @@ std::vector Window::GetPosition() { return result; } +void Window::SetSheetOffset(double offset) { + window_->SetSheetOffset(offset); +} + void Window::SetTitle(const std::string& title) { window_->SetTitle(title); } @@ -763,6 +767,7 @@ void Window::BuildPrototype(v8::Isolate* isolate, .SetMethod("center", &Window::Center) .SetMethod("setPosition", &Window::SetPosition) .SetMethod("getPosition", &Window::GetPosition) + .SetMethod("setSheetOffset", &Window::SetSheetOffset) .SetMethod("setTitle", &Window::SetTitle) .SetMethod("getTitle", &Window::GetTitle) .SetMethod("flashFrame", &Window::FlashFrame) diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index d26ff5b3674..0b8f0e3c491 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -110,6 +110,7 @@ class Window : public mate::TrackableObject, std::vector GetMinimumSize(); void SetMaximumSize(int width, int height); std::vector GetMaximumSize(); + void SetSheetOffset(double offset); void SetResizable(bool resizable); bool IsResizable(); void SetMovable(bool movable); diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 37bf8f687ed..091a7b8a3fb 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -201,14 +201,6 @@ gfx::Size NativeWindow::GetContentSize() { return WindowSizeToContentSize(GetSize()); } -void NativeWindow::SetSheetOffset(const double offset) { - sheet_offset_ = offset; -} - -double NativeWindow::GetSheetOffset() { - return sheet_offset_; -} - void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints; @@ -262,6 +254,14 @@ gfx::Size NativeWindow::GetMaximumSize() { return GetSizeConstraints().GetMaximumSize(); } +void NativeWindow::SetSheetOffset(const double offset) { + sheet_offset_ = offset; +} + +double NativeWindow::GetSheetOffset() { + return sheet_offset_; +} + void NativeWindow::SetRepresentedFilename(const std::string& filename) { } diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 877a6d0f745..a28ed10f3cf 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -675,6 +675,17 @@ Returns the title of the native window. **Note:** The title of web page can be different from the title of the native window. +### `win.setSheetOffset(offset)` + +Changes the attachment point for sheets on Mac OS X. By default, sheets are attached +just below the window frame, but you may want to display them beneath a HTML-rendered +toolbar. For example: + +``` +var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); +win.setSheetOffset(toolbarRect.height); +``` + ### `win.flashFrame(flag)` * `flag` Boolean diff --git a/docs/api/dialog.md b/docs/api/dialog.md index f36850f310a..32b8628567a 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -129,19 +129,5 @@ On Mac OS X, dialogs are presented as sheets attached to a window if you provide a `BrowserWindow` reference in the `browserWindow` parameter, or modals if no window is provided. -### `dialog.setSheetOffset(browserWindow, offset)` - -* `browserWindow` BrowserWindow (optional) - -Changes the attachment point for sheets on Mac OS X. By default, sheets are attached -just below the window frame, but you may want to display them beneath a HTML-rendered -toolbar. For example: -``` -const {remote} = require('electron'); -const browserWindow = remote.getCurrentWindow(); - -var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); -remote.dialog.setSheetOffset(browserWindow, toolbarRect.height); - -... show dialog ... -``` +You can call `BrowserWindow.getCurrentWindow().setSheetOffset(offset)` to change +the offset from the window frame where sheets are attached. diff --git a/lib/browser/api/dialog.js b/lib/browser/api/dialog.js index ed7ab063ed8..6669d8cab89 100644 --- a/lib/browser/api/dialog.js +++ b/lib/browser/api/dialog.js @@ -49,10 +49,6 @@ var checkAppInitialized = function () { } module.exports = { - setSheetOffset: function (window, offset) { - return binding.setSheetOffset(window, offset) - }, - showOpenDialog: function (...args) { var prop, properties, value, wrappedCallback checkAppInitialized() From 414245f4d837c3a04b14149903367daa15d894e3 Mon Sep 17 00:00:00 2001 From: Ben Gotow Date: Mon, 18 Apr 2016 22:45:38 -0700 Subject: [PATCH 0531/1265] Keep function placement consistent --- atom/browser/api/atom_api_window.cc | 10 +++++----- atom/browser/native_window.h | 5 ++--- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 07cee2af2d3..2bac6fa808d 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -440,6 +440,10 @@ std::vector Window::GetMaximumSize() { return result; } +void Window::SetSheetOffset(double offset) { + window_->SetSheetOffset(offset); +} + void Window::SetResizable(bool resizable) { window_->SetResizable(resizable); } @@ -514,10 +518,6 @@ std::vector Window::GetPosition() { return result; } -void Window::SetSheetOffset(double offset) { - window_->SetSheetOffset(offset); -} - void Window::SetTitle(const std::string& title) { window_->SetTitle(title); } @@ -750,6 +750,7 @@ void Window::BuildPrototype(v8::Isolate* isolate, .SetMethod("getMinimumSize", &Window::GetMinimumSize) .SetMethod("setMaximumSize", &Window::SetMaximumSize) .SetMethod("getMaximumSize", &Window::GetMaximumSize) + .SetMethod("setSheetOffset", &Window::SetSheetOffset) .SetMethod("setResizable", &Window::SetResizable) .SetMethod("isResizable", &Window::IsResizable) .SetMethod("setMovable", &Window::SetMovable) @@ -767,7 +768,6 @@ void Window::BuildPrototype(v8::Isolate* isolate, .SetMethod("center", &Window::Center) .SetMethod("setPosition", &Window::SetPosition) .SetMethod("getPosition", &Window::GetPosition) - .SetMethod("setSheetOffset", &Window::SetSheetOffset) .SetMethod("setTitle", &Window::SetTitle) .SetMethod("getTitle", &Window::GetTitle) .SetMethod("flashFrame", &Window::FlashFrame) diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index d60ac209d8a..f3acf622231 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -123,6 +123,8 @@ class NativeWindow : public base::SupportsUserData, virtual gfx::Size GetMinimumSize(); virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize(); + virtual void SetSheetOffset(const double offset); + virtual double GetSheetOffset(); virtual void SetResizable(bool resizable) = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; @@ -190,9 +192,6 @@ class NativeWindow : public base::SupportsUserData, gfx::Size GetAspectRatioExtraSize(); void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); - void SetSheetOffset(const double offset); - double GetSheetOffset(); - base::WeakPtr GetWeakPtr() { return weak_factory_.GetWeakPtr(); } From 2d8286515defc2e201fe319768d3dab1fdc30606 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Tue, 19 Apr 2016 10:47:28 +0530 Subject: [PATCH 0532/1265] expose api only on platforms using nss cert database --- atom/browser/api/atom_api_app.cc | 8 ++++++-- atom/browser/api/atom_api_app.h | 13 ++++++++++++- electron.gyp | 3 +++ filenames.gypi | 6 ++++-- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index d6afbb366e0..46402d7f9b2 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -159,13 +159,14 @@ void PassLoginInformation(scoped_refptr login_handler, login_handler->CancelAuth(); } +#if defined(USE_NSS_CERTS) int ImportIntoCertStore( CertificateManagerModel* model, const base::DictionaryValue& options) { std::string file_data, cert_path; base::string16 password; net::CertificateList imported_certs; - int rv; + int rv = -1; options.GetString("clientCertificate", &cert_path); options.GetString("password", &password); @@ -189,6 +190,7 @@ int ImportIntoCertStore( } return rv; } +#endif } // namespace @@ -402,6 +404,7 @@ bool App::MakeSingleInstance( } } +#if defined(USE_NSS_CERTS) void App::ImportClientCertificate( const base::DictionaryValue& options, const net::CompletionCallback& callback) { @@ -429,6 +432,7 @@ void App::OnCertificateManagerModelCreated( *(options.get())); callback.Run(rv); } +#endif mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( v8::Isolate* isolate) { @@ -469,7 +473,7 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( .SetMethod("allowNTLMCredentialsForAllDomains", &App::AllowNTLMCredentialsForAllDomains) .SetMethod("getLocale", &App::GetLocale) -#if defined(OS_LINUX) +#if defined(USE_NSS_CERTS) .SetMethod("importClientCertificate", &App::ImportClientCertificate) #endif .SetMethod("makeSingleInstance", &App::MakeSingleInstance); diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index ce66daedf10..acaa64a3437 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -11,12 +11,15 @@ #include "atom/browser/atom_browser_client.h" #include "atom/browser/browser_observer.h" #include "atom/common/native_mate_converters/callback.h" -#include "chrome/browser/certificate_manager_model.h" #include "chrome/browser/process_singleton.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "native_mate/handle.h" #include "net/base/completion_callback.h" +#if defined(USE_NSS_CERTS) +#include "chrome/browser/certificate_manager_model.h" +#endif + namespace base { class FilePath; } @@ -43,10 +46,12 @@ class App : public AtomBrowserClient::Delegate, int render_process_id, int render_frame_id); +#if defined(USE_NSS_CERTS) void OnCertificateManagerModelCreated( scoped_ptr options, const net::CompletionCallback& callback, scoped_ptr model); +#endif protected: App(); @@ -104,15 +109,21 @@ class App : public AtomBrowserClient::Delegate, bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); std::string GetLocale(); + +#if defined(USE_NSS_CERTS) void ImportClientCertificate(const base::DictionaryValue& options, const net::CompletionCallback& callback); +#endif #if defined(OS_WIN) bool IsAeroGlassEnabled(); #endif scoped_ptr process_singleton_; + +#if defined(USE_NSS_CERTS) scoped_ptr certificate_manager_model_; +#endif DISALLOW_COPY_AND_ASSIGN(App); }; diff --git a/electron.gyp b/electron.gyp index 7a431028f19..11a35490923 100644 --- a/electron.gyp +++ b/electron.gyp @@ -310,6 +310,9 @@ ], }], # OS=="mac" and mas_build==1 ['OS=="linux"', { + 'sources': [ + '<@(lib_sources_nss)', + ], 'link_settings': { 'ldflags': [ # Make binary search for libraries under current directory, so we diff --git a/filenames.gypi b/filenames.gypi index 4de1b366b4f..a1c704c348b 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -390,8 +390,6 @@ 'atom/utility/atom_content_utility_client.h', 'chromium_src/chrome/browser/browser_process.cc', 'chromium_src/chrome/browser/browser_process.h', - 'chromium_src/chrome/browser/certificate_manager_model.cc', - 'chromium_src/chrome/browser/certificate_manager_model.h', 'chromium_src/chrome/browser/chrome_process_finder_win.cc', 'chromium_src/chrome/browser/chrome_process_finder_win.h', 'chromium_src/chrome/browser/chrome_notification_types.h', @@ -519,6 +517,10 @@ '<@(native_mate_files)', '<(SHARED_INTERMEDIATE_DIR)/atom_natives.h', ], + 'lib_sources_nss': [ + 'chromium_src/chrome/browser/certificate_manager_model.cc', + 'chromium_src/chrome/browser/certificate_manager_model.h', + ], 'lib_sources_win': [ 'chromium_src/chrome/browser/ui/views/color_chooser_dialog.cc', 'chromium_src/chrome/browser/ui/views/color_chooser_dialog.h', From bd406ab04678bf6215949fb36c83f24e7d859811 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 19 Apr 2016 16:08:37 +0900 Subject: [PATCH 0533/1265] Update the MAS submission guide --- .../mac-app-store-submission-guide.md | 34 +++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index ec8d8653ca0..bb4a02ba09a 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -4,10 +4,6 @@ Since v0.34.0, Electron allows submitting packaged apps to the Mac App Store (MAS). This guide provides information on: how to submit your app and the limitations of the MAS build. -**Note:** From v0.36.0 there was a bug preventing GPU process to start after -the app being sandboxed, so it is recommended to use v0.35.x before this bug -gets fixed. You can find more about this in [issue #3871][issue-3871]. - **Note:** Submitting an app to Mac App Store requires enrolling [Apple Developer Program][developer-program], which costs money. @@ -43,6 +39,8 @@ First, you need to prepare two entitlements files. com.apple.security.inherit + com.apple.security.temporary-exception.sbpl + (allow mach-lookup (global-name-regex #"^org.chromium.Chromium.rohitfork.[0-9]+$")) ``` @@ -56,6 +54,8 @@ First, you need to prepare two entitlements files. com.apple.security.app-sandbox + com.apple.security.temporary-exception.sbpl + (allow mach-lookup (global-name-regex #"^org.chromium.Chromium.rohitfork.[0-9]+$")) ``` @@ -96,11 +96,32 @@ If you are new to app sandboxing under OS X, you should also read through Apple's [Enabling App Sandbox][enable-app-sandbox] to have a basic idea, then add keys for the permissions needed by your app to the entitlements files. -### Upload Your App and Submit for Review +### Upload Your App After signing your app, you can use Application Loader to upload it to iTunes Connect for processing, making sure you have [created a record][create-record] -before uploading. Then you can [submit your app for review][submit-for-review]. +before uploading. + +### Explain the Usages of `temporary-exception` + +When sandboxing your app there was a `temporary-exception` entry added to the +entitlements, according to the [App Sandbox Temporary Exception +Entitlements][temporary-exception] documentation, you have to explain why this +entry is needed: + +> Note: If you request a temporary-exception entitlement, be sure to follow the +guidance regarding entitlements provided on the iTunes Connect website. In +particular, identify the entitlement and corresponding issue number in the App +Sandbox Entitlement Usage Information section in iTunes Connect and explain why +your app needs the exception. + +You may explain that your app is built upon Chromium browser, which uses Mach +port for its multi-process architecture. But there is still probability that +your app failed the review because of this. + +### Submit Your App for Review + +After these steps, you can [submit your app for review][submit-for-review]. ## Limitations of MAS Build @@ -165,3 +186,4 @@ ERN)][ern-tutorial]. [app-sandboxing]: https://developer.apple.com/app-sandboxing/ [issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ +[temporary-exception]: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html From fd6747483aacf229916c941e4ea59e898650c632 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 19 Apr 2016 20:27:58 +0900 Subject: [PATCH 0534/1265] Update the codesign code for latest Xcode --- .../mac-app-store-submission-guide.md | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index bb4a02ba09a..c80885f5a56 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -39,8 +39,6 @@ First, you need to prepare two entitlements files. com.apple.security.inherit - com.apple.security.temporary-exception.sbpl - (allow mach-lookup (global-name-regex #"^org.chromium.Chromium.rohitfork.[0-9]+$")) ``` @@ -77,17 +75,18 @@ INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)" FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" -if [ -d "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" ]; then - # Signing a non-MAS build. - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Mantle.framework/Versions/A" - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/ReactiveCocoa.framework/Versions/A" - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" -fi -codesign -fs "$APP_KEY" --entitlements parent.plist "$APP_PATH" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$APP_PATH/Contents/MacOS/$APP" +codesign -s "$APP_KEY" -f --entitlements parent.plist "$APP_PATH" productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH" ``` From 58dfad4d016f6f23129dd18b6fbeb900d2bafab4 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Tue, 19 Apr 2016 18:12:05 +0530 Subject: [PATCH 0535/1265] devtools: allow opening in specified dock state --- atom/browser/api/atom_api_web_contents.cc | 14 ++++++++++---- docs/api/web-contents.md | 3 ++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index abad4add4fb..0eddd03399c 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -848,14 +848,20 @@ void WebContents::OpenDevTools(mate::Arguments* args) { if (type_ == REMOTE) return; - bool detach = false; + std::string state; if (type_ == WEB_VIEW) { - detach = true; + state = "detach"; } else if (args && args->Length() == 1) { + bool detach = false; mate::Dictionary options; - args->GetNext(&options) && options.Get("detach", &detach); + if (args->GetNext(&options)) { + options.Get("mode", &state); + options.Get("detach", &detach); + if (state.empty() && detach) + state = "detach"; + } } - managed_web_contents()->SetCanDock(!detach); + managed_web_contents()->SetDockState(state); managed_web_contents()->ShowDevTools(); } diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 8fc7a959f69..46b7ec167b9 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -647,7 +647,8 @@ Removes the specified path from DevTools workspace. ### `webContents.openDevTools([options])` * `options` Object (optional) - * `detach` Boolean - opens DevTools in a new window + * `mode` String - Opens the devtools with specified dock state, can be one of + "right", "bottom", "undocked", "detach". Defaults to last used dock state. Opens the devtools. From 838cf0ffdc02bef70ca51ffe4678b344797faaf8 Mon Sep 17 00:00:00 2001 From: rmcdonald Date: Tue, 19 Apr 2016 09:31:04 -0700 Subject: [PATCH 0536/1265] Correct transposition errors by changing xfvb to xvfb --- docs/tutorial/testing-on-headless-ci.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/tutorial/testing-on-headless-ci.md b/docs/tutorial/testing-on-headless-ci.md index ec1f4635c90..f9090a6cbd7 100644 --- a/docs/tutorial/testing-on-headless-ci.md +++ b/docs/tutorial/testing-on-headless-ci.md @@ -18,9 +18,9 @@ Then, create a virtual xvfb screen and export an environment variable called DISPLAY that points to it. Chromium in Electron will automatically look for `$DISPLAY`, so no further configuration of your app is required. This step can be automated with Paul Betts's -[xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe): Prepend your test -commands with `xfvb-maybe` and the little tool will automatically configure -xfvb, if required by the current system. On Windows or Mac OS X, it will simply +[xvfb-maybe](https://github.com/paulcbetts/xvfb-maybe): Prepend your test +commands with `xvfb-maybe` and the little tool will automatically configure +xvfb, if required by the current system. On Windows or Mac OS X, it will simply do nothing. ``` @@ -47,7 +47,7 @@ install: ### Jenkins -For Jenkins, a [Xfvb plugin is available](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). +For Jenkins, a [Xvfb plugin is available](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). ### Circle CI From 8f04dd1b9ce4f748feb3c7e090d42e1fca6cfcf0 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Tue, 19 Apr 2016 09:46:48 -0700 Subject: [PATCH 0537/1265] remove the git --- docs/development/source-code-directory-structure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/source-code-directory-structure.md b/docs/development/source-code-directory-structure.md index 1c9e8c2b774..b2672def654 100644 --- a/docs/development/source-code-directory-structure.md +++ b/docs/development/source-code-directory-structure.md @@ -87,5 +87,5 @@ in your `~/.gitconfig` file: ``` [alias] - su = git submodule update --init --recursive + su = submodule update --init --recursive ``` From 02c8c58c0b71b5af21fc193aba6a7c997448dcc1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 19 Apr 2016 12:47:05 -0400 Subject: [PATCH 0538/1265] Fixed docs sample code programming error for DownloadItem --- docs/api/download-item.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/api/download-item.md b/docs/api/download-item.md index 756353b8ba3..f117ffc57a7 100644 --- a/docs/api/download-item.md +++ b/docs/api/download-item.md @@ -22,6 +22,7 @@ win.webContents.session.on('will-download', function(event, item, webContents) { console.log("Download is cancelled or interrupted that can't be resumed"); } }); +}); ``` ## Events From 18f5fcde60007f6b22878f08de3022405a9e5203 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 20 Apr 2016 09:18:50 +0900 Subject: [PATCH 0539/1265] Fix some coding style issues --- atom/browser/native_window.cc | 1 + atom/browser/native_window_mac.mm | 6 +++--- atom/browser/net/atom_network_delegate.h | 1 + docs/api/dialog.md | 1 - 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 091a7b8a3fb..2379bdd053c 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -54,6 +54,7 @@ NativeWindow::NativeWindow( enable_larger_than_screen_(false), is_closed_(false), has_dialog_attached_(false), + sheet_offset_(0.0), aspect_ratio_(0.0), inspectable_web_contents_(inspectable_web_contents), weak_factory_(this) { diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index c35c177ac29..5f980fed62c 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -243,13 +243,13 @@ bool ScopedDisableResize::disable_resize_ = false; return NO; } -- (NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect { - NSView * view = window.contentView; +- (NSRect)window:(NSWindow*)window + willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { + NSView* view = window.contentView; rect.origin.y = view.frame.size.height - shell_->GetSheetOffset(); return rect; } - @end @interface AtomNSWindow : NSWindow { diff --git a/atom/browser/net/atom_network_delegate.h b/atom/browser/net/atom_network_delegate.h index 92ea6415e69..701a953c265 100644 --- a/atom/browser/net/atom_network_delegate.h +++ b/atom/browser/net/atom_network_delegate.h @@ -121,6 +121,7 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate { std::map callbacks_; base::Lock lock_; + // Client id for devtools network emulation. std::string client_id_; diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 32b8628567a..1cea9da119a 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -122,7 +122,6 @@ it is usually used to report errors in early stage of startup. If called before the app `ready`event on Linux, the message will be emitted to stderr, and no GUI dialog will appear. - ## Sheets On Mac OS X, dialogs are presented as sheets attached to a window if you provide From b80272dbb424aaaec03b53f265b339b45453e6b0 Mon Sep 17 00:00:00 2001 From: Adam Drago Date: Tue, 19 Apr 2016 18:12:37 -0700 Subject: [PATCH 0540/1265] Add note for OS X about using `role` on MenuItem --- docs/api/menu-item.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index fb12e251153..0029ba14dd4 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -61,6 +61,8 @@ On OS X `role` can also have following additional values: * `help` - The submenu is a "Help" menu * `services` - The submenu is a "Services" menu +When specifying `role` on OS X, `label` and `accelerator` are the only options that will affect the MenuItem. All other options will be ignored. + ## Instance Properties The following properties (and no others) can be updated on an existing `MenuItem`: From 942971b01afd6773fce41e5ca3d49270cf88b5ce Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Tue, 19 Apr 2016 19:20:59 -0700 Subject: [PATCH 0541/1265] Fix linting errors. --- atom/browser/api/atom_api_web_contents.cc | 2 +- atom/browser/api/atom_api_web_contents.h | 27 +++++++++++++---------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index c6943d506e6..7c7e5896abc 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -816,7 +816,7 @@ base::string16 WebContents::GetTitle() const { bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } - + bool WebContents::IsLoadingMainFrame() const { return is_loading_main_frame_; } diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 7e4bd693536..292ec096088 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -224,18 +224,21 @@ class WebContents : public mate::TrackableObject, int error_code, const base::string16& error_description, bool was_ignored_by_handler) override; - void DidFailProvisionalLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) override; - void DidStartProvisionalLoadForFrame(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override; - void DidCommitProvisionalLoadForFrame(content::RenderFrameHost* render_frame_host, - const GURL& url, - ui::PageTransition transition_type) override; + void DidFailProvisionalLoad( + content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description, + bool was_ignored_by_handler) override; + void DidStartProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + bool is_error_page, + bool is_iframe_srcdoc) override; + void DidCommitProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& url, + ui::PageTransition transition_type) override; void DidStartLoading() override; void DidStopLoading() override; void DidGetResourceResponseStart( From 7468118df55b98f7ee6e13f2462bd5d48d00493c Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Wed, 20 Apr 2016 10:26:31 +0800 Subject: [PATCH 0542/1265] Update screen.md --- docs-translations/zh-CN/api/screen.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/zh-CN/api/screen.md b/docs-translations/zh-CN/api/screen.md index 0de4c975afb..93b61a46078 100644 --- a/docs-translations/zh-CN/api/screen.md +++ b/docs-translations/zh-CN/api/screen.md @@ -23,7 +23,7 @@ app.on('ready', function() { }); ``` -另一个例子,在次页外创建一个窗口: +另一个例子,在此页外创建一个窗口: ```javascript const electron = require('electron'); @@ -132,4 +132,4 @@ app.on('ready', function() { * `width` Integer * `height` Integer -返回与提供的边界范围最密切相关的 display. \ No newline at end of file +返回与提供的边界范围最密切相关的 display. From 16b54e15025c4d5f11e31c9fa0ff38d057aa4407 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Wed, 20 Apr 2016 10:37:41 +0800 Subject: [PATCH 0543/1265] Update screen.md --- docs-translations/zh-CN/api/screen.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/api/screen.md b/docs-translations/zh-CN/api/screen.md index 93b61a46078..bd4aec8b370 100644 --- a/docs-translations/zh-CN/api/screen.md +++ b/docs-translations/zh-CN/api/screen.md @@ -54,7 +54,7 @@ app.on('ready', function() { ## `Display` 对象 -`Display` 对象表示了物力方式连接系统. 一个伪造的 `Display` 或许存在于一个无头系统中,或者一个 `Display` 相当于一个远程的、虚拟的 display. +`Display` 对象表示一个连接到系统的物理显示. 一个虚设的 `Display` 或许存在于一个`headless system`中,或者一个 `Display` 对应一个远程的、虚拟的display. * `display` object * `id` Integer - 与display 相关的唯一性标志. From 57bdbd818544f3006d0ca289fedba6cf2a1bd40b Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Wed, 20 Apr 2016 10:39:47 +0800 Subject: [PATCH 0544/1265] Update download-item.md --- docs-translations/zh-CN/api/download-item.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/api/download-item.md b/docs-translations/zh-CN/api/download-item.md index a8ed266479d..e869e8f3057 100644 --- a/docs-translations/zh-CN/api/download-item.md +++ b/docs-translations/zh-CN/api/download-item.md @@ -1,7 +1,7 @@ # DownloadItem `DownloadItem`(下载项)是一个在Electron中展示下载项的 -[EventEmitter](https://github.com/nodejs/node/blob/master/doc/api/events.markdown)(nodejs)。 +[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)。 它被用于`Session`模块中的`will-download`事件,允许用户去控制下载项。 ```javascript From bdde5fd7adf33ede7f6f0aa8d55bdf29003fd873 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Wed, 20 Apr 2016 10:58:32 +0800 Subject: [PATCH 0545/1265] Update screen.md --- docs-translations/zh-CN/api/screen.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/api/screen.md b/docs-translations/zh-CN/api/screen.md index bd4aec8b370..3919ebabb77 100644 --- a/docs-translations/zh-CN/api/screen.md +++ b/docs-translations/zh-CN/api/screen.md @@ -54,7 +54,7 @@ app.on('ready', function() { ## `Display` 对象 -`Display` 对象表示一个连接到系统的物理显示. 一个虚设的 `Display` 或许存在于一个`headless system`中,或者一个 `Display` 对应一个远程的、虚拟的display. +`Display` 对象表示一个连接到系统的物理显示. 一个虚设的 `Display` 或许存在于一个无头系统(headless system)中,或者一个 `Display` 对应一个远程的、虚拟的display. * `display` object * `id` Integer - 与display 相关的唯一性标志. From 794d1207547dd422dc4791ab09deaaf7283155bf Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 20 Apr 2016 08:45:49 +0530 Subject: [PATCH 0546/1265] rename importClientCertificate => importCertificate --- atom/browser/api/atom_api_app.cc | 6 +++--- atom/browser/api/atom_api_app.h | 4 ++-- docs/api/app.md | 12 ++++++++++++ spec/api-app-spec.js | 6 +++--- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 46402d7f9b2..9d0aa792e60 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -167,7 +167,7 @@ int ImportIntoCertStore( base::string16 password; net::CertificateList imported_certs; int rv = -1; - options.GetString("clientCertificate", &cert_path); + options.GetString("certificate", &cert_path); options.GetString("password", &password); if (!cert_path.empty()) { @@ -405,7 +405,7 @@ bool App::MakeSingleInstance( } #if defined(USE_NSS_CERTS) -void App::ImportClientCertificate( +void App::ImportCertificate( const base::DictionaryValue& options, const net::CompletionCallback& callback) { auto browser_context = AtomBrowserMainParts::Get()->browser_context(); @@ -474,7 +474,7 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( &App::AllowNTLMCredentialsForAllDomains) .SetMethod("getLocale", &App::GetLocale) #if defined(USE_NSS_CERTS) - .SetMethod("importClientCertificate", &App::ImportClientCertificate) + .SetMethod("importCertificate", &App::ImportCertificate) #endif .SetMethod("makeSingleInstance", &App::MakeSingleInstance); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index acaa64a3437..d4102521c0b 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -111,8 +111,8 @@ class App : public AtomBrowserClient::Delegate, std::string GetLocale(); #if defined(USE_NSS_CERTS) - void ImportClientCertificate(const base::DictionaryValue& options, - const net::CompletionCallback& callback); + void ImportCertificate(const base::DictionaryValue& options, + const net::CompletionCallback& callback); #endif #if defined(OS_WIN) diff --git a/docs/api/app.md b/docs/api/app.md index 84eeed51d6c..c8ddb47bd31 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -514,6 +514,18 @@ if (browserOptions.transparent) { This method returns `true` if the system is in Dark Mode, and `false` otherwise. +### `app.importCertificate(options, callback)` _LINUX_ + +* `options` Object + * `certificate` String - Path for the pkcs12 file. + * `password` String - Passphrase for the certificate. +* `callback` Function + * `result` Integer - Result of import. + +Imports the certificate in pkcs12 format into the platform certificate store. +`callback` is called with the `result` of import operation, a value of `0` indicates +success while any other value indicates failure according to chromium [net_error_list](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h). + ### `app.commandLine.appendSwitch(switch[, value])` Append a switch (with optional `value`) to Chromium's command line. diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 8923d2d214f..1c20ef8e452 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -89,7 +89,7 @@ describe('app module', function () { }) }) - describe('app.importClientCertificate', function () { + describe('app.importCertificate', function () { if (process.platform !== 'linux') return @@ -124,7 +124,7 @@ describe('app module', function () { it('can import certificate into platform cert store', function (done) { let options = { - clientCertificate: path.join(certPath, 'client.p12'), + certificate: path.join(certPath, 'client.p12'), password: 'electron' } @@ -143,7 +143,7 @@ describe('app module', function () { callback(list[0]) }) - app.importClientCertificate(options, function (result) { + app.importCertificate(options, function (result) { assert(!result) server.listen(0, '127.0.0.1', function () { var port = server.address().port From a3e8591a41b98fa0cd8a9cff9a344bb300bc9db7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 20 Apr 2016 13:34:30 +0900 Subject: [PATCH 0547/1265] Update brightray for #5208 --- vendor/brightray | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/brightray b/vendor/brightray index bc9c496a618..8dbaeed37b9 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit bc9c496a6185e37e792c10bfc5b49ea779b27cd3 +Subproject commit 8dbaeed37b9c4fb8ae985670b142f659bb265fb4 From d3e879cd7f3cc7093ebc9246eaccd2b5857faebb Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Tue, 19 Apr 2016 22:05:09 -0700 Subject: [PATCH 0548/1265] Change `WebContents::IsLoadingMainFrame` to compare SiteInstances (per @deepak1556's recommendation) Also updates tests to cover the situation where navigating between pages from the same potential "site" and adds generalized tests for `isLoadingMainFrame()`. --- atom/browser/api/atom_api_web_contents.cc | 34 +++------- atom/browser/api/atom_api_web_contents.h | 23 ++----- spec/api-browser-window-spec.js | 76 +++++++++++++++++------ 3 files changed, 69 insertions(+), 64 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 7c7e5896abc..e39fa985e26 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -220,8 +220,7 @@ WebContents::WebContents(content::WebContents* web_contents) embedder_(nullptr), type_(REMOTE), request_id_(0), - background_throttling_(true), - is_loading_main_frame_(false) { + background_throttling_(true) { AttachAsUserData(web_contents); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); } @@ -230,8 +229,7 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options) : embedder_(nullptr), request_id_(0), - background_throttling_(true), - is_loading_main_frame_(false) { + background_throttling_(true) { // Read options. options.Get("backgroundThrottling", &background_throttling_); @@ -545,32 +543,12 @@ void WebContents::DocumentLoadedInFrame( void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); - if (is_main_frame) - is_loading_main_frame_ = false; - Emit("did-frame-finish-load", is_main_frame); if (is_main_frame) Emit("did-finish-load"); } -void WebContents::DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, - bool is_error_page, - bool is_iframe_srcdoc) { - if (!render_frame_host->GetParent()) - is_loading_main_frame_ = true; -} - -void WebContents::DidCommitProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, - ui::PageTransition transition_type) { - if (!render_frame_host->GetParent()) - is_loading_main_frame_ = true; -} - void WebContents::DidFailProvisionalLoad( content::RenderFrameHost* render_frame_host, const GURL& url, @@ -578,8 +556,6 @@ void WebContents::DidFailProvisionalLoad( const base::string16& description, bool was_ignored_by_handler) { bool is_main_frame = !render_frame_host->GetParent(); - if (is_main_frame) - is_loading_main_frame_ = false; Emit("did-fail-provisional-load", code, description, url, is_main_frame); Emit("did-fail-load", code, description, url, is_main_frame); } @@ -818,7 +794,11 @@ bool WebContents::IsLoading() const { } bool WebContents::IsLoadingMainFrame() const { - return is_loading_main_frame_; + // Comparing site instances works because Electron always creates a new site + // instance when navigating, regardless of origin. See AtomBrowserClient. + return (web_contents()->GetLastCommittedURL().is_empty() || + web_contents()->GetSiteInstance() != + web_contents()->GetPendingSiteInstance()) && IsLoading(); } bool WebContents::IsWaitingForResponse() const { diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index 292ec096088..bc2d4106f5f 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -224,21 +224,11 @@ class WebContents : public mate::TrackableObject, int error_code, const base::string16& error_description, bool was_ignored_by_handler) override; - void DidFailProvisionalLoad( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) override; - void DidStartProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override; - void DidCommitProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, - ui::PageTransition transition_type) override; + void DidFailProvisionalLoad(content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description, + bool was_ignored_by_handler) override; void DidStartLoading() override; void DidStopLoading() override; void DidGetResourceResponseStart( @@ -313,9 +303,6 @@ class WebContents : public mate::TrackableObject, // Whether background throttling is disabled. bool background_throttling_; - // Whether the main frame (not just a sub-frame) is currently loading. - bool is_loading_main_frame_; - DISALLOW_COPY_AND_ASSIGN(WebContents); }; diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 26d4ff4af35..1110269e5de 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -19,6 +19,23 @@ const isCI = remote.getGlobal('isCi') describe('browser-window module', function () { var fixtures = path.resolve(__dirname, 'fixtures') var w = null + var server + + before(function (done) { + server = http.createServer(function (req, res) { + function respond() { res.end(''); } + setTimeout(respond, req.url.includes('slow') ? 200 : 0) + }); + server.listen(0, '127.0.0.1', function () { + server.url = 'http://127.0.0.1:' + server.address().port + done() + }) + }) + + after(function () { + server.close() + server = null + }) beforeEach(function () { if (w != null) { @@ -635,6 +652,44 @@ describe('browser-window module', function () { assert.equal(w.isResizable(), true) }) }) + + describe('loading main frame state', function () { + it('is true when the main frame is loading', function (done) { + w.webContents.on('did-start-loading', function() { + assert.equal(w.webContents.isLoadingMainFrame(), true) + done() + }) + w.webContents.loadURL(server.url) + }) + + it('is false when only a subframe is loading', function (done) { + w.webContents.once('did-finish-load', function() { + assert.equal(w.webContents.isLoadingMainFrame(), false) + w.webContents.on('did-start-loading', function() { + assert.equal(w.webContents.isLoadingMainFrame(), false) + done() + }) + w.webContents.executeJavaScript(` + var iframe = document.createElement('iframe') + iframe.src = '${server.url}/page2' + document.body.appendChild(iframe) + `) + }) + w.webContents.loadURL(server.url) + }) + + it('is true when navigating to pages from the same origin', function (done) { + w.webContents.once('did-finish-load', function() { + assert.equal(w.webContents.isLoadingMainFrame(), false) + w.webContents.on('did-start-loading', function() { + assert.equal(w.webContents.isLoadingMainFrame(), true) + done() + }) + w.webContents.loadURL(`${server.url}/page2`) + }) + w.webContents.loadURL(server.url) + }) + }) }) describe('window states (excluding Linux)', function () { @@ -786,14 +841,6 @@ describe('browser-window module', function () { describe('window.webContents.executeJavaScript', function () { var expected = 'hello, world!' var code = '(() => "' + expected + '")()' - var server - - afterEach(function () { - if (server) { - server.close() - server = null - } - }) it('doesnt throw when no calback is provided', function () { const result = ipcRenderer.sendSync('executeJavaScript', code, false) @@ -809,21 +856,11 @@ describe('browser-window module', function () { }) it('works after page load and during subframe load', function (done) { - var url - // a slow server, guaranteeing time to execute code during loading - server = http.createServer(function (req, res) { - setTimeout(function() { res.end('') }, 200) - }); - server.listen(0, '127.0.0.1', function () { - url = 'http://127.0.0.1:' + server.address().port - w.loadURL('file://' + path.join(fixtures, 'pages', 'base-page.html')) - }) - w.webContents.once('did-finish-load', function() { // initiate a sub-frame load, then try and execute script during it w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') - iframe.src = '${url}' + iframe.src = '${server.url}/slow' document.body.appendChild(iframe) `, function() { w.webContents.executeJavaScript(`console.log('hello')`, function() { @@ -831,6 +868,7 @@ describe('browser-window module', function () { }) }) }) + w.loadURL(server.url) }) }) From ff1b7d18f6499b73803ccee69037fb3b4b8bebf4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 20 Apr 2016 14:26:49 +0900 Subject: [PATCH 0549/1265] Cleanup the code determining value's type --- lib/browser/rpc-server.js | 59 +++++++++++++++----------------------- lib/renderer/api/remote.js | 22 +++++++------- 2 files changed, 35 insertions(+), 46 deletions(-) diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index 4603ba332c2..d512cbabf1c 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -50,50 +50,37 @@ let getObjectPrototype = function (object) { } // Convert a real value into meta data. -var valueToMeta = function (sender, value, optimizeSimpleObject) { - var el, i, len, meta - if (optimizeSimpleObject == null) { - optimizeSimpleObject = false - } - meta = { - type: typeof value - } +let valueToMeta = function (sender, value, optimizeSimpleObject = false) { + // Determine the type of value. + let meta = { type: typeof value } if (Buffer.isBuffer(value)) { meta.type = 'buffer' - } - if (value === null) { + } else if (value === null) { meta.type = 'value' - } - if (Array.isArray(value)) { + } else if (Array.isArray(value)) { meta.type = 'array' - } - if (value instanceof Error) { + } else if (value instanceof Error) { meta.type = 'error' - } - if (value instanceof Date) { + } else if (value instanceof Date) { meta.type = 'date' - } - if ((value != null ? value.constructor.name : void 0) === 'Promise') { - meta.type = 'promise' - } - - // Treat simple objects as value. - if (optimizeSimpleObject && meta.type === 'object' && v8Util.getHiddenValue(value, 'simple')) { - meta.type = 'value' - } - - // Treat the arguments object as array. - if (meta.type === 'object' && (value.hasOwnProperty('callee')) && (value.length != null)) { - meta.type = 'array' - } - if (meta.type === 'array') { - meta.members = [] - for (i = 0, len = value.length; i < len; i++) { - el = value[i] - meta.members.push(valueToMeta(sender, el)) + } else if (meta.type === 'object') { + // Recognize certain types of objects. + if (value.constructor != null && value.constructor.name === 'Promise') { + meta.type = 'promise' + } else if (value.hasOwnProperty('callee') && value.length != null) { + // Treat the arguments object as array. + meta.type = 'array' + } else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) { + // Treat simple objects as value. + meta.type = 'value' } + } + + // Fill the meta object according to value's type. + if (meta.type === 'array') { + meta.members = value.map((el) => valueToMeta(sender, el)) } else if (meta.type === 'object' || meta.type === 'function') { - meta.name = value.constructor.name + meta.name = value.constructor ? value.constructor.name : '' // Reference the original value if it's an object, because when it's // passed to renderer we would assume the renderer keeps a reference of diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 8865c33c277..d15ebd717ec 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -45,17 +45,19 @@ var wrapArgs = function (args, visited) { type: 'date', value: value.getTime() } - } else if ((value != null ? value.constructor.name : void 0) === 'Promise') { - return { - type: 'promise', - then: valueToMeta(function (v) { value.then(v) }) - } - } else if ((value != null) && typeof value === 'object' && v8Util.getHiddenValue(value, 'atomId')) { - return { - type: 'remote-object', - id: v8Util.getHiddenValue(value, 'atomId') - } } else if ((value != null) && typeof value === 'object') { + if (value.constructor != null && value.constructor.name === 'Promise') { + return { + type: 'promise', + then: valueToMeta(function (v) { value.then(v) }) + } + } else if (v8Util.getHiddenValue(value, 'atomId')) { + return { + type: 'remote-object', + id: v8Util.getHiddenValue(value, 'atomId') + } + } + ret = { type: 'object', name: value.constructor.name, From 680652d01c4fc29d2b3315043632d11743cd9d5f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 20 Apr 2016 14:32:32 +0900 Subject: [PATCH 0550/1265] buffer, null, array etc. all belong to object --- lib/browser/rpc-server.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index d512cbabf1c..ca193b4115e 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -53,19 +53,19 @@ let getObjectPrototype = function (object) { let valueToMeta = function (sender, value, optimizeSimpleObject = false) { // Determine the type of value. let meta = { type: typeof value } - if (Buffer.isBuffer(value)) { - meta.type = 'buffer' - } else if (value === null) { - meta.type = 'value' - } else if (Array.isArray(value)) { - meta.type = 'array' - } else if (value instanceof Error) { - meta.type = 'error' - } else if (value instanceof Date) { - meta.type = 'date' - } else if (meta.type === 'object') { + if (meta.type === 'object') { // Recognize certain types of objects. - if (value.constructor != null && value.constructor.name === 'Promise') { + if (value === null) { + meta.type = 'value' + } else if (Buffer.isBuffer(value)) { + meta.type = 'buffer' + } else if (Array.isArray(value)) { + meta.type = 'array' + } else if (value instanceof Error) { + meta.type = 'error' + } else if (value instanceof Date) { + meta.type = 'date' + } else if (value.constructor != null && value.constructor.name === 'Promise') { meta.type = 'promise' } else if (value.hasOwnProperty('callee') && value.length != null) { // Treat the arguments object as array. From dc8fc7c079ec0eec416eedb0bfd54b68de42b1b8 Mon Sep 17 00:00:00 2001 From: Rob Brackett Date: Tue, 19 Apr 2016 23:27:22 -0700 Subject: [PATCH 0551/1265] :memo: Add English docs for `webContents.isLoadingMainFrame()` [ci skip] --- docs/api/web-contents.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 8fc7a959f69..cb0998804a5 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -353,6 +353,10 @@ Returns the title of the current web page. Returns whether web page is still loading resources. +### `webContents.isLoadingMainFrame()` + +Returns whether the main frame (and not just iframes or frames within it) is still loading. + ### `webContents.isWaitingForResponse()` Returns whether the web page is waiting for a first-response from the main From 720fbc1003a45bbcfb9bf6686e3492b767f51b32 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 20 Apr 2016 18:45:07 +0900 Subject: [PATCH 0552/1265] :memo: Update Korean docs as upstream * Update docs * Small fixes [ci skip] --- docs-translations/ko-KR/README.md | 3 +- docs-translations/ko-KR/api/app.md | 13 +++++ docs-translations/ko-KR/api/browser-window.md | 13 ++++- .../ko-KR/api/chrome-command-line-switches.md | 4 -- .../ko-KR/api/desktop-capturer.md | 1 + docs-translations/ko-KR/api/dialog.md | 18 ++++-- docs-translations/ko-KR/api/download-item.md | 1 + docs-translations/ko-KR/api/menu-item.md | 3 + docs-translations/ko-KR/api/menu.md | 2 +- docs-translations/ko-KR/api/screen.md | 3 +- docs-translations/ko-KR/api/session.md | 2 +- docs-translations/ko-KR/api/shell.md | 4 +- docs-translations/ko-KR/api/web-contents.md | 3 + docs-translations/ko-KR/api/web-view-tag.md | 47 +++++++++++++--- .../source-code-directory-structure.md | 27 +++++++++ .../mac-app-store-submission-guide.md | 55 +++++++++++++------ .../ko-KR/tutorial/supported-platforms.md | 2 +- .../ko-KR/tutorial/testing-on-headless-ci.md | 8 +-- 18 files changed, 160 insertions(+), 49 deletions(-) diff --git a/docs-translations/ko-KR/README.md b/docs-translations/ko-KR/README.md index f6b15879a64..717bfd5ef30 100644 --- a/docs-translations/ko-KR/README.md +++ b/docs-translations/ko-KR/README.md @@ -93,4 +93,5 @@ Electron에 대해 자주 묻는 질문이 있습니다. 이슈를 생성하기 * [빌드 설명서 (OS X)](development/build-instructions-osx.md) * [빌드 설명서 (Windows)](development/build-instructions-windows.md) * [빌드 설명서 (Linux)](development/build-instructions-linux.md) -* [디버거에서 디버그 심볼 서버 설정](development/setting-up-symbol-server.md) +* [디버그 설명서 (Windows)](development/debug-instructions-windows.md) +* [디버거 심볼 서버 설정](development/setting-up-symbol-server.md) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 8e734f2f415..ff6b4640ad2 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -521,6 +521,19 @@ if (browserOptions.transparent) { 이 메서드는 시스템이 다크 모드 상태인 경우 `true`를 반환하고 아닐 경우 `false`를 반환합니다. +### `app.importCertificate(options, callback)` _LINUX_ + +* `options` Object + * `certificate` String - pkcs12 파일의 위치. + * `password` String - 인증서의 암호. +* `callback` Function + * `result` Integer - 가져오기의 결과. + +pkcs12 형식으로된 인증서를 플랫폼 인증서 저장소로 가져옵니다. `callback`은 가져오기의 +결과를 포함하는 `result` 객체를 포함하여 호출됩니다. 값이 `0` 일 경우 성공을 의미하며 +다른 값은 모두 Chrominum의 [net_error_list](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h)에 +따라 실패를 의미합니다. + ### `app.commandLine.appendSwitch(switch[, value])` Chrominum의 명령줄에 스위치를 추가합니다. `value`는 추가적인 값을 뜻하며 옵션입니다. diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 6f10274850d..9ba61bea57f 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -670,6 +670,17 @@ var win = new BrowserWindow({ width: 800, height: 600 }); **참고:** 웹 페이지의 제목과 네이티브 윈도우의 제목은 서로 다를 수 있습니다. +### `win.setSheetOffset(offset)` _OS X_ + +Mac OS X에서 시트를 부착할 위치를 지정합니다. 기본적으로 시트는 윈도우의 프레임 바로 +아래의 위치에 부착됩니다. 아마도 이 기능은 보통 다음과 같이 HTML 렌더링된 툴바 밑에 +표시하기 위해 사용할 것입니다: + +```javascript +var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); +win.setSheetOffset(toolbarRect.height); +``` + ### `win.flashFrame(flag)` * `flag` Boolean @@ -900,4 +911,4 @@ Linux 플랫폼에선 Unity 데스크톱 환경만 지원합니다. 그리고 윈도우에서 일어나는 모든 마우스 이벤트를 무시합니다. -[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=576 diff --git a/docs-translations/ko-KR/api/chrome-command-line-switches.md b/docs-translations/ko-KR/api/chrome-command-line-switches.md index a9f149c96a5..babddd32755 100644 --- a/docs-translations/ko-KR/api/chrome-command-line-switches.md +++ b/docs-translations/ko-KR/api/chrome-command-line-switches.md @@ -15,10 +15,6 @@ app.on('ready', function() { }); ``` -## --client-certificate=`path` - -`path`를 클라이언트 인증서로 설정합니다. - ## --ignore-connections-limit=`domains` `domains` 리스트(`,`로 구분)의 연결 제한을 무시합니다. diff --git a/docs-translations/ko-KR/api/desktop-capturer.md b/docs-translations/ko-KR/api/desktop-capturer.md index 5a531bf44ab..534b487f772 100644 --- a/docs-translations/ko-KR/api/desktop-capturer.md +++ b/docs-translations/ko-KR/api/desktop-capturer.md @@ -65,6 +65,7 @@ function getUserMediaError(e) { `sources`는 `Source` 객체의 배열입니다. 각 `Source`는 캡쳐된 화면과 독립적인 윈도우를 표현합니다. 그리고 다음과 같은 속성을 가지고 있습니다: + * `id` String - `navigator.webkitGetUserMedia` API에서 사용할 수 있는 캡쳐된 윈도우 또는 화면의 id입니다. 포맷은 `window:XX` 또는 `screen:XX`로 표현되며 `XX` 는 무작위로 생성된 숫자입니다. diff --git a/docs-translations/ko-KR/api/dialog.md b/docs-translations/ko-KR/api/dialog.md index f23bd333f6e..cbb1afc71ae 100644 --- a/docs-translations/ko-KR/api/dialog.md +++ b/docs-translations/ko-KR/api/dialog.md @@ -19,9 +19,6 @@ console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', ' const dialog = require('electron').remote.dialog; ``` -**OS X 참고**: 대화 상자를 시트처럼 보여지게 하려면 `browserWindow` 인자에 -`BrowserWindow` 객체의 참조를 제공하면 됩니다. - ## Methods `dialog` 모듈은 다음과 같은 메서드를 가지고 있습니다: @@ -116,7 +113,7 @@ const dialog = require('electron').remote.dialog; 대화 상자를 표시합니다. `browserWindow`를 지정하면 대화 상자가 완전히 닫힐 때까지 지정한 창을 사용할 수 없습니다. 완료 시 유저가 선택한 버튼의 인덱스를 반환합니다. -역주: 부정을 표현하는 "아니오", "취소"와 같은 한글 단어는 지원되지 않습니다. 만약 +**역주:** 부정을 표현하는 "아니오", "취소"와 같은 한글 단어는 지원되지 않습니다. 만약 OS X 또는 Windows에서 "확인", "취소"와 같은 순서로 버튼을 지정하게 될 때 Alt + f4로 해당 대화 상자를 끄게 되면 "확인"을 누른 것으로 판단되어 버립니다. 이를 해결하려면 "Cancel"을 대신 사용하거나 BrowserWindow API를 사용하여 대화 상자를 직접 구현해야 @@ -130,4 +127,15 @@ OS X 또는 Windows에서 "확인", "취소"와 같은 순서로 버튼을 지 에러 메시지를 보여주는 대화 상자를 표시합니다. 이 API는 `app` 모듈의 `ready` 이벤트가 발생하기 전에 사용할 수 있습니다. 이 메서드는 -보통 어플리케이션이 시작되기 전에 특정한 에러를 표시하기 위해 사용됩니다. +보통 어플리케이션이 시작되기 전에 특정한 에러를 표시하기 위해 사용됩니다. 만약 +Linux에서 `ready` 이벤트가 호출되기 이전에 이 API를 호출할 경우, 메시지는 stderr를 +통해서 표시되며 GUI 대화 상자는 표시되지 않습니다. + +## Sheets + +Mac OS X에선, `browserWindow` 인자에 `BrowserWindow` 객체 참조를 전달하면 대화 +상자가 해당 윈도우에 시트처럼 표시되도록 표현할 수 있습니다. 윈도우의 객체 참조가 +제공되지 않으면 모달 형태로 표시됩니다. + +`BrowserWindow.getCurrentWindow().setSheetOffset(offset)`을 통해 윈도우에 부착될 +시트의 위치를 조정할 수 있습니다. diff --git a/docs-translations/ko-KR/api/download-item.md b/docs-translations/ko-KR/api/download-item.md index a367d0e000b..0356030d8fb 100644 --- a/docs-translations/ko-KR/api/download-item.md +++ b/docs-translations/ko-KR/api/download-item.md @@ -22,6 +22,7 @@ win.webContents.session.on('will-download', function(event, item, webContents) { console.log("Download is cancelled or interrupted that can't be resumed"); } }); +}); ``` ## Events diff --git a/docs-translations/ko-KR/api/menu-item.md b/docs-translations/ko-KR/api/menu-item.md index f2f495a7e59..3ee5a2ff507 100644 --- a/docs-translations/ko-KR/api/menu-item.md +++ b/docs-translations/ko-KR/api/menu-item.md @@ -62,6 +62,9 @@ OS X에서의 `role`은 다음 값을 추가로 가질 수 있습니다: * `help` - 부 메뉴를 가지는 "Help" 메뉴 * `services` - 부 메뉴를 가지는 "Services" 메뉴 +OS X에서는 `role`을 지정할 때, `label`과 `accelerator`만 MenuItem에 효과가 +적용되도록 변경되며, 다른 옵션들은 모두 무시됩니다. + ## Instance Properties 다음 속성들은 존재하는 `MenuItem`에서 계속 변경될 수 있습니다: diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 47a2939050d..c0de2ec2ab0 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -106,7 +106,7 @@ var template = [ })(), click: function(item, focusedWindow) { if (focusedWindow) - focusedWindow.toggleDevTools(); + focusedWindow.webContents.toggleDevTools(); } }, ] diff --git a/docs-translations/ko-KR/api/screen.md b/docs-translations/ko-KR/api/screen.md index ff57b02e4b2..db832852f3d 100644 --- a/docs-translations/ko-KR/api/screen.md +++ b/docs-translations/ko-KR/api/screen.md @@ -1,7 +1,8 @@ # screen `screen` 모듈은 화면 크기, 디스플레이, 커서 위치 등등의 다양한 정보를 가져옵니다. -이 모듈은 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 사용할 수 없습니다. +이 모듈은 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 사용할 수 없습니다. (호출 또는 +모듈 포함) `screen`은 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)를 상속 받았습니다. diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index 36907992a31..6ffdab04744 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -419,7 +419,7 @@ HTTP 요청을 보내기 전 요청 헤더를 사용할 수 있을 때 `listener * `timestamp` Double * `requestHeaders` Object -#### `ses.webRequest.onHeadersReceived([filter,] listener)` +#### `ses.webRequest.onHeadersReceived([filter, ]listener)` * `filter` Object * `listener` Function diff --git a/docs-translations/ko-KR/api/shell.md b/docs-translations/ko-KR/api/shell.md index c4831092f3c..6e9b0f25d5a 100644 --- a/docs-translations/ko-KR/api/shell.md +++ b/docs-translations/ko-KR/api/shell.md @@ -36,14 +36,12 @@ shell.openExternal('https://github.com'); mailto: URL은 유저의 기본 이메일 에이전트로 URL을 엽니다.) 어플리케이션이 해당 URL을 열 수 있을 때 `true`를 반환합니다. 아니라면 `false`를 반환합니다. -역주: 폴더는 'file:\\\\C:\\'와 같이 지정하여 열 수 있습니다. (Windows의 경우) +**역주:** 탐색기로 폴더만 표시하려면 `'file://경로'`와 같이 지정하여 열 수 있습니다. ### `shell.moveItemToTrash(fullPath)` * `fullPath` String -Move the given file to trash and returns boolean status for the operation. - 지정한 파일을 휴지통으로 이동합니다. 작업의 성공여부를 boolean 형으로 리턴합니다. ### `shell.beep()` diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 3e19fcd66bc..5ca4d84ce64 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -640,6 +640,9 @@ mainWindow.webContents.on('devtools-opened', function() { * `options` Object (optional) * `detach` Boolean - 새 창에서 개발자 도구를 엽니다. + * `mode` String - 개발자 도구 표시 상태를 지정합니다. 옵션은 "right", "bottom", + "undocked", "detach" 중 한 가지가 될 수 있습니다. 기본값은 마지막 표시 상태를 + 사용합니다. 개발자 도구를 엽니다. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index c47c270d24f..b04398e8e5d 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -20,12 +20,6 @@ ``` -주의할 점은 `webview` 태그의 스타일은 전통적인 flexbox 레이아웃을 사용했을 때 자식 -`object` 요소가 해당 `webview` 컨테이너의 전체 높이와 넓이를 확실히 채우도록 -내부적으로 `display:flex;`를 사용합니다. (v0.36.11 부터) 따라서 인라인 레이아웃을 -위해 `display:inline-flex;`를 쓰지 않는 한, 기본 `display:flex;` CSS 속성을 -덮어쓰지 않도록 주의해야 합니다. - 게스트 컨텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 응답을 받을 수 있습니다. 다음 예제를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 이벤트를 확인하고 두번째 리스너는 페이지의 로딩이 끝난시점을 확인합니다. 그리고 @@ -49,6 +43,36 @@ ``` +## CSS 스타일링 참고 + +주의할 점은 `webview` 태그의 스타일은 전통적인 flexbox 레이아웃을 사용했을 때 자식 +`object` 요소가 해당 `webview` 컨테이너의 전체 높이와 넓이를 확실히 채우도록 +내부적으로 `display:flex;`를 사용합니다. (v0.36.11 부터) 따라서 인라인 레이아웃을 +위해 `display:inline-flex;`를 쓰지 않는 한, 기본 `display:flex;` CSS 속성을 +덮어쓰지 않도록 주의해야 합니다. + +`webview`는 `hidden` 또는 `display: none;` 속성을 사용할 때 발생하는 문제를 한 가지 +가지고 있습니다. 자식 `browserplugin` 객체 내에서 비정상적인 랜더링 동작을 발생시킬 수 +있으며 웹 페이지가 로드되었을 때, `webview`가 숨겨지지 않았을 때, 반대로 그냥 바로 +다시 보이게 됩니다. `webview`를 숨기는 방법으로 가장 권장되는 방법은 `width` & +`height`를 0으로 지정하는 CSS를 사용하는 것이며 `flex`를 통해 0px로 요소를 수축할 수 +있도록 합니다. + +```html + +``` + ## 태그 속성 `webview` 태그는 다음과 같은 속성을 가지고 있습니다: @@ -294,7 +318,7 @@ Webview에 웹 페이지 `url`을 로드합니다. `url`은 `http://`, `file://` 이 옵션을 활성화 시키면 `requestFullScreen`와 같은 HTML API에서 유저의 승인을 무시하고 개발자가 API를 바로 사용할 수 있도록 허용합니다. -역주: 기본적으로 브라우저에선 전체화면, 웹캠, 파일 열기등의 API를 사용하려면 유저의 +**역주:** 기본적으로 브라우저에선 전체화면, 웹캠, 파일 열기등의 API를 사용하려면 유저의 승인(이벤트)이 필요합니다. ### `.openDevTools()` @@ -469,9 +493,10 @@ Returns: * `errorCode` Integer * `errorDescription` String * `validatedURL` String +* `isMainFrame` Boolean -`did-finish-load`와 비슷합니다. 하지만 이 이벤트는 `window.stop()`과 같은 무언가로 -인해 로드에 실패했을 때 발생하는 이벤트입니다. +`did-finish-load`와 비슷합니다. 하지만 이 이벤트는 `window.stop()`과 같이 취소 +함수가 호출되었거나 로드에 실패했을 때 발생하는 이벤트입니다. ### Event: 'did-frame-finish-load' @@ -725,6 +750,10 @@ WebContents가 파괴될 때 발생하는 이벤트입니다. ### Event: 'did-change-theme-color' +Returns: + +* `themeColor` String + 페이지의 테마 색이 변경될 때 발생하는 이벤트입니다. 이 이벤트는 보통 meta 태그에 의해서 발생합니다: diff --git a/docs-translations/ko-KR/development/source-code-directory-structure.md b/docs-translations/ko-KR/development/source-code-directory-structure.md index 47410b8ec2c..98a3fd2a1de 100644 --- a/docs-translations/ko-KR/development/source-code-directory-structure.md +++ b/docs-translations/ko-KR/development/source-code-directory-structure.md @@ -57,3 +57,30 @@ Electron 스크립트로부터 만들어지는 임시 디렉터리. * **external_binaries** - `gyp` 빌드를 지원하지 않아 따로 다운로드된 서드파티 프레임워크 바이너리들. + +## Git 서브 모듈 최신 버전으로 유지 + +Electron 저장소는 몇 가지 외부 벤더 종속성을 가지고 있으며 [/vendor](/vendor) +디렉터리에서 확인할 수 있습니다. 때때로 `git status`를 실행했을 때 아마 다음과 같은 +메시지를 흔히 목격할 것입니다: + +```sh +$ git status + + modified: vendor/brightray (new commits) + modified: vendor/node (new commits) +``` + +이 외부 종속성 모듈들을 업데이트 하려면, 다음 커맨드를 실행합니다: + +```sh +git submodule update --init --recursive +``` + +만약 자기 자신이 너무 이 커맨드를 자주 사용하는 것 같다면, `~/.gitconfig` 파일을 +생성하여 편하게 업데이트할 수 있습니다: + +``` +[alias] + su = submodule update --init --recursive +``` diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index 43d707b7942..9e05c83dc25 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -4,10 +4,6 @@ Electron은 v0.34.0 버전부터 앱 패키지를 Mac App Store(MAS)에 제출 되었습니다. 이 가이드는 어플리케이션을 앱 스토어에 등록하는 방법과 빌드의 한계에 대한 설명을 제공합니다. -**참고:** v0.36.0 버전부터 어플리케이션이 샌드박스화 된 상태로 실행되면 GPU 작동을 -방지하는 버그가 있었습니다. 따라서 이 버그가 고쳐지기 전까진 v0.35.x 버전을 사용하는 -것을 권장합니다. 이 버그에 관한 자세한 사항은 [issue #3871][issue-3871]를 참고하세요. - **참고:** Mac App Store에 어플리케이션을 등록하려면 [Apple Developer Program][developer-program]에 등록되어 있어야 하며 비용이 발생할 수 있습니다. @@ -56,6 +52,8 @@ Apple로부터 인증서를 취득했다면, [어플리케이션 배포](applica com.apple.security.app-sandbox + com.apple.security.temporary-exception.sbpl + (allow mach-lookup (global-name-regex #"^org.chromium.Chromium.rohitfork.[0-9]+$")) ``` @@ -77,17 +75,18 @@ INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)" FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" -codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" -if [ -d "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" ]; then - # non-MAS 빌드 서명 - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Mantle.framework/Versions/A" - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/ReactiveCocoa.framework/Versions/A" - codesign --deep -fs "$APP_KEY" --entitlements child.plist "$FRAMEWORKS_PATH/Squirrel.framework/Versions/A" -fi -codesign -fs "$APP_KEY" --entitlements parent.plist "$APP_PATH" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" +codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" +codesign -s "$APP_KEY" -f --entitlements child.plist "$APP_PATH/Contents/MacOS/$APP" +codesign -s "$APP_KEY" -f --entitlements parent.plist "$APP_PATH" productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH" ``` @@ -96,11 +95,31 @@ productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RES 문서를 참고하여 기본적인 개념을 이해해야 합니다. 그리고 자격(plist) 파일에 어플리케이션에서 요구하는 권한의 키를 추가합니다. -### 어플리케이션을 업로드하고 심사용 앱으로 제출 +### 어플리케이션 업로드 어플리케이션 서명을 완료한 후 iTunes Connect에 업로드하기 위해 Application Loader를 사용할 수 있습니다. 참고로 업로드하기 전에 [레코드][create-record]를 만들었는지 -확인해야 합니다. 그리고 [심사를 위해 앱을 제출][submit-for-review]할 수 있습니다. +확인해야 합니다. + +### `temporary-exception`의 사용처 설명 + +어플리케이션을 샌드박싱할 때 `temporary-exception` 엔트리가 자격에 추가되며 +[App Sandbox Temporary Exception Entitlements][temporary-exception] 문서에 따라 +왜 이 엔트리가 필요한지 설명해야 합니다: + +> Note: If you request a temporary-exception entitlement, be sure to follow the +guidance regarding entitlements provided on the iTunes Connect website. In +particular, identify the entitlement and corresponding issue number in the App +Sandbox Entitlement Usage Information section in iTunes Connect and explain why +your app needs the exception. + +아마 제출하려는 어플리케이션이 Chromium 브라우저를 기반으로 만들어졌고, 또한 +멀티-프로세스 구조를 위해 Mach port를 사용하는 것도 설명해야 할 수 있습니다. 하지만 +여전히 이러한 문제 때문에 어플리케이션 심사에 실패할 수 있습니다. + +### 어플리케이션을 심사에 제출 + +위 과정을 마치면 [어플리케이션을 심사를 위해 제출][submit-for-review]할 수 있습니다. ## MAS 빌드의 한계 @@ -164,5 +183,5 @@ ERN의 승인을 얻는 방법은, 다음 글을 참고하는 것이 좋습니 [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ +[temporary-exception]: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html diff --git a/docs-translations/ko-KR/tutorial/supported-platforms.md b/docs-translations/ko-KR/tutorial/supported-platforms.md index 656d31308e0..d71951cd3d8 100644 --- a/docs-translations/ko-KR/tutorial/supported-platforms.md +++ b/docs-translations/ko-KR/tutorial/supported-platforms.md @@ -12,7 +12,7 @@ Windows 7 이후 버전만 지원됩니다. Windows Vista에서도 작동할 수 테스트가 완료되지 않았습니다. 윈도우용 바이너리는 `x86`과 `x64` 모두 제공됩니다. 그리고 `ARM` 버전 윈도우는 아직 -지원하지 않습니다. (역주: 추후 지원할 가능성이 있습니다) +지원하지 않습니다. ### Linux diff --git a/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md index be88be1cec6..4fec05e1505 100644 --- a/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md +++ b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md @@ -16,9 +16,9 @@ Electron 기반 어플리케이션을 Travis, Circle, Jenkins 또는 유사한 그리고, 가상 xvfb 스크린을 생성하고 DISPLAY라고 불리우는 환경 변수를 지정합니다. Electron의 Chromium은 자동적으로 `$DISPLAY` 변수를 찾습니다. 따라서 앱의 추가적인 다른 설정이 필요하지 않습니다. 이러한 작업은 Paul Betts의 -[xfvb-maybe](https://github.com/paulcbetts/xvfb-maybe)를 통해 자동화 할 수 -있습니다: `xfvb-maybe`를 테스트 커맨드 앞에 추가하고 현재 시스템에서 요구하면 -이 작은 툴이 자동적으로 xfvb를 설정합니다. Windows와 Mac OS X에선 간단히 아무 작업도 +[xvfb-maybe](https://github.com/paulcbetts/xvfb-maybe)를 통해 자동화 할 수 +있습니다: `xvfb-maybe`를 테스트 커맨드 앞에 추가하고 현재 시스템에서 요구하면 +이 작은 툴이 자동적으로 xvfb를 설정합니다. Windows와 Mac OS X에선 간단히 아무 작업도 하지 않습니다. ``` @@ -45,7 +45,7 @@ install: ### Jenkins -Jenkins는 [Xfvb 플러그인이 존재합니다](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). +Jenkins는 [Xvfb 플러그인이 존재합니다](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). ### Circle CI From ca756c3c2492c69c75c9a8c1d99dc29c73f3f942 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 20 Apr 2016 22:25:15 +0530 Subject: [PATCH 0553/1265] session: allow providing permission to handle external protocols --- .../atom_resource_dispatcher_host_delegate.cc | 35 ++++++++++++++++--- .../browser/web_contents_permission_helper.cc | 8 +++++ atom/browser/web_contents_permission_helper.h | 6 +++- .../content_converter.cc | 2 ++ docs/api/session.md | 3 +- spec/webview-spec.js | 11 +++++- 6 files changed, 58 insertions(+), 7 deletions(-) diff --git a/atom/browser/atom_resource_dispatcher_host_delegate.cc b/atom/browser/atom_resource_dispatcher_host_delegate.cc index 68576a52f24..59ac258ea13 100644 --- a/atom/browser/atom_resource_dispatcher_host_delegate.cc +++ b/atom/browser/atom_resource_dispatcher_host_delegate.cc @@ -5,6 +5,7 @@ #include "atom/browser/atom_resource_dispatcher_host_delegate.h" #include "atom/browser/login_handler.h" +#include "atom/browser/web_contents_permission_helper.h" #include "atom/common/platform_util.h" #include "content/public/browser/browser_thread.h" #include "net/base/escape.h" @@ -14,20 +15,46 @@ using content::BrowserThread; namespace atom { +namespace { + +void OnOpenExternal(const GURL& escaped_url, + bool allowed) { + if (allowed) + platform_util::OpenExternal(escaped_url, true); +} + +void HandleExternalProtocolInUI( + const GURL& url, + const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, + bool has_user_gesture) { + content::WebContents* web_contents = web_contents_getter.Run(); + if (!web_contents) + return; + + GURL escaped_url(net::EscapeExternalHandlerValue(url.spec())); + auto callback = base::Bind(&OnOpenExternal, escaped_url); + auto permission_helper = + WebContentsPermissionHelper::FromWebContents(web_contents); + permission_helper->RequestOpenExternalPermission(callback, has_user_gesture); +} + +} // namespace + AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() { } bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol( const GURL& url, int child_id, - const content::ResourceRequestInfo::WebContentsGetter&, + const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, bool is_main_frame, ui::PageTransition transition, bool has_user_gesture) { - GURL escaped_url(net::EscapeExternalHandlerValue(url.spec())); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind( - base::IgnoreResult(platform_util::OpenExternal), escaped_url, true)); + base::Bind(&HandleExternalProtocolInUI, + url, + web_contents_getter, + has_user_gesture)); return true; } diff --git a/atom/browser/web_contents_permission_helper.cc b/atom/browser/web_contents_permission_helper.cc index d018e1d09db..7c944832d88 100644 --- a/atom/browser/web_contents_permission_helper.cc +++ b/atom/browser/web_contents_permission_helper.cc @@ -91,4 +91,12 @@ void WebContentsPermissionHelper::RequestPointerLockPermission( user_gesture); } +void WebContentsPermissionHelper::RequestOpenExternalPermission( + const base::Callback& callback, + bool user_gesture) { + RequestPermission((content::PermissionType)(PermissionType::OPEN_EXTERNAL), + callback, + user_gesture); +} + } // namespace atom diff --git a/atom/browser/web_contents_permission_helper.h b/atom/browser/web_contents_permission_helper.h index 90ae6dff56f..89da64b7583 100644 --- a/atom/browser/web_contents_permission_helper.h +++ b/atom/browser/web_contents_permission_helper.h @@ -19,7 +19,8 @@ class WebContentsPermissionHelper enum class PermissionType { POINTER_LOCK = static_cast(content::PermissionType::NUM) + 1, - FULLSCREEN + FULLSCREEN, + OPEN_EXTERNAL, }; void RequestFullscreenPermission( @@ -30,6 +31,9 @@ class WebContentsPermissionHelper void RequestWebNotificationPermission( const base::Callback& callback); void RequestPointerLockPermission(bool user_gesture); + void RequestOpenExternalPermission( + const base::Callback& callback, + bool user_gesture); private: explicit WebContentsPermissionHelper(content::WebContents* web_contents); diff --git a/atom/common/native_mate_converters/content_converter.cc b/atom/common/native_mate_converters/content_converter.cc index f5d81d085bc..7e7cd9bd1ff 100644 --- a/atom/common/native_mate_converters/content_converter.cc +++ b/atom/common/native_mate_converters/content_converter.cc @@ -145,6 +145,8 @@ v8::Local Converter::ToV8( return StringToV8(isolate, "pointerLock"); else if (val == (content::PermissionType)(PermissionType::FULLSCREEN)) return StringToV8(isolate, "fullscreen"); + else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL)) + return StringToV8(isolate, "openExternal"); return StringToV8(isolate, "unknown"); } diff --git a/docs/api/session.md b/docs/api/session.md index 9cccefcbdb6..ecc65f550ed 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -295,7 +295,8 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c * `handler` Function * `webContents` Object - [WebContents](web-contents.md) requesting the permission. - * `permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex', 'pointerLock', 'fullscreen'. + * `permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex', + 'pointerLock', 'fullscreen', 'openExternal'. * `callback` Function - Allow or deny the permission. Sets the handler which can be used to respond to permission requests for the `session`. diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 10758a0a436..88afbe2f131 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -722,11 +722,13 @@ describe(' tag', function () { }) describe('permission-request event', function () { - function setUpRequestHandler (webview, requested_permission) { + function setUpRequestHandler (webview, requested_permission, completed) { var listener = function (webContents, permission, callback) { if (webContents.getId() === webview.getId()) { assert.equal(permission, requested_permission) callback(false) + if (completed) + completed() } } session.fromPartition(webview.partition).setPermissionRequestHandler(listener) @@ -770,6 +772,13 @@ describe(' tag', function () { setUpRequestHandler(webview, 'midiSysex') document.body.appendChild(webview) }) + + it('emits when accessing external protocol', function (done) { + webview.src = 'magnet:test' + webview.partition = 'permissionTest' + setUpRequestHandler(webview, 'openExternal', done) + document.body.appendChild(webview) + }) }) describe('.getWebContents', function () { From b5c1db9ad9901585e397492888b6320b724298fe Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 21 Apr 2016 11:17:12 +0900 Subject: [PATCH 0554/1265] Guard against unexist owner when removing ref to remote object --- lib/browser/objects-registry.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/browser/objects-registry.js b/lib/browser/objects-registry.js index b8aa480a6db..adbf6835554 100644 --- a/lib/browser/objects-registry.js +++ b/lib/browser/objects-registry.js @@ -50,7 +50,10 @@ class ObjectsRegistry { this.dereference(id) // Also remove the reference in owner. - this.owners[webContentsId].delete(id) + let owner = this.owners[webContentsId] + if (owner) { + owner.delete(id) + } } // Clear all references to objects refrenced by the WebContents. From 30d37fcba42517d574851202eaf08ed49e7131c4 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 21 Apr 2016 12:33:56 +0900 Subject: [PATCH 0555/1265] :memo: Small fixes [ci skip] --- docs-translations/ko-KR/api/session.md | 2 +- .../ko-KR/tutorial/mac-app-store-submission-guide.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index 6ffdab04744..077cb1867c6 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -294,7 +294,7 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c * `handler` Function * `webContents` Object - [WebContents](web-contents.md) 권한을 요청. * `permission` String - 'media', 'geolocation', 'notifications', - 'midiSysex', 'pointerLock', 'fullscreen'의 나열. + 'midiSysex', 'pointerLock', 'fullscreen', 'openExternal'의 나열. * `callback` Function - 권한 허용 및 거부. `session`의 권한 요청에 응답을 하는데 사용하는 핸들러를 설정합니다. diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index 9e05c83dc25..45342f14de2 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -104,7 +104,7 @@ productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RES ### `temporary-exception`의 사용처 설명 어플리케이션을 샌드박싱할 때 `temporary-exception` 엔트리가 자격에 추가되며 -[App Sandbox Temporary Exception Entitlements][temporary-exception] 문서에 따라 +[어플리케이션 샌드박스 임시 예외 적용][temporary-exception] 문서에 따라 왜 이 엔트리가 필요한지 설명해야 합니다: > Note: If you request a temporary-exception entitlement, be sure to follow the @@ -114,7 +114,7 @@ Sandbox Entitlement Usage Information section in iTunes Connect and explain why your app needs the exception. 아마 제출하려는 어플리케이션이 Chromium 브라우저를 기반으로 만들어졌고, 또한 -멀티-프로세스 구조를 위해 Mach port를 사용하는 것도 설명해야 할 수 있습니다. 하지만 +멀티-프로세스 구조를 위해 Mach 포트를 사용하는 것도 설명해야 할 수 있습니다. 하지만 여전히 이러한 문제 때문에 어플리케이션 심사에 실패할 수 있습니다. ### 어플리케이션을 심사에 제출 @@ -136,7 +136,7 @@ your app needs the exception. * 어플리케이션이 DNS의 변경을 감지하지 못할 수 있습니다. 또한 어플리케이션 샌드박스 개념으로 인해 어플리케이션에서 접근할 수 있는 리소스는 -엄격하게 제한되어 있습니다. 자세한 내용은 [App Sandboxing][app-sandboxing] 문서를 +엄격하게 제한되어 있습니다. 자세한 내용은 [앱 샌드박싱][app-sandboxing] 문서를 참고하세요. ## Electron에서 사용하는 암호화 알고리즘 From 0900762507570b8e823d6eb14c43821842128f26 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 21 Apr 2016 13:58:11 +0900 Subject: [PATCH 0556/1265] Make the length of SingletonSocket's path as short as we can --- .../chrome/browser/process_singleton_posix.cc | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/chromium_src/chrome/browser/process_singleton_posix.cc b/chromium_src/chrome/browser/process_singleton_posix.cc index 7e54d9b5d37..c583db0162a 100644 --- a/chromium_src/chrome/browser/process_singleton_posix.cc +++ b/chromium_src/chrome/browser/process_singleton_posix.cc @@ -111,7 +111,7 @@ const base::FilePath::CharType kSingletonCookieFilename[] = const base::FilePath::CharType kSingletonLockFilename[] = FILE_PATH_LITERAL("SingletonLock"); const base::FilePath::CharType kSingletonSocketFilename[] = - FILE_PATH_LITERAL("SingletonSocket"); + FILE_PATH_LITERAL("SS"); // Set the close-on-exec bit on a file descriptor. // Returns 0 on success, -1 on failure. @@ -943,6 +943,19 @@ bool ProcessSingleton::Create() { #endif } +#if defined(MAS_BUILD) + // For Mac App Store build, the tmp dir could be too long to fit + // addr->sun_path, so we need to make it as short as possible. + base::FilePath tmp_dir; + if (!base::GetTempDir(&tmp_dir)) { + LOG(ERROR) << "Failed to get temporary directory."; + return false; + } + if (!socket_dir_.Set(tmp_dir.Append("S"))) { + LOG(ERROR) << "Failed to set socket directory."; + return false; + } +#else // Create the socket file somewhere in /tmp which is usually mounted as a // normal filesystem. Some network filesystems (notably AFS) are screwy and // do not support Unix domain sockets. @@ -950,6 +963,7 @@ bool ProcessSingleton::Create() { LOG(ERROR) << "Failed to create socket directory."; return false; } +#endif // Check that the directory was created with the correct permissions. int dir_mode = 0; From df97be30e5903958ad75f661c0079d77d6644206 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 21 Apr 2016 14:37:29 +0900 Subject: [PATCH 0557/1265] Do not create the folder passed to app.setPath --- atom/browser/api/atom_api_app.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 9d0aa792e60..d239a63d058 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -351,10 +351,15 @@ base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) { void App::SetPath(mate::Arguments* args, const std::string& name, const base::FilePath& path) { + if (!path.IsAbsolute()) { + args->ThrowError("path must be absolute"); + return; + } + bool succeed = false; int key = GetPathConstant(name); if (key >= 0) - succeed = PathService::Override(key, path); + succeed = PathService::OverrideAndCreateIfNeeded(key, path, true, false); if (!succeed) args->ThrowError("Failed to set path"); } From 2a2a8d3263c0d35c1e1248c7da873b75a23760d8 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Wed, 20 Apr 2016 23:55:56 -0700 Subject: [PATCH 0558/1265] Add Windows Store Detection If we're running as a Windows Store appx package, `process.windowsstore` will be `true`, otherwise `undefined`. --- docs/api/process.md | 2 ++ lib/common/init.js | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/docs/api/process.md b/docs/api/process.md index 620ad6dc931..c5506f7e25b 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -10,6 +10,8 @@ upstream node: * `process.resourcesPath` String - Path to JavaScript source code. * `process.mas` Boolean - For Mac App Store build, this value is `true`, for other builds it is `undefined`. +* `process.windowsstore` Boolean - If the app is running as a Windows Store app (appx), this value is `true`, for + other builds it is `undefined`. ## Events diff --git a/lib/common/init.js b/lib/common/init.js index 221febb0c37..8790320376d 100644 --- a/lib/common/init.js +++ b/lib/common/init.js @@ -44,3 +44,12 @@ if (process.type === 'browser') { global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout) global.setInterval = wrapWithActivateUvLoop(timers.setInterval) } + +// If we're running as a Windows Store app, __dirname will be set +// to C:/Program Files/WindowsApps. +// +// Nobody else get's to install there, changing the path is forbidden +// We can therefore say that we're running as appx +if (process.platform === 'win32' && __dirname.indexOf('\\Program Files\\WindowsApps\\') === 2) { + process.windowsstore = true +} From 67f672541cab5eda3a90797888a8cfff97b252b7 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 21 Apr 2016 18:51:27 +0900 Subject: [PATCH 0559/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/web-contents.md | 4 + .../development/debug-instructions-windows.md | 87 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 docs-translations/ko-KR/development/debug-instructions-windows.md diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 5ca4d84ce64..48798f79b6c 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -350,6 +350,10 @@ var currentURL = win.webContents.getURL(); 현재 웹 페이지가 리소스를 로드중인지 여부를 반환합니다. +### `webContents.isLoadingMainFrame()` + +메인 프레임이 여전히 로딩중인지 여부를 반환합니다. (내부 iframe 또는 frame 포함) + ### `webContents.isWaitingForResponse()` 현재 웹 페이지가 페이지의 메인 리소스로부터 첫 응답을 기다리고있는지 여부를 반환합니다. diff --git a/docs-translations/ko-KR/development/debug-instructions-windows.md b/docs-translations/ko-KR/development/debug-instructions-windows.md new file mode 100644 index 00000000000..eb738f15508 --- /dev/null +++ b/docs-translations/ko-KR/development/debug-instructions-windows.md @@ -0,0 +1,87 @@ +# Windows에서 Electron 디버깅하기 + +만약 작성한 Javascript 어플리케이션이 아닌 Electron 자체의 크래시나 문제를 경험하고 +있다면, 네이티브/C++ 디버깅에 익숙하지 않은 개발자는 디버깅이 약간 까다로울 수 +있습니다. 그렇다 해도, Visual Studio, GitHub의 Electron이 호스팅하는 심볼 서버, +Electron 소스 코드가 중단점을 통해 순차적으로 쉽게 디버깅할 수 있는 환경을 제공합니다. + +## 요구 사항 + +* **Electron의 디버그 빌드**: 가장 쉬운 방법은 보통 + [Windows용 빌드 설명서](build-instructions-windows.md)에 명시된 요구사항과 툴을 + 사용하여 스스로 빌드하는 것입니다. 물론 직접 다운로드 받은 Electron 바이너리에도 + 디버거 연결 및 디버깅을 사용할 수 있지만, 실질적으로 디버깅이 까다롭게 고도의 + 최적화가 되어있음을 발견하게 될 것입니다: 인라인화, 꼬리 호출, 이외 여러 가지 + 생소한 최적화가 적용되어 디버거가 모든 변수와 실행 경로를 정상적으로 표시할 수 + 없습니다. + +* **Visual Studio와 C++ 툴**: Visual Studio 2013과 Visual Studio 2015 두 가지 + 커뮤니티 에디션 모두 잘 작동합니다. 설치가 완료되면, + [Visual Studio가 GitHub의 Electron 심볼 서버를 사용하도록](setting-up-symbol-server.md) + 설정해야 합니다. 이 작업은 Visual Studio가 Electron에서 무슨일이 일어나는지 더 잘 + 이해할 수 있도록 하며 변수를 사람이 읽기 좋은 포맷으로 쉽게 표현할 수 있도록 합니다. + +* **ProcMon**: 이 무료 [SysInternals][sys-internals] 툴은 프로세스 인자, 파일 + 핸들러 그리고 레지스트리 작업을 탐색할 수 있게 도와줍니다. + +## Electron에 디버거 연결하고 디버깅하기 + +디버깅 작업을 시작하려면, PowerShell/CMD 중 한 가지를 열고 디버그 빌드 상태의 +Electron에 인자로 어플리케이션을 전달하여 실행합니다: + +```powershell +$ ./out/D/electron.exe ~/my-electron-app/ +``` + +### 중단점 설정 + +그리고, Visual Studio를 엽니다. Electron은 Visual Studio로 만들어지지 않았으며 +이러한 이유로 인해 프로젝트 파일을 가지고 있지 않습니다. 하지만 "파일로 열기"를 통해 +소스 코드 파일들을 열 수 있습니다. Visual Studio가 각각의 파일을 따로 연다는 것입니다. +여전히 중단점을 설정할 수 있습니다. Visual Studio는 현재 소스 코드와 일치하는 작동 +중인 프로세스와 중단점을 자동으로 찾아냅니다. + +관련된 코드 파일들은 `./atom/`에서 찾을 수 있으며 또한 Brightray 안 +`./vendor/brightray/browser`와 `./vendor/brightray/common`에서도 찾을 수 있습니다. +만약 하드코어를 좋아한다면, Chromium을 직접 디버깅할 수도 있습니다. 확실히 +`chromium_src` 안에서 찾을 수 있습니다. + +### 디버거 연결 + +로컬에서 작동 중인 프로세스 또는 원격 컴퓨터에 Visual Studio 디버거를 적용시킬 수 +있습니다. 프로세스의 실행이 끝난 후, 디버그 / 프로세스에 연결을 (또는 `Ctrl+Alt+P` +입력) 클릭하면 "프로세스에 연결" 대화 상자가 열립니다. 이 도구를 통해 로컬 또는 +원격에서 작동 중인 어플리케이션을 디버깅할 수 있으며 여러 프로세스를 동시에 디버깅할 +수도 있습니다. + +만약 Electron이 서로 다른 유저 계정에서 실행 중이라면, `모든 사용자의 프로세스 +보이기`를 선택하면 됩니다. 참고로 이는 `BrowserWindow`가 열린 개수에 따라 달라질 수 +있으며 아마 다수의 프로세스를 발견할 수 있을 것입니다. 전형적인 one-window +어플리케이션은 Visual Studio에서 두 개의 `Electron.exe` 항목으로 표시됩니다. 하나는 +메인 프로세스이며 다른 하나는 렌더러 프로세스입니다. 리스트는 단지 이름 하나만 제공하기 +때문에 현재까지는 다른 적절한 프로세스 판별법이 없습니다. + +## 어떤 프로세스에 디버거를 적용해야 하나요? + +코드는 메인 프로세스 내에서 실행되며 (이는 코드를 안에서 찾을 수 있거나, 결국 메인 +Javascript 파일에 의해 실행) remote (`require('electron').remote`)를 사용하여 +코드를 실행하는 것 또한 메인 프로세스 내에서 실행됩니다. 다른 코드는 각각의 렌더러 +프로세스 내에서 실행됩니다. + +디버깅할 때 여러 프로그램에 디버거를 적용할 수 있지만, 언제나 한 개의 프로그램만 +디버거에서 활성화되어야 합니다. `디버그 경로` 툴바 또는 `프로세스 창`에서 활성화 +프로그램을 설정할 수 있습니다. + +## 프로세스를 관찰하기 위해 ProcMon 사용 + +Visual Studio는 특정 코드 경로를 탐색하는것에 대해 환상적인 기능을 제공하고 ProcMon은 +어플리케이션이 운영체제와 하는 일의 모든 것을 관찰하는데 강력한 기능을 가지고 있습니다. +이 툴은 프로세스의 파일, 레지스트리, 네트워킹, 프로세스, 프로파일링 상세를 포착할 수 +있으며 강력하게 **모든** 이벤트의 발생을 로깅을 시도합니다. 만약 어플리케이션이 +운영체제에 대해 무슨 일을 하고 있는지 이해하고 싶다면 이는 좋은 자원이 될 것입니다. + +ProcMon의 기본적인 디버깅 기능을 알아보고 싶다면 Microsoft에서 제공하는 +[동영상 강좌][procmon-instructions]를 참고하세요. + +[sys-internals]: https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx +[procmon-instructions]: https://channel9.msdn.com/shows/defrag-tools/defrag-tools-4-process-monitor From e4bd592e0e712a4ba0f3da28eb61e7fb3cd5695a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 21 Apr 2016 11:49:42 -0700 Subject: [PATCH 0560/1265] Add failing spec --- spec/fixtures/module/answer.js | 4 +++ spec/fixtures/pages/web-view-log-process.html | 13 ++++++++ ...webview-no-node-integration-on-window.html | 23 +++++++++++++ spec/webview-spec.js | 33 +++++++++++++++++++ 4 files changed, 73 insertions(+) create mode 100644 spec/fixtures/module/answer.js create mode 100644 spec/fixtures/pages/web-view-log-process.html create mode 100644 spec/fixtures/pages/webview-no-node-integration-on-window.html diff --git a/spec/fixtures/module/answer.js b/spec/fixtures/module/answer.js new file mode 100644 index 00000000000..d592d6cda21 --- /dev/null +++ b/spec/fixtures/module/answer.js @@ -0,0 +1,4 @@ +var ipcRenderer = require('electron').ipcRenderer +window.answer = function (answer) { + ipcRenderer.send('answer', answer) +} diff --git a/spec/fixtures/pages/web-view-log-process.html b/spec/fixtures/pages/web-view-log-process.html new file mode 100644 index 00000000000..9e75edb393e --- /dev/null +++ b/spec/fixtures/pages/web-view-log-process.html @@ -0,0 +1,13 @@ + + + + + test + + + + test? + + diff --git a/spec/fixtures/pages/webview-no-node-integration-on-window.html b/spec/fixtures/pages/webview-no-node-integration-on-window.html new file mode 100644 index 00000000000..0af03cf1c49 --- /dev/null +++ b/spec/fixtures/pages/webview-no-node-integration-on-window.html @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 88afbe2f131..d2c37c857df 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -84,6 +84,39 @@ describe(' tag', function () { document.body.appendChild(webview) }) + it('disables node integration when disabled on the parent BrowserWindow', function (done) { + var b = undefined + + ipcMain.once('answer', function (event, typeofProcess) { + try { + assert.equal(typeofProcess, 'undefined') + done() + } finally { + b.close() + } + }) + + var windowUrl = require('url').format({ + pathname: `${fixtures}/pages/webview-no-node-integration-on-window.html`, + protocol: 'file', + query: { + p: `${fixtures}/pages/web-view-log-process.html` + }, + slashes: true + }) + var preload = path.join(fixtures, 'module', 'answer.js') + + b = new BrowserWindow({ + height: 400, + width: 400, + show: false, + webPreferences: { + preload: preload, + nodeIntegration: false, + } + }) + b.loadURL(windowUrl) + }) it('disables node integration on child windows when it is disabled on the webview', function (done) { app.once('browser-window-created', function (event, window) { From 8e7bf1051d9f35837ce7a0a6009a61b5642b8ca1 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 21 Apr 2016 11:52:10 -0700 Subject: [PATCH 0561/1265] Disable node integration on webview when disabled on window --- lib/browser/guest-view-manager.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/browser/guest-view-manager.js b/lib/browser/guest-view-manager.js index ad79fe699a4..58775669c2f 100644 --- a/lib/browser/guest-view-manager.js +++ b/lib/browser/guest-view-manager.js @@ -182,6 +182,11 @@ var attachGuest = function (embedder, elementInstanceId, guestInstanceId, params webSecurity: !params.disablewebsecurity, blinkFeatures: params.blinkfeatures } + + if (embedder.getWebPreferences().nodeIntegration === false) { + webPreferences.nodeIntegration = false + } + if (params.preload) { webPreferences.preloadURL = params.preload } From b45f6836554f6a4e1451df0560cddb976ed79045 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Thu, 21 Apr 2016 17:00:19 -0500 Subject: [PATCH 0562/1265] Update desktop-capturer.md Fixed native image link. --- docs/api/desktop-capturer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index 3babe0e1638..bf775c3a6d2 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -72,7 +72,7 @@ captured screen or individual window, and has following properties: * `name` String - The described name of the capturing screen or window. If the source is a screen, the name will be `Entire Screen` or `Screen `; if it is a window, the name will be the window's title. -* `thumbnail` [NativeImage](NativeImage.md) - A thumbnail image. +* `thumbnail` A thumbnail [native image](native-image.md). **Note:** There is no guarantee that the size of `source.thumbnail` is always the same as the `thumnbailSize` in `options`. It also depends on the scale of From c0f63eed4eaf3134e55c6b1cf75050e0ca5a9fe2 Mon Sep 17 00:00:00 2001 From: Felix Rieseberg Date: Thu, 21 Apr 2016 19:11:25 -0700 Subject: [PATCH 0563/1265] :art: Windows Store Camels --- docs/api/process.md | 2 +- lib/common/init.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/process.md b/docs/api/process.md index c5506f7e25b..b2d9c765a03 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -10,7 +10,7 @@ upstream node: * `process.resourcesPath` String - Path to JavaScript source code. * `process.mas` Boolean - For Mac App Store build, this value is `true`, for other builds it is `undefined`. -* `process.windowsstore` Boolean - If the app is running as a Windows Store app (appx), this value is `true`, for +* `process.windowsStore` Boolean - If the app is running as a Windows Store app (appx), this value is `true`, for other builds it is `undefined`. ## Events diff --git a/lib/common/init.js b/lib/common/init.js index 8790320376d..11c098d3ce5 100644 --- a/lib/common/init.js +++ b/lib/common/init.js @@ -51,5 +51,5 @@ if (process.type === 'browser') { // Nobody else get's to install there, changing the path is forbidden // We can therefore say that we're running as appx if (process.platform === 'win32' && __dirname.indexOf('\\Program Files\\WindowsApps\\') === 2) { - process.windowsstore = true + process.windowsStore = true } From c04d43ca132bea2bbd048c2bf3d347b920089438 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 22 Apr 2016 17:39:11 +0900 Subject: [PATCH 0564/1265] Bump v0.37.7 --- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- electron.gyp | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 50522ddda17..8cfb6368891 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 0.37.6 + 0.37.7 CFBundleShortVersionString - 0.37.6 + 0.37.7 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 473cd151f9a..bcd4a829369 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,6,0 - PRODUCTVERSION 0,37,6,0 + FILEVERSION 0,37,7,0 + PRODUCTVERSION 0,37,7,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.6" + VALUE "FileVersion", "0.37.7" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.6" + VALUE "ProductVersion", "0.37.7" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index 65921c77581..dab2966bb99 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 6 +#define ATOM_PATCH_VERSION 7 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/electron.gyp b/electron.gyp index 11a35490923..e6134df117b 100644 --- a/electron.gyp +++ b/electron.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.6', + 'version%': '0.37.7', }, 'includes': [ 'filenames.gypi', diff --git a/package.json b/package.json index d6306b8406e..aa7ca37e5eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.6", + "version": "0.37.7", "devDependencies": { "asar": "^0.11.0", "request": "*", From da727a3c1bdbf5cfaa55b7e718dc280d2d0a720d Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Fri, 22 Apr 2016 12:32:11 +0200 Subject: [PATCH 0565/1265] Fix display.rotation documentation --- docs/api/screen.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/screen.md b/docs/api/screen.md index 4d12f1359f7..0dbf5b35a29 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -62,8 +62,8 @@ a remote, virtual display. * `display` object * `id` Integer - Unique identifier associated with the display. - * `rotation` Integer - Can be 0, 1, 2, 3, each represents screen rotation in - clock-wise degrees of 0, 90, 180, 270. + * `rotation` Integer - Can be 0, 90, 180, 270, represents screen rotation in + clock-wise degrees. * `scaleFactor` Number - Output device's pixel scale factor. * `touchSupport` String - Can be `available`, `unavailable`, `unknown`. * `bounds` Object From d125483c133296705c0c3549d0048fc5061afe8c Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:02:39 +0900 Subject: [PATCH 0566/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/desktop-capturer.md | 2 +- docs-translations/ko-KR/api/process.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs-translations/ko-KR/api/desktop-capturer.md b/docs-translations/ko-KR/api/desktop-capturer.md index 534b487f772..3b4f8c71983 100644 --- a/docs-translations/ko-KR/api/desktop-capturer.md +++ b/docs-translations/ko-KR/api/desktop-capturer.md @@ -72,7 +72,7 @@ function getUserMediaError(e) { * `name` String - 캡쳐된 화면과 윈도우에 대해 묘사된 이름입니다. 만약 소스가 화면이라면, `Entire Screen` 또는 `Screen `가 될 것이고 소스가 윈도우라면, 해당 윈도우의 제목이 반환됩니다. -* `thumbnail` [NativeImage](NativeImage.md) - 섬네일 이미지. +* `thumbnail` [NativeImage](native-image.md) - 섬네일 네이티브 이미지. **참고:** `source.thumbnail`의 크기는 언제나 `options`의 `thumnbailSize`와 같다고 보장할 수 없습니다. 섬네일의 크기는 화면과 윈도우의 크기에 의존하여 조정됩니다. diff --git a/docs-translations/ko-KR/api/process.md b/docs-translations/ko-KR/api/process.md index de24b5ac174..3cdc10dd78c 100644 --- a/docs-translations/ko-KR/api/process.md +++ b/docs-translations/ko-KR/api/process.md @@ -9,6 +9,8 @@ Electron의 `process` 객체는 기존의 node와는 달리 약간의 차이점 * `process.resourcesPath` String - JavaScript 소스 코드의 경로. * `process.mas` Boolean - Mac 앱 스토어용 빌드일 때 `true`로 지정됩니다. 다른 빌드일 땐 `undefined`로 지정됩니다. +* `process.windowsStore` Boolean - 만약 앱이 Windows Store 앱 (appx)으로 작동하고 + 있다면, 이 값이 `true`로 지정되며 다른 빌드인 경우엔 `undefined`로 지정됩니다. ## Events From 57115a447c74db99a497238ebe1d992918ea1462 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:04:39 +0900 Subject: [PATCH 0567/1265] :memo: Update `README-ko.md` [ci skip] --- README-ko.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README-ko.md b/README-ko.md index 246898d2a14..ffb984c3275 100644 --- a/README-ko.md +++ b/README-ko.md @@ -1,8 +1,8 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) -[![Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron) +[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) -[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies) +[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron#info=devDependencies) [![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/) ### [Electron](https://github.com/electron/electron/) 한국어 참조문서 @@ -62,7 +62,7 @@ API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝 ## 시작하기 -[`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) +[`electron/electron-quick-start`](https://github.com/electron/electron-quick-start) 저장소를 클론하여 Electron을 간단히 접해볼 수 있습니다. ## 커뮤니티 From 552609db73ff4b616eaace2a283e9591bf1fd5cc Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:11:02 +0900 Subject: [PATCH 0568/1265] :memo: Apply small fixes [ci skip] --- CONTRIBUTING-ko.md | 6 +++--- README-ko.md | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTING-ko.md b/CONTRIBUTING-ko.md index 1c938d434b1..5e87fcdc996 100644 --- a/CONTRIBUTING-ko.md +++ b/CONTRIBUTING-ko.md @@ -1,10 +1,10 @@ # Electron에 기여하기 -:+1::tada: 먼저, 이 프로젝트에 기여해주셔서 감사합니다! :tada::+1: +:+1::tada: 먼저, 기여에 관심을 가져주셔서 감사합니다! :tada::+1: -이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이 +이 프로젝트는 기여자 규약인 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이 프로젝트의 개발에 참여하려면 이 규약을 지켜야 합니다. 받아들일 수 없는 행위를 발견했을 -경우 atom@github.com로 보고 하십시오. +경우 atom@github.com로 보고하세요. 다음 항목들은 Electron에 기여하는 가이드라인을 제시합니다. 참고로 이 항목들은 그저 가이드라인에 불과하며 규칙이 아닙니다. 따라서 스스로의 적절한 diff --git a/README-ko.md b/README-ko.md index ffb984c3275..a3dd38124fa 100644 --- a/README-ko.md +++ b/README-ko.md @@ -17,15 +17,15 @@ Cross-Platform 데스크톱 어플리케이션을 개발할 수 있도록 해주 Electron에 대한 중요한 알림을 받고 싶다면 Twitter에서 [@ElectronJS](https://twitter.com/electronjs)를 팔로우 하세요. -이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이 +이 프로젝트는 기여자 규약인 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이 프로젝트의 개발에 참여하려면 이 규약을 지켜야 합니다. 받아들일 수 없는 행위를 발견했을 -경우 atom@github.com로 보고 하십시오. +경우 atom@github.com로 보고하세요. ## 다운로드 Linux, Windows, OS X 용으로 미리 빌드된 Electron 바이너리와 디버그 심볼이 준비되어 -있습니다. [releases](https://github.com/electron/electron/releases) 페이지에서 받아 볼 -수 있습니다. +있습니다. [releases](https://github.com/electron/electron/releases) 페이지에서 +받아 볼 수 있습니다. 또한 [`npm`](https://docs.npmjs.com/)을 통해 미리 빌드된 Electron 바이너리를 설치할 수도 있습니다: @@ -44,9 +44,9 @@ npm install electron-prebuilt --save-dev ## 참조 문서 -[Docs](https://github.com/electron/electron/tree/master/docs/README.md)에 개발 지침과 -API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝트에 기여하는법 또한 문서에 -포함되어 있으니 참고하시기 바랍니다. +[Docs](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/README.md)에 +개발 지침과 API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝트에 기여하는법 +또한 문서에 포함되어 있으니 참고하시기 바랍니다. ## 참조 문서 (번역) From 08dbd35cedd223b32b2cbe59b0fdb74010e2eaa7 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:14:42 +0900 Subject: [PATCH 0569/1265] :memo: Apply small fixes [ci skip] --- CONTRIBUTING-ko.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING-ko.md b/CONTRIBUTING-ko.md index 5e87fcdc996..cb687f9227a 100644 --- a/CONTRIBUTING-ko.md +++ b/CONTRIBUTING-ko.md @@ -29,8 +29,8 @@ ## Pull Request 하기 * 가능한한 스크린샷과 GIF 애니메이션 이미지를 pull request에 추가 -* CoffeeScript, JavaScript, C++과 Python등 -[참조문서에 정의된 코딩스타일](/docs-translations/ko-KR/development/coding-style.md)을 +* JavaScript, C++과 Python등 +[참조 문서에 정의된 코딩스타일](/docs-translations/ko-KR/development/coding-style.md)을 준수 * [문서 스타일 가이드](/docs-translations/ko-KR/styleguide.md)에 따라 문서를 [Markdown](https://daringfireball.net/projects/markdown) 형식으로 작성. From 0282180b9c4ec0ee16385b3b002857e9bb1e4a6a Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:20:41 +0900 Subject: [PATCH 0570/1265] :memo: Correct description style [ci skip] --- docs/api/desktop-capturer.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index bf775c3a6d2..b39a09e5aa8 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -40,7 +40,7 @@ function getUserMediaError(e) { When creating a constraints object for the `navigator.webkitGetUserMedia` call, if you are using a source from `desktopCapturer` your `chromeMediaSource` must -be set to `"desktop"` and your `audio` must be set to `false`. +be set to `"desktop"` and your `audio` must be set to `false`. If you wish to capture the audio and video from the entire desktop you can set @@ -72,7 +72,7 @@ captured screen or individual window, and has following properties: * `name` String - The described name of the capturing screen or window. If the source is a screen, the name will be `Entire Screen` or `Screen `; if it is a window, the name will be the window's title. -* `thumbnail` A thumbnail [native image](native-image.md). +* `thumbnail` [NativeImage](native-image.md) - A thumbnail native image. **Note:** There is no guarantee that the size of `source.thumbnail` is always the same as the `thumnbailSize` in `options`. It also depends on the scale of From 4f4277e25e2207a879501d0fc76be28b4a9d3b1f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:53:26 +0900 Subject: [PATCH 0571/1265] :memo: Fix coding style issues * Adjust line length to `80` * Normalize whitespaces [ci skip] --- docs/api/app.md | 4 ++-- docs/api/auto-updater.md | 7 +++++-- docs/api/browser-window.md | 13 ++++++------ docs/api/crash-reporter.md | 3 ++- docs/api/dialog.md | 3 ++- docs/api/frameless-window.md | 8 ++++++-- docs/api/menu-item.md | 9 +++++---- docs/api/process.md | 4 ++-- docs/api/session.md | 5 +++-- docs/api/synopsis.md | 4 ++-- docs/api/web-contents.md | 13 +++++++----- docs/api/web-view-tag.md | 20 +++++++++---------- docs/development/build-instructions-osx.md | 4 ++-- .../development/build-instructions-windows.md | 3 ++- docs/development/build-system-overview.md | 5 +++-- docs/development/coding-style.md | 6 ++++-- docs/faq/electron-faq.md | 4 ++-- docs/tutorial/debugging-main-process.md | 5 +++-- .../desktop-environment-integration.md | 3 +-- docs/tutorial/quick-start.md | 4 ++-- 20 files changed, 73 insertions(+), 54 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index c8ddb47bd31..f86a205e6f9 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -523,8 +523,8 @@ This method returns `true` if the system is in Dark Mode, and `false` otherwise. * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. -`callback` is called with the `result` of import operation, a value of `0` indicates -success while any other value indicates failure according to chromium [net_error_list](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h). +`callback` is called with the `result` of import operation, a value of `0` +indicates success while any other value indicates failure according to chromium [net_error_list](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h). ### `app.commandLine.appendSwitch(switch[, value])` diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 8dd6d2412a4..dccae1212aa 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -5,8 +5,11 @@ This module provides an interface for the `Squirrel` auto-updater framework. You can quickly launch a multi-platform release server for distributing your application by using one of these projects: -- [electron-release-server][electron-release-server]: *A fully featured, self-hosted release server for electron applications, compatible with auto-updater* -- [squirrel-updates-server][squirrel-updates-server]: *A simple node.js server for Squirrel.Mac and Squirrel.Windows which uses GitHub releases* +- [electron-release-server][electron-release-server]: *A fully featured, + self-hosted release server for electron applications, compatible with + auto-updater* +- [squirrel-updates-server][squirrel-updates-server]: *A simple node.js server + for Squirrel.Mac and Squirrel.Windows which uses GitHub releases* ## Platform notices diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 67f8c737a0c..97dd2d97295 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -311,7 +311,8 @@ Emitted when an [App Command](https://msdn.microsoft.com/en-us/library/windows/d is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. -Commands are lowercased with underscores replaced with hyphens and the `APPCOMMAND_` prefix stripped off. +Commands are lowercased with underscores replaced with hyphens and the +`APPCOMMAND_` prefix stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```js @@ -677,9 +678,9 @@ window. ### `win.setSheetOffset(offset)` -Changes the attachment point for sheets on Mac OS X. By default, sheets are attached -just below the window frame, but you may want to display them beneath a HTML-rendered -toolbar. For example: +Changes the attachment point for sheets on Mac OS X. By default, sheets are +attached just below the window frame, but you may want to display them beneath +a HTML-rendered toolbar. For example: ``` var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); @@ -823,8 +824,8 @@ cleared * `description` String - a description that will be provided to Accessibility screen readers -Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some -sort of application status or to passively notify the user. +Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to +convey some sort of application status or to passively notify the user. ### `win.setHasShadow(hasShadow)` _OS X_ diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 64e5602474a..9b7141e364e 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -60,7 +60,8 @@ ID. ## crash-reporter Payload -The crash reporter will send the following data to the `submitURL` as a `multipart/form-data` `POST`: +The crash reporter will send the following data to the `submitURL` as +a `multipart/form-data` `POST`: * `ver` String - The version of Electron. * `platform` String - e.g. 'win32'. diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 1cea9da119a..3eb0292a493 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -12,7 +12,8 @@ const dialog = require('electron').dialog; console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]})); ``` -The Dialog is opened from Electron's main thread. If you want to use the dialog object from a renderer process, remember to access it using the remote: +The Dialog is opened from Electron's main thread. If you want to use the dialog +object from a renderer process, remember to access it using the remote: ```javascript const dialog = require('electron').remote.dialog; diff --git a/docs/api/frameless-window.md b/docs/api/frameless-window.md index 3c26a36b032..8e1dd46ec56 100644 --- a/docs/api/frameless-window.md +++ b/docs/api/frameless-window.md @@ -1,6 +1,9 @@ # Frameless Window -A frameless window is a window that has no [chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome), the parts of the window, like toolbars, that are not a part of the web page. These are options on the [`BrowserWindow`](browser-window.md) class. +A frameless window is a window that has no +[chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome), the parts of +the window, like toolbars, that are not a part of the web page. These are +options on the [`BrowserWindow`](browser-window.md) class. ## Create a frameless window @@ -38,7 +41,8 @@ var win = new BrowserWindow({ transparent: true, frame: false }); ### Limitations * You can not click through the transparent area. We are going to introduce an - API to set window shape to solve this, see [our issue](https://github.com/electron/electron/issues/1335) for details. + API to set window shape to solve this, see + [our issue](https://github.com/electron/electron/issues/1335) for details. * Transparent windows are not resizable. Setting `resizable` to `true` may make a transparent window stop working on some platforms. * The `blur` filter only applies to the web page, so there is no way to apply diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index 0029ba14dd4..1b36432ab29 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -22,9 +22,10 @@ Create a new `MenuItem` with the following method: * `sublabel` String * `accelerator` [Accelerator](accelerator.md) * `icon` [NativeImage](native-image.md) - * `enabled` Boolean - If false, the menu item will be greyed out and unclickable. + * `enabled` Boolean - If false, the menu item will be greyed out and + unclickable. * `visible` Boolean - If false, the menu item will be entirely hidden. - * `checked` Boolean - Should only be specified for `checkbox` or `radio` type + * `checked` Boolean - Should only be specified for `checkbox` or `radio` type menu items. * `submenu` Menu - Should be specified for `submenu` type menu items. If `submenu` is specified, the `type: 'submenu'` can be omitted. If the value @@ -61,7 +62,8 @@ On OS X `role` can also have following additional values: * `help` - The submenu is a "Help" menu * `services` - The submenu is a "Services" menu -When specifying `role` on OS X, `label` and `accelerator` are the only options that will affect the MenuItem. All other options will be ignored. +When specifying `role` on OS X, `label` and `accelerator` are the only options +that will affect the MenuItem. All other options will be ignored. ## Instance Properties @@ -79,4 +81,3 @@ selected. You can add a `click` function to do additional work. A `radio` menu item will turn on its `checked` property when clicked, and will turn off that property for all adjacent items in the same menu. Again, you can add a `click` function for additional behavior. - diff --git a/docs/api/process.md b/docs/api/process.md index b2d9c765a03..ce76eb2d99a 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -10,8 +10,8 @@ upstream node: * `process.resourcesPath` String - Path to JavaScript source code. * `process.mas` Boolean - For Mac App Store build, this value is `true`, for other builds it is `undefined`. -* `process.windowsStore` Boolean - If the app is running as a Windows Store app (appx), this value is `true`, for - other builds it is `undefined`. +* `process.windowsStore` Boolean - If the app is running as a Windows Store app + (appx), this value is `true`, for other builds it is `undefined`. ## Events diff --git a/docs/api/session.md b/docs/api/session.md index ecc65f550ed..b8ea23434cd 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -447,8 +447,9 @@ The `callback` has to be called with an `response` object: * `cancel` Boolean * `responseHeaders` Object (optional) - When provided, the server is assumed to have responded with these headers. - * `statusLine` String (optional) - Should be provided when overriding `responseHeaders` - to change header status otherwise original response header's status will be used. + * `statusLine` String (optional) - Should be provided when overriding + `responseHeaders` to change header status otherwise original response + header's status will be used. #### `ses.webRequest.onResponseStarted([filter, ]listener)` diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index 015674c2ef6..466b13828c4 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -11,8 +11,8 @@ both processes. The basic rule is: if a module is [GUI][gui] or low-level 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. +the concept of [main process vs. renderer process](../tutorial/quick-start.md#the-main-process) +scripts to be able to use those modules. The main process script is just like a normal Node.js script: diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 9acceadd360..0eee6c5bf8b 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -278,7 +278,8 @@ Emitted when media is paused or done playing. ### Event: 'did-change-theme-color' -Emitted when a page's theme color changes. This is usually due to encountering a meta tag: +Emitted when a page's theme color changes. This is usually due to encountering +a meta tag: ```html @@ -355,7 +356,8 @@ Returns whether web page is still loading resources. ### `webContents.isLoadingMainFrame()` -Returns whether the main frame (and not just iframes or frames within it) is still loading. +Returns whether the main frame (and not just iframes or frames within it) is +still loading. ### `webContents.isWaitingForResponse()` @@ -525,9 +527,10 @@ Inserts `text` to the focused element. uppercase letter followed by a lowercase or non-letter. Accepts several other intra-word matches, defaults to `false`. -Starts a request to find all matches for the `text` in the web page and returns an `Integer` -representing the request id used for the request. The result of the request can be -obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. +Starts a request to find all matches for the `text` in the web page and returns +an `Integer` representing the request id used for the request. The result of +the request can be obtained by subscribing to +[`found-in-page`](web-contents.md#event-found-in-page) event. ### `webContents.stopFindInPage(action)` diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index c77d3c690b8..214f93dbad6 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -47,17 +47,17 @@ and displays a "loading..." message during the load time: ## CSS Styling Notes -Please note that the `webview` tag's style uses `display:flex;` internally to -ensure the child `object` element fills the full height and width of its `webview` -container when used with traditional and flexbox layouts (since v0.36.11). Please -do not overwrite the default `display:flex;` CSS property, unless specifying +Please note that the `webview` tag's style uses `display:flex;` internally to +ensure the child `object` element fills the full height and width of its `webview` +container when used with traditional and flexbox layouts (since v0.36.11). Please +do not overwrite the default `display:flex;` CSS property, unless specifying `display:inline-flex;` for inline layout. -`webview` has issues being hidden using the `hidden` attribute or using `display: none;`. -It can cause unusual rendering behaviour within its child `browserplugin` object -and the web page is reloaded, when the `webview` is un-hidden, as opposed to just -becoming visible again. The recommended approach is to hide the `webview` using -CSS by zeroing the `width` & `height` and allowing the element to shrink to the 0px +`webview` has issues being hidden using the `hidden` attribute or using `display: none;`. +It can cause unusual rendering behaviour within its child `browserplugin` object +and the web page is reloaded, when the `webview` is un-hidden, as opposed to just +becoming visible again. The recommended approach is to hide the `webview` using +CSS by zeroing the `width` & `height` and allowing the element to shrink to the 0px dimensions via `flex`. ```html @@ -70,7 +70,7 @@ dimensions via `flex`. webview.hide { flex: 0 1; width: 0px; - height: 0px; + height: 0px; } ``` diff --git a/docs/development/build-instructions-osx.md b/docs/development/build-instructions-osx.md index 02bdb72e227..b703a75897d 100644 --- a/docs/development/build-instructions-osx.md +++ b/docs/development/build-instructions-osx.md @@ -22,8 +22,8 @@ $ git clone https://github.com/electron/electron.git ## Bootstrapping The bootstrap script will download all necessary build dependencies and create -the build project files. Notice that we're using [ninja](https://ninja-build.org/) to build Electron so -there is no Xcode project generated. +the build project files. Notice that we're using [ninja](https://ninja-build.org/) +to build Electron so there is no Xcode project generated. ```bash $ cd electron diff --git a/docs/development/build-instructions-windows.md b/docs/development/build-instructions-windows.md index 73526b36258..3f94a18393c 100644 --- a/docs/development/build-instructions-windows.md +++ b/docs/development/build-instructions-windows.md @@ -11,7 +11,8 @@ Follow the guidelines below for building Electron on Windows. * [Node.js](http://nodejs.org/download/) * [Git](http://git-scm.com) -If you don't currently have a Windows installation, [modern.ie](https://www.modern.ie/en-us/virtualization-tools#downloads) +If you don't currently have a Windows installation, +[modern.ie](https://www.modern.ie/en-us/virtualization-tools#downloads) has timebombed versions of Windows that you can use to build Electron. Building Electron is done entirely with command-line scripts and cannot be done diff --git a/docs/development/build-system-overview.md b/docs/development/build-system-overview.md index 61b88e14078..bc27c1932fa 100644 --- a/docs/development/build-system-overview.md +++ b/docs/development/build-system-overview.md @@ -1,7 +1,8 @@ # Build System Overview -Electron uses [gyp](https://gyp.gsrc.io/) for project generation and [ninja](https://ninja-build.org/) for building. Project -configurations can be found in the `.gyp` and `.gypi` files. +Electron uses [gyp](https://gyp.gsrc.io/) for project generation and +[ninja](https://ninja-build.org/) for building. Project configurations can +be found in the `.gyp` and `.gypi` files. ## Gyp Files diff --git a/docs/development/coding-style.md b/docs/development/coding-style.md index baf2a2cce7d..1840700f523 100644 --- a/docs/development/coding-style.md +++ b/docs/development/coding-style.md @@ -45,8 +45,10 @@ Electron APIs uses the same capitalization scheme as Node.js: - When the module itself is a class like `BrowserWindow`, use `CamelCase`. - When the module is a set of APIs, like `globalShortcut`, use `mixedCase`. -- When the API is a property of object, and it is complex enough to be in a separate chapter like `win.webContents`, use `mixedCase`. -- For other non-module APIs, use natural titles, like ` Tag` or `Process Object`. +- When the API is a property of object, and it is complex enough to be in a + separate chapter like `win.webContents`, use `mixedCase`. +- For other non-module APIs, use natural titles, like ` Tag` or + `Process Object`. When creating a new API, it is preferred to use getters and setters instead of jQuery's one-function style. For example, `.getText()` and `.setText(text)` diff --git a/docs/faq/electron-faq.md b/docs/faq/electron-faq.md index 41b301d7198..02d72744e65 100644 --- a/docs/faq/electron-faq.md +++ b/docs/faq/electron-faq.md @@ -77,8 +77,8 @@ app.on('ready', function() { ## I can not use jQuery/RequireJS/Meteor/AngularJS in Electron. Due to the Node.js integration of Electron, there are some extra symbols -inserted into the DOM like `module`, `exports`, `require`. This causes problems for -some libraries since they want to insert the symbols with the same names. +inserted into the DOM like `module`, `exports`, `require`. This causes problems +for some libraries since they want to insert the symbols with the same names. To solve this, you can turn off node integration in Electron: diff --git a/docs/tutorial/debugging-main-process.md b/docs/tutorial/debugging-main-process.md index ee7fc4c5fa4..714b7100cf4 100644 --- a/docs/tutorial/debugging-main-process.md +++ b/docs/tutorial/debugging-main-process.md @@ -68,9 +68,10 @@ $ ELECTRON_RUN_AS_NODE=true path/to/electron.exe node_modules/node-inspector/bin ### 7. Load the debugger UI -Open http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858 in the Chrome browser. You may have to click pause if starting with debug-brk to see the entry line. +Open http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858 in the Chrome +browser. You may have to click pause if starting with debug-brk to see the +entry line. [node-inspector]: https://github.com/node-inspector/node-inspector [node-gyp-required-tools]: https://github.com/nodejs/node-gyp#installation [how-to-install-native-modules]: using-native-node-modules.md#how-to-install-native-modules - diff --git a/docs/tutorial/desktop-environment-integration.md b/docs/tutorial/desktop-environment-integration.md index 1186918799b..110d2917ab4 100644 --- a/docs/tutorial/desktop-environment-integration.md +++ b/docs/tutorial/desktop-environment-integration.md @@ -53,8 +53,7 @@ GNOME, KDE. ### OS X Notifications are straight-forward on OS X, you should however be aware of -[Apple's Human Interface guidelines regarding -notifications](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/OSXHIGuidelines/NotificationCenter.html). +[Apple's Human Interface guidelines regarding notifications](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/OSXHIGuidelines/NotificationCenter.html). Note that notifications are limited to 256 bytes in size - and will be truncated if you exceed that limit. diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md index 2a41d6356a8..ddbda378244 100644 --- a/docs/tutorial/quick-start.md +++ b/docs/tutorial/quick-start.md @@ -147,8 +147,8 @@ working as expected. ### electron-prebuilt -If you've installed `electron-prebuilt` globally with `npm`, then you will only need -to run the following in your app's source directory: +If you've installed `electron-prebuilt` globally with `npm`, then you will only +need to run the following in your app's source directory: ```bash electron . From c72bb6df33488f4069cfb42f6a5994a969f4c3e5 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:55:38 +0900 Subject: [PATCH 0572/1265] :memo: Remove unused link reference [ci skip] --- docs/tutorial/mac-app-store-submission-guide.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index c80885f5a56..404dcb80efb 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -183,6 +183,5 @@ ERN)][ern-tutorial]. [create-record]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/CreatingiTunesConnectRecord.html [submit-for-review]: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html [app-sandboxing]: https://developer.apple.com/app-sandboxing/ -[issue-3871]: https://github.com/electron/electron/issues/3871 [ern-tutorial]: https://carouselapps.com/2015/12/15/legally-submit-app-apples-app-store-uses-encryption-obtain-ern/ [temporary-exception]: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html From cbc2a869e3a6568da9390fa6b04a101aecbd1a8f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 22:56:24 +0900 Subject: [PATCH 0573/1265] :memo: Fix typos [ci skip] --- docs/api/screen.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/screen.md b/docs/api/screen.md index 4d12f1359f7..90ef183a8a8 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -1,7 +1,7 @@ # screen The `screen` module retrieves information about screen size, displays, cursor -position, etc. You cannot not use this module until the `ready` event of the +position, etc. You can not use this module until the `ready` event of the `app` module is emitted (by invoking or requiring it). `screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). From 741f8091b45122c0257b5a47b7a13036e9d30a7c Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:09:59 +0900 Subject: [PATCH 0574/1265] :memo: Fix coding style issues * Correct heading order * Adjust line length to `80` * Beautify docs * Apply small fixes * Normalize whitespaces [ci skip] --- .../development/debug-instructions-windows.md | 105 +++++++++++++----- 1 file changed, 80 insertions(+), 25 deletions(-) diff --git a/docs/development/debug-instructions-windows.md b/docs/development/debug-instructions-windows.md index 3070bf33443..3a1a05e1103 100644 --- a/docs/development/debug-instructions-windows.md +++ b/docs/development/debug-instructions-windows.md @@ -1,38 +1,93 @@ # Debugging Electron in Windows -If you experience crashes or issues in Electron that you believe are not caused by your JavaScript application, but instead by Electron itself, debugging can be a little bit tricky, especially for developers not used to native/C++ debugging. However, using Visual Studio, GitHub's hosted Electron Symbol Server, and the Electron source code, it is fairly easy to enable step-through debugging with breakpoints inside Electron's source code. -### Requirements - * **A debug build of Electron**: The easiest way is usually building it yourself, using the tools and prerequisites listed in the [build instructions for Windows](build-instructions-osx.md). While you can easily attach to and debug Electron as you can download it directly, you will find that it is heavily optimized, making debugging substantially more difficult: The debugger will not be able to show you the content of all variables and the execution path can seem strange because of inlining, tail calls, and other compiler optimizations. - - * **Visual Studio with C++ Tools**: The free community editions of [Visual Studio 2013]() and [Visual Studio 2015]() both work. - - Once installed, [configure Visual Studio to use GitHub's Electron Symbol server](setting-up-symbol-server.md). It will enable Visual Studio to gain a better understanding of what happens inside Electron, making it easier to present variables in a human-readable format. - - * **ProcMon**: The [free SysInternals tool](https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx) allows you to inspect a processes parameters, file handles, and registry operations. - -# Attaching to and Debugging Electron -To start a debugging session, open up PowerShell/CMD and execute your debug build of Electron, using the application to open as a parameter. +If you experience crashes or issues in Electron that you believe are not caused +by your JavaScript application, but instead by Electron itself, debugging can +be a little bit tricky, especially for developers not used to native/C++ +debugging. However, using Visual Studio, GitHub's hosted Electron Symbol Server, +and the Electron source code, it is fairly easy to enable step-through debugging +with breakpoints inside Electron's source code. -``` -./out/D/electron.exe ~/my-electron-app/ +## Requirements + +* **A debug build of Electron**: The easiest way is usually building it + yourself, using the tools and prerequisites listed in the + [build instructions for Windows](build-instructions-osx.md). While you can + easily attach to and debug Electron as you can download it directly, you will + find that it is heavily optimized, making debugging substantially more + difficult: The debugger will not be able to show you the content of all + variables and the execution path can seem strange because of inlining, + tail calls, and other compiler optimizations. + +* **Visual Studio with C++ Tools**: The free community editions of Visual + Studio 2013 and Visual Studio 2015 both work. Once installed, + [configure Visual Studio to use GitHub's Electron Symbol server](setting-up-symbol-server.md). + It will enable Visual Studio to gain a better understanding of what happens + inside Electron, making it easier to present variables in a human-readable + format. + +* **ProcMon**: The [free SysInternals tool][sys-internals] allows you to inspect + a processes parameters, file handles, and registry operations. + +## Attaching to and Debugging Electron + +To start a debugging session, open up PowerShell/CMD and execute your debug +build of Electron, using the application to open as a parameter. + +```powershell +$ ./out/D/electron.exe ~/my-electron-app/ ``` -## Setting Breakpoints -Then, open up Visual Studio. Electron is not built with Visual Studio and hence does not contain a project file - you can however open up the source code files "As File", meaning that Visual Studio will open them up by themselves. You can still set breakpoints - Visual Studio will automatically figure out that the source code matches the code running in the attached process and break accordingly. +### Setting Breakpoints -Relevant code files can be found in `./atom/` as well as in Brightray, found in `./vendor/brightray/browser` and `./vendor/brightray/common`. If you're hardcore, you can also debug Chromium directly, which is obviously found in `chromium_src`. +Then, open up Visual Studio. Electron is not built with Visual Studio and hence +does not contain a project file - you can however open up the source code files +"As File", meaning that Visual Studio will open them up by themselves. You can +still set breakpoints - Visual Studio will automatically figure out that the +source code matches the code running in the attached process and break +accordingly. -## Attaching -You can attach the Visual Studio debugger to a running process on a local or remote computer. After the process is running, click Debug / Attach to Process (or press `CTRL+ALT+P`) to open the "Attach to Process" dialog box. You can use this capability to debug apps that are running on a local or remote computer, debug multiple processes simultaneously. +Relevant code files can be found in `./atom/` as well as in Brightray, found in +`./vendor/brightray/browser` and `./vendor/brightray/common`. If you're hardcore, +you can also debug Chromium directly, which is obviously found in `chromium_src`. -If Electron is running under a different user account, select the `Show processes from all users` check box. Notice that depending on how many BrowserWindows your app opened, you will see multiple processes. A typical one-window app will result in Visual Studio presenting you with two `Electron.exe` entries - one for the main process and one for the renderer process. Since the list only gives you names, there's currently no reliable way of figuring out which is which. +### Attaching -#### Which Process Should I Attach to? -Code executed within the main process (that is, code found in or eventually run by your main JavaScript file) as well as code called using the remote (`require('electron').remote`) will run inside the main process, while other code will execute inside its respective renderer process. +You can attach the Visual Studio debugger to a running process on a local or +remote computer. After the process is running, click Debug / Attach to Process +(or press `CTRL+ALT+P`) to open the "Attach to Process" dialog box. You can use +this capability to debug apps that are running on a local or remote computer, +debug multiple processes simultaneously. -You can be attached to multiple programs when you are debugging, but only one program is active in the debugger at any time. You can set the active program in the `Debug Location` toolbar or the `Processes window`. +If Electron is running under a different user account, select the +`Show processes from all users` check box. Notice that depending on how many +BrowserWindows your app opened, you will see multiple processes. A typical +one-window app will result in Visual Studio presenting you with two +`Electron.exe` entries - one for the main process and one for the renderer +process. Since the list only gives you names, there's currently no reliable +way of figuring out which is which. + +### Which Process Should I Attach to? + +Code executed within the main process (that is, code found in or eventually run +by your main JavaScript file) as well as code called using the remote +(`require('electron').remote`) will run inside the main process, while other +code will execute inside its respective renderer process. + +You can be attached to multiple programs when you are debugging, but only one +program is active in the debugger at any time. You can set the active program +in the `Debug Location` toolbar or the `Processes window`. ## Using ProcMon to Observe a Process -While Visual Studio is fantastic for inspecting specific code paths, ProcMon's strength is really in observing everything your application is doing with the operating system - it captures File, Registry, Network, Process, and Profiling details of processes. It attempts to log *all* events occurring and can be quite overwhelming, but if you seek to understand what and how your application is doing to the operating system, it can be a valuable resource. -For an introduction to ProcMon's basic and advanced debugging features, go check out [this video tutorial](https://channel9.msdn.com/shows/defrag-tools/defrag-tools-4-process-monitor) provided by Microsoft. \ No newline at end of file +While Visual Studio is fantastic for inspecting specific code paths, ProcMon's +strength is really in observing everything your application is doing with the +operating system - it captures File, Registry, Network, Process, and Profiling +details of processes. It attempts to log **all** events occurring and can be +quite overwhelming, but if you seek to understand what and how your application +is doing to the operating system, it can be a valuable resource. + +For an introduction to ProcMon's basic and advanced debugging features, go check +out [this video tutorial][procmon-instructions] provided by Microsoft. + +[sys-internals]: https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx +[procmon-instructions]: https://channel9.msdn.com/shows/defrag-tools/defrag-tools-4-process-monitor From b862cee6ec2d55fdb332cd15f66554212e1f59d6 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:11:39 +0900 Subject: [PATCH 0575/1265] :memo: Correct heading order [ci skip] --- .../ko-KR/development/debug-instructions-windows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/ko-KR/development/debug-instructions-windows.md b/docs-translations/ko-KR/development/debug-instructions-windows.md index eb738f15508..a0d50e475c7 100644 --- a/docs-translations/ko-KR/development/debug-instructions-windows.md +++ b/docs-translations/ko-KR/development/debug-instructions-windows.md @@ -61,7 +61,7 @@ $ ./out/D/electron.exe ~/my-electron-app/ 메인 프로세스이며 다른 하나는 렌더러 프로세스입니다. 리스트는 단지 이름 하나만 제공하기 때문에 현재까지는 다른 적절한 프로세스 판별법이 없습니다. -## 어떤 프로세스에 디버거를 적용해야 하나요? +### 어떤 프로세스에 디버거를 적용해야 하나요? 코드는 메인 프로세스 내에서 실행되며 (이는 코드를 안에서 찾을 수 있거나, 결국 메인 Javascript 파일에 의해 실행) remote (`require('electron').remote`)를 사용하여 From 7fa4b7c8b59531f7fa336e3c282d8d912bf933eb Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:15:31 +0900 Subject: [PATCH 0576/1265] :memo: Normalize code tags [ci skip] --- docs/api/app.md | 4 ++-- docs/api/browser-window.md | 4 ++-- docs/api/process.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index f86a205e6f9..54e40263eab 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -453,7 +453,7 @@ use this method to ensure single instance. An example of activating the window of primary instance when a second instance starts: -```js +```javascript var myWindow = null; var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) { @@ -489,7 +489,7 @@ correctly when DWM composition is disabled). Usage example: -```js +```javascript let browserOptions = {width: 1000, height: 800}; // Make the window transparent only if the platform supports it. diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 97dd2d97295..29073c7539b 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -315,7 +315,7 @@ Commands are lowercased with underscores replaced with hyphens and the `APPCOMMAND_` prefix stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. -```js +```javascript someWindow.on('app-command', function(e, cmd) { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && someWindow.webContents.canGoBack()) { @@ -682,7 +682,7 @@ Changes the attachment point for sheets on Mac OS X. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: -``` +```javascript var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win.setSheetOffset(toolbarRect.height); ``` diff --git a/docs/api/process.md b/docs/api/process.md index ce76eb2d99a..17c0be10926 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -23,7 +23,7 @@ beginning to load the web page or the main script. It can be used by the preload script to add removed Node global symbols back to the global scope when node integration is turned off: -```js +```javascript // preload.js var _setImmediate = setImmediate; var _clearImmediate = clearImmediate; From b6f8dcea20dfd4d21e04046e17f58ac2face91b8 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:21:42 +0900 Subject: [PATCH 0577/1265] :memo: Add missing platform specified tag [ci skip] --- docs/api/browser-window.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 29073c7539b..c2497281526 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -676,7 +676,7 @@ Returns the title of the native window. **Note:** The title of web page can be different from the title of the native window. -### `win.setSheetOffset(offset)` +### `win.setSheetOffset(offset)` _OS X_ Changes the attachment point for sheets on Mac OS X. By default, sheets are attached just below the window frame, but you may want to display them beneath From 66f4701d937a882fa02881eb9e03c8b6d5be6db7 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:23:15 +0900 Subject: [PATCH 0578/1265] :memo: Remove additional whitespaces [ci skip] --- docs/api/session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/session.md b/docs/api/session.md index b8ea23434cd..c668ef7e45f 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -295,9 +295,9 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c * `handler` Function * `webContents` Object - [WebContents](web-contents.md) requesting the permission. - * `permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex', + * `permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex', 'pointerLock', 'fullscreen', 'openExternal'. - * `callback` Function - Allow or deny the permission. + * `callback` Function - Allow or deny the permission. Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. From ba9fa95653251ed04bb4a00c4f0c65fe840d01ed Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:23:39 +0900 Subject: [PATCH 0579/1265] :memo: Remove additional whitespaces [ci skip] --- docs-translations/ko-KR/api/session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index 077cb1867c6..76a3fc9ea83 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -293,9 +293,9 @@ myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, c * `handler` Function * `webContents` Object - [WebContents](web-contents.md) 권한을 요청. - * `permission` String - 'media', 'geolocation', 'notifications', + * `permission` String - 'media', 'geolocation', 'notifications', 'midiSysex', 'pointerLock', 'fullscreen', 'openExternal'의 나열. - * `callback` Function - 권한 허용 및 거부. + * `callback` Function - 권한 허용 및 거부. `session`의 권한 요청에 응답을 하는데 사용하는 핸들러를 설정합니다. `callback(true)`를 호출하면 권한 제공을 허용하고 `callback(false)`를 From a14014941b8b40642ecef256c9da5838fb38f0f1 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:26:19 +0900 Subject: [PATCH 0580/1265] :memo: Fix coding style issues [ci skip] --- docs/api/session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/session.md b/docs/api/session.md index c668ef7e45f..9490de1f668 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -422,7 +422,7 @@ response are visible by the time this listener is fired. * `timestamp` Double * `requestHeaders` Object -#### `ses.webRequest.onHeadersReceived([filter,] listener)` +#### `ses.webRequest.onHeadersReceived([filter,]listener)` * `filter` Object * `listener` Function From 6205dfa25f9b776fe6dfdba2502ad6443c4a404f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 22 Apr 2016 23:30:16 +0900 Subject: [PATCH 0581/1265] :memo: Remove additional whitespaces [ci skip] --- docs/api/session.md | 2 +- docs/development/source-code-directory-structure.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/session.md b/docs/api/session.md index 9490de1f668..90030180363 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -467,7 +467,7 @@ and response headers are available. * `resourceType` String * `timestamp` Double * `responseHeaders` Object - * `fromCache` Boolean - Indicates whether the response was fetched from disk + * `fromCache` Boolean - Indicates whether the response was fetched from disk cache. * `statusCode` Integer * `statusLine` String diff --git a/docs/development/source-code-directory-structure.md b/docs/development/source-code-directory-structure.md index b2672def654..27cf36b9d4e 100644 --- a/docs/development/source-code-directory-structure.md +++ b/docs/development/source-code-directory-structure.md @@ -34,7 +34,7 @@ Electron ├── default_app - The default page to show when Electron is started without | providing an app. ├── docs - Documentations. -├── lib - JavaScript source code. +├── lib - JavaScript source code. | ├── browser - Javascript main process initialization code. | | └── api - Javascript API implementation. | ├── common - JavaScript used by both the main and renderer processes From ee190ca62aa0595b23396544667dcc63bb83667c Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 21 Apr 2016 15:35:29 -0700 Subject: [PATCH 0582/1265] create a one-liner description for each API --- docs/api/accelerator.md | 6 ++++-- docs/api/app.md | 2 +- docs/api/auto-updater.md | 4 +++- docs/api/browser-window.md | 3 +-- docs/api/chrome-command-line-switches.md | 9 +++++---- docs/api/clipboard.md | 3 ++- docs/api/content-tracing.md | 5 +++-- docs/api/crash-reporter.md | 2 +- docs/api/desktop-capturer.md | 4 ++-- docs/api/dialog.md | 4 +--- docs/api/download-item.md | 2 ++ docs/api/environment-variables.md | 2 ++ docs/api/file-object.md | 2 ++ docs/api/frameless-window.md | 2 ++ docs/api/global-shortcut.md | 2 ++ docs/api/ipc-main.md | 2 ++ docs/api/ipc-renderer.md | 2 ++ docs/api/menu-item.md | 3 +-- docs/api/menu.md | 5 ++--- docs/api/native-image.md | 2 ++ docs/api/power-monitor.md | 5 +++-- docs/api/power-save-blocker.md | 4 +--- docs/api/process.md | 2 ++ docs/api/protocol.md | 4 ++-- docs/api/remote.md | 2 ++ docs/api/screen.md | 7 ++++--- docs/api/session.md | 2 ++ docs/api/shell.md | 2 ++ docs/api/synopsis.md | 2 ++ docs/api/tray.md | 3 +-- docs/api/web-contents.md | 3 ++- docs/api/web-frame.md | 3 +-- docs/api/web-view-tag.md | 2 ++ docs/api/window-open.md | 2 ++ 34 files changed, 70 insertions(+), 39 deletions(-) diff --git a/docs/api/accelerator.md b/docs/api/accelerator.md index 83d8d3a7c2d..ff2b8190a94 100644 --- a/docs/api/accelerator.md +++ b/docs/api/accelerator.md @@ -1,7 +1,9 @@ # Accelerator -An accelerator is a string that represents a keyboard shortcut. It can contain -multiple modifiers and key codes, combined by the `+` character. +Define keyboard shortcuts. + +Accelerators can contain multiple modifiers and key codes, combined by +the `+` character. Examples: diff --git a/docs/api/app.md b/docs/api/app.md index 54e40263eab..b06f8e6b6af 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -1,6 +1,6 @@ # app -The `app` module is responsible for controlling the application's lifecycle. +Control your application's event lifecycle. The following example shows how to quit the application when the last window is closed: diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index dccae1212aa..daea5012100 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -1,6 +1,8 @@ # autoUpdater -This module provides an interface for the `Squirrel` auto-updater framework. +Enable apps to update themselves automatically. + +The `autoUpdater` module provides and interface for the [Squirrel](https://github.com/Squirrel) framework. You can quickly launch a multi-platform release server for distributing your application by using one of these projects: diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index c2497281526..b7536249f8f 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -1,7 +1,6 @@ # BrowserWindow -The `BrowserWindow` class gives you the ability to create a browser window. For -example: +Create and control browser windows. ```javascript // In the main process. diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index 8e8aa38e62d..f7515a5f1fb 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -1,9 +1,10 @@ # Supported Chrome command line switches -This page lists the command line switches used by the Chrome browser that are -also supported by Electron. You can use -[app.commandLine.appendSwitch][append-switch] to append them in your app's main -script before the [ready][ready] event of [app][app] module is emitted: +Command line switches supported by Electron. + +You can use [app.commandLine.appendSwitch][append-switch] to append them in +your app's main script before the [ready][ready] event of [app][app] module is +emitted: ```javascript const app = require('electron').app; diff --git a/docs/api/clipboard.md b/docs/api/clipboard.md index 7f95a1af26d..2f9440f80e9 100644 --- a/docs/api/clipboard.md +++ b/docs/api/clipboard.md @@ -1,6 +1,7 @@ # clipboard -The `clipboard` module provides methods to perform copy and paste operations. +Perform copy and paste operations on the system clipboard. + The following example shows how to write a string to the clipboard: ```javascript diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index 0b83c2759c6..66c7679dd09 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -1,7 +1,8 @@ # contentTracing -The `content-tracing` module is used to collect tracing data generated by the -underlying Chromium content module. This module does not include a web interface +Debug your application using Chromium's content module. + +This module does not include a web interface so you need to open `chrome://tracing/` in a Chrome browser and load the generated file to view the result. diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 9b7141e364e..0ef2317db6b 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -1,6 +1,6 @@ # crashReporter -The `crash-reporter` module enables sending your app's crash reports. +Submit crash reports to a remote server. The following is an example of automatically submitting a crash report to a remote server: diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index b39a09e5aa8..c80928017ac 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -1,7 +1,7 @@ # desktopCapturer -The `desktopCapturer` module can be used to get available sources that can be -used to be captured with `getUserMedia`. +Capture audio, video, and images from a microphone, camera, or +screen using the `getUserMedia` API. ```javascript // In the renderer process. diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 3eb0292a493..e052f10dca9 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -1,8 +1,6 @@ # dialog -The `dialog` module provides APIs to show native system dialogs, such as opening -files or alerting, so web applications can deliver the same user experience as -native applications. +Display native system dialogs for opening and saving files, alerting, etc. An example of showing a dialog to select multiple files and directories: diff --git a/docs/api/download-item.md b/docs/api/download-item.md index f117ffc57a7..02e5b395004 100644 --- a/docs/api/download-item.md +++ b/docs/api/download-item.md @@ -1,5 +1,7 @@ # DownloadItem +Trigger file downloads from remote sources. + `DownloadItem` is an EventEmitter represents a download item in Electron. It is used in `will-download` event of `Session` module, and allows users to control the download item. diff --git a/docs/api/environment-variables.md b/docs/api/environment-variables.md index 3483c19d643..6186c06904a 100644 --- a/docs/api/environment-variables.md +++ b/docs/api/environment-variables.md @@ -1,5 +1,7 @@ # Environment variables +Control application configuration and behavior without changing code. + Some behaviors of Electron are controlled by environment variables, because they are initialized earlier than command line and the app's code. diff --git a/docs/api/file-object.md b/docs/api/file-object.md index 01d49c39155..f1d3680eb8a 100644 --- a/docs/api/file-object.md +++ b/docs/api/file-object.md @@ -1,5 +1,7 @@ # `File` object +Use the HTML5 `File` API to work natively with files on the filesystem. + The DOM's File interface provides abstraction around native files in order to let users work on native files directly with the HTML5 file API. Electron has added a `path` attribute to the `File` interface which exposes the file's real diff --git a/docs/api/frameless-window.md b/docs/api/frameless-window.md index 8e1dd46ec56..12497db4dae 100644 --- a/docs/api/frameless-window.md +++ b/docs/api/frameless-window.md @@ -1,5 +1,7 @@ # Frameless Window +> Open a window without toolbars, borders, or other graphical "chrome". + A frameless window is a window that has no [chrome](https://developer.mozilla.org/en-US/docs/Glossary/Chrome), the parts of the window, like toolbars, that are not a part of the web page. These are diff --git a/docs/api/global-shortcut.md b/docs/api/global-shortcut.md index f20758406b7..c1bce458c89 100644 --- a/docs/api/global-shortcut.md +++ b/docs/api/global-shortcut.md @@ -1,5 +1,7 @@ # globalShortcut +Detect keyboard events when the application does not have keyboard focus. + The `globalShortcut` module can register/unregister a global keyboard shortcut with the operating system so that you can customize the operations for various shortcuts. diff --git a/docs/api/ipc-main.md b/docs/api/ipc-main.md index 84fbcfd5a72..1ddb0bb1c99 100644 --- a/docs/api/ipc-main.md +++ b/docs/api/ipc-main.md @@ -1,5 +1,7 @@ # ipcMain +Communicate asynchronously from the main process to renderer processes. + The `ipcMain` module is an instance of the [EventEmitter](https://nodejs.org/api/events.html) class. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer diff --git a/docs/api/ipc-renderer.md b/docs/api/ipc-renderer.md index 46a2331af43..8d18524d1cd 100644 --- a/docs/api/ipc-renderer.md +++ b/docs/api/ipc-renderer.md @@ -1,5 +1,7 @@ # ipcRenderer +Communicate asynchronously from a renderer process to the main process. + The `ipcRenderer` module is an instance of the [EventEmitter](https://nodejs.org/api/events.html) class. It provides a few methods so you can send synchronous and asynchronous messages from the render diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index 1b36432ab29..5c5532289a9 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -1,7 +1,6 @@ # MenuItem -The `menu-item` module allows you to add items to an application or context -[`menu`](menu.md). +Add items to application and context menus. See [`menu`](menu.md) for examples. diff --git a/docs/api/menu.md b/docs/api/menu.md index cb5a0cbe2df..6ac8a9ea1e0 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -1,8 +1,7 @@ # Menu -The `menu` class is used to create native menus that can be used as -application menus and -[context menus](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/ContextMenus). +Create native application menus and context menus. + This module is a main process module which can be used in a render process via the `remote` module. diff --git a/docs/api/native-image.md b/docs/api/native-image.md index e0c3ae46624..ed3bbdacc9a 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -1,5 +1,7 @@ # nativeImage +Create tray, dock, and application icons using PNG or JPG files. + In Electron, for the APIs that take images, you can pass either file paths or `nativeImage` instances. An empty image will be used when `null` is passed. diff --git a/docs/api/power-monitor.md b/docs/api/power-monitor.md index 4465b253a75..72cfbca1f13 100644 --- a/docs/api/power-monitor.md +++ b/docs/api/power-monitor.md @@ -1,7 +1,8 @@ # powerMonitor -The `power-monitor` module is used to monitor power state changes. You can -only use it in the main process. You should not use this module until the `ready` +Monitor power state changes. + +You can 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: diff --git a/docs/api/power-save-blocker.md b/docs/api/power-save-blocker.md index a3ef798411f..315bbdb9bec 100644 --- a/docs/api/power-save-blocker.md +++ b/docs/api/power-save-blocker.md @@ -1,8 +1,6 @@ # powerSaveBlocker -The `powerSaveBlocker` module is used to block the system from entering -low-power (sleep) mode and thus allowing the app to keep the system and screen -active. +Block the system from entering low-power (sleep) mode. For example: diff --git a/docs/api/process.md b/docs/api/process.md index 17c0be10926..18053370953 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -1,5 +1,7 @@ # process +Get information about the running application process. + The `process` object in Electron has the following differences from the one in upstream node: diff --git a/docs/api/protocol.md b/docs/api/protocol.md index e57a34ef89b..ade04c1cc30 100644 --- a/docs/api/protocol.md +++ b/docs/api/protocol.md @@ -1,7 +1,7 @@ # protocol -The `protocol` module can register a custom protocol or intercept an existing -protocol. +Register a custom protocol to intercept click events from other running +applications. An example of implementing a protocol that has the same effect as the `file://` protocol: diff --git a/docs/api/remote.md b/docs/api/remote.md index 7bdbe0362f6..fb585a0fc3d 100644 --- a/docs/api/remote.md +++ b/docs/api/remote.md @@ -1,5 +1,7 @@ # remote +Communicate between the renderer process and the main process. + The `remote` module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process. diff --git a/docs/api/screen.md b/docs/api/screen.md index 90ef183a8a8..5f8188f0d8a 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -1,8 +1,9 @@ # screen -The `screen` module retrieves information about screen size, displays, cursor -position, etc. You can not use this module until the `ready` event of the -`app` module is emitted (by invoking or requiring it). +> Retrieve information about screen size, displays, cursor position, etc. + +You cannot not use this module until the `ready` event of the `app` module is +emitted (by invoking or requiring it). `screen` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). diff --git a/docs/api/session.md b/docs/api/session.md index 90030180363..e7689c8e4b7 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1,5 +1,7 @@ # session +Manage browser cookies, cache, and other session data. + The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` diff --git a/docs/api/shell.md b/docs/api/shell.md index 823dc481bb0..b340acaebf6 100644 --- a/docs/api/shell.md +++ b/docs/api/shell.md @@ -1,5 +1,7 @@ # shell +Manage files and URLs using their default applications. + The `shell` module provides functions related to desktop integration. An example of opening a URL in the user's default browser: diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index 466b13828c4..d79942531e3 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -1,5 +1,7 @@ # Synopsis +Info about Node.js and the main and renderer processes. + All of [Node.js's built-in modules](http://nodejs.org/api/) are available in Electron and third-party node modules also fully supported as well (including the [native modules](../tutorial/using-native-node-modules.md)). diff --git a/docs/api/tray.md b/docs/api/tray.md index aa972c57cd9..d6bf2b3c73e 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -1,7 +1,6 @@ # Tray -A `Tray` represents an icon in an operating system's notification area, it is -usually attached with a context menu. +Add icons and context menus to the system's notification area. ```javascript const electron = require('electron'); diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 0eee6c5bf8b..e49e220dbbd 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1,8 +1,9 @@ # webContents +Render and control web pages using lifecycle events. + `webContents` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). - It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index d9e02ac097e..109bfa103d5 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -1,7 +1,6 @@ # webFrame -The `web-frame` module allows you to customize the rendering of the current -web page. +Customize the rendering of the current web page. An example of zooming current page to 200%. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 214f93dbad6..36b0513e556 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -1,5 +1,7 @@ # The `` tag +Display external web content in an isolated frame and process. + Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. An embedded page within your app controls how the guest content is laid out and diff --git a/docs/api/window-open.md b/docs/api/window-open.md index 46e74327741..14a0dce65f2 100644 --- a/docs/api/window-open.md +++ b/docs/api/window-open.md @@ -1,5 +1,7 @@ # The `window.open` function +Create a new window in a web page. + When `window.open` is called to create a new window in a web page, a new instance of `BrowserWindow` will be created for the `url` and a proxy will be returned to `window.open` to let the page have limited control over it. From 0527b17e4203f6593cdf64daa146b9a326039446 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Thu, 21 Apr 2016 15:39:12 -0700 Subject: [PATCH 0583/1265] blockquote summaries --- docs/api/accelerator.md | 2 +- docs/api/app.md | 2 +- docs/api/auto-updater.md | 2 +- docs/api/browser-window.md | 2 +- docs/api/chrome-command-line-switches.md | 2 +- docs/api/clipboard.md | 2 +- docs/api/content-tracing.md | 2 +- docs/api/crash-reporter.md | 2 +- docs/api/desktop-capturer.md | 2 +- docs/api/dialog.md | 2 +- docs/api/download-item.md | 2 +- docs/api/environment-variables.md | 2 +- docs/api/file-object.md | 2 +- docs/api/global-shortcut.md | 2 +- docs/api/ipc-main.md | 2 +- docs/api/ipc-renderer.md | 2 +- docs/api/menu-item.md | 2 +- docs/api/menu.md | 2 +- docs/api/native-image.md | 2 +- docs/api/power-monitor.md | 2 +- docs/api/power-save-blocker.md | 2 +- docs/api/process.md | 2 +- docs/api/protocol.md | 2 +- docs/api/remote.md | 2 +- docs/api/session.md | 2 +- docs/api/shell.md | 2 +- docs/api/synopsis.md | 2 +- docs/api/tray.md | 2 +- docs/api/web-contents.md | 2 +- docs/api/web-frame.md | 2 +- docs/api/web-view-tag.md | 2 +- docs/api/window-open.md | 2 +- 32 files changed, 32 insertions(+), 32 deletions(-) diff --git a/docs/api/accelerator.md b/docs/api/accelerator.md index ff2b8190a94..cf28e01037a 100644 --- a/docs/api/accelerator.md +++ b/docs/api/accelerator.md @@ -1,6 +1,6 @@ # Accelerator -Define keyboard shortcuts. +> Define keyboard shortcuts. Accelerators can contain multiple modifiers and key codes, combined by the `+` character. diff --git a/docs/api/app.md b/docs/api/app.md index b06f8e6b6af..8a2cdcfd922 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -1,6 +1,6 @@ # app -Control your application's event lifecycle. +> Control your application's event lifecycle. The following example shows how to quit the application when the last window is closed: diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index daea5012100..8ad3f8f16ed 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -1,6 +1,6 @@ # autoUpdater -Enable apps to update themselves automatically. +> Enable apps to update themselves automatically. The `autoUpdater` module provides and interface for the [Squirrel](https://github.com/Squirrel) framework. diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index b7536249f8f..7289057b40e 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -1,6 +1,6 @@ # BrowserWindow -Create and control browser windows. +> Create and control browser windows. ```javascript // In the main process. diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index f7515a5f1fb..71a5ce6a40e 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -1,6 +1,6 @@ # Supported Chrome command line switches -Command line switches supported by Electron. +> Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of [app][app] module is diff --git a/docs/api/clipboard.md b/docs/api/clipboard.md index 2f9440f80e9..58e5a1c1b09 100644 --- a/docs/api/clipboard.md +++ b/docs/api/clipboard.md @@ -1,6 +1,6 @@ # clipboard -Perform copy and paste operations on the system clipboard. +> Perform copy and paste operations on the system clipboard. The following example shows how to write a string to the clipboard: diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index 66c7679dd09..c69031850a3 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -1,6 +1,6 @@ # contentTracing -Debug your application using Chromium's content module. +> Debug your application using Chromium's content module. This module does not include a web interface so you need to open `chrome://tracing/` in a Chrome browser and load the diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 0ef2317db6b..1f8229eaa79 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -1,6 +1,6 @@ # crashReporter -Submit crash reports to a remote server. +> Submit crash reports to a remote server. The following is an example of automatically submitting a crash report to a remote server: diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index c80928017ac..505dd9596a9 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -1,6 +1,6 @@ # desktopCapturer -Capture audio, video, and images from a microphone, camera, or +> Capture audio, video, and images from a microphone, camera, or screen using the `getUserMedia` API. ```javascript diff --git a/docs/api/dialog.md b/docs/api/dialog.md index e052f10dca9..a5f61a53e3f 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -1,6 +1,6 @@ # dialog -Display native system dialogs for opening and saving files, alerting, etc. +> Display native system dialogs for opening and saving files, alerting, etc. An example of showing a dialog to select multiple files and directories: diff --git a/docs/api/download-item.md b/docs/api/download-item.md index 02e5b395004..0f38ceedac9 100644 --- a/docs/api/download-item.md +++ b/docs/api/download-item.md @@ -1,6 +1,6 @@ # DownloadItem -Trigger file downloads from remote sources. +> Trigger file downloads from remote sources. `DownloadItem` is an EventEmitter represents a download item in Electron. It is used in `will-download` event of `Session` module, and allows users to diff --git a/docs/api/environment-variables.md b/docs/api/environment-variables.md index 6186c06904a..7339661b09f 100644 --- a/docs/api/environment-variables.md +++ b/docs/api/environment-variables.md @@ -1,6 +1,6 @@ # Environment variables -Control application configuration and behavior without changing code. +> Control application configuration and behavior without changing code. Some behaviors of Electron are controlled by environment variables, because they are initialized earlier than command line and the app's code. diff --git a/docs/api/file-object.md b/docs/api/file-object.md index f1d3680eb8a..31c6feddb50 100644 --- a/docs/api/file-object.md +++ b/docs/api/file-object.md @@ -1,6 +1,6 @@ # `File` object -Use the HTML5 `File` API to work natively with files on the filesystem. +> Use the HTML5 `File` API to work natively with files on the filesystem. The DOM's File interface provides abstraction around native files in order to let users work on native files directly with the HTML5 file API. Electron has diff --git a/docs/api/global-shortcut.md b/docs/api/global-shortcut.md index c1bce458c89..08453d68a46 100644 --- a/docs/api/global-shortcut.md +++ b/docs/api/global-shortcut.md @@ -1,6 +1,6 @@ # globalShortcut -Detect keyboard events when the application does not have keyboard focus. +> Detect keyboard events when the application does not have keyboard focus. The `globalShortcut` module can register/unregister a global keyboard shortcut with the operating system so that you can customize the operations for various diff --git a/docs/api/ipc-main.md b/docs/api/ipc-main.md index 1ddb0bb1c99..c8ba60ba317 100644 --- a/docs/api/ipc-main.md +++ b/docs/api/ipc-main.md @@ -1,6 +1,6 @@ # ipcMain -Communicate asynchronously from the main process to renderer processes. +> Communicate asynchronously from the main process to renderer processes. The `ipcMain` module is an instance of the [EventEmitter](https://nodejs.org/api/events.html) class. When used in the main diff --git a/docs/api/ipc-renderer.md b/docs/api/ipc-renderer.md index 8d18524d1cd..9835e42b467 100644 --- a/docs/api/ipc-renderer.md +++ b/docs/api/ipc-renderer.md @@ -1,6 +1,6 @@ # ipcRenderer -Communicate asynchronously from a renderer process to the main process. +> Communicate asynchronously from a renderer process to the main process. The `ipcRenderer` module is an instance of the [EventEmitter](https://nodejs.org/api/events.html) class. It provides a few diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index 5c5532289a9..0b5db943113 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -1,6 +1,6 @@ # MenuItem -Add items to application and context menus. +> Add items to application and context menus. See [`menu`](menu.md) for examples. diff --git a/docs/api/menu.md b/docs/api/menu.md index 6ac8a9ea1e0..4106dfdd408 100644 --- a/docs/api/menu.md +++ b/docs/api/menu.md @@ -1,6 +1,6 @@ # Menu -Create native application menus and context menus. +> Create native application menus and context menus. This module is a main process module which can be used in a render process via the `remote` module. diff --git a/docs/api/native-image.md b/docs/api/native-image.md index ed3bbdacc9a..1cbfcf41018 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -1,6 +1,6 @@ # nativeImage -Create tray, dock, and application icons using PNG or JPG files. +> Create tray, dock, and application icons using PNG or JPG files. In Electron, for the APIs that take images, you can pass either file paths or `nativeImage` instances. An empty image will be used when `null` is passed. diff --git a/docs/api/power-monitor.md b/docs/api/power-monitor.md index 72cfbca1f13..75546dc8015 100644 --- a/docs/api/power-monitor.md +++ b/docs/api/power-monitor.md @@ -1,6 +1,6 @@ # powerMonitor -Monitor power state changes. +> Monitor power state changes. You can only use it in the main process. You should not use this module until the `ready` event of the `app` module is emitted. diff --git a/docs/api/power-save-blocker.md b/docs/api/power-save-blocker.md index 315bbdb9bec..3ec07338646 100644 --- a/docs/api/power-save-blocker.md +++ b/docs/api/power-save-blocker.md @@ -1,6 +1,6 @@ # powerSaveBlocker -Block the system from entering low-power (sleep) mode. +> Block the system from entering low-power (sleep) mode. For example: diff --git a/docs/api/process.md b/docs/api/process.md index 18053370953..80f0e539d80 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -1,6 +1,6 @@ # process -Get information about the running application process. +> Get information about the running application process. The `process` object in Electron has the following differences from the one in upstream node: diff --git a/docs/api/protocol.md b/docs/api/protocol.md index ade04c1cc30..b3062bb6325 100644 --- a/docs/api/protocol.md +++ b/docs/api/protocol.md @@ -1,6 +1,6 @@ # protocol -Register a custom protocol to intercept click events from other running +> Register a custom protocol to intercept click events from other running applications. An example of implementing a protocol that has the same effect as the diff --git a/docs/api/remote.md b/docs/api/remote.md index fb585a0fc3d..65f58f01b0c 100644 --- a/docs/api/remote.md +++ b/docs/api/remote.md @@ -1,6 +1,6 @@ # remote -Communicate between the renderer process and the main process. +> Communicate between the renderer process and the main process. The `remote` module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process. diff --git a/docs/api/session.md b/docs/api/session.md index e7689c8e4b7..390a9a5e4d8 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1,6 +1,6 @@ # session -Manage browser cookies, cache, and other session data. +> Manage browser cookies, cache, and other session data. The `session` module can be used to create new `Session` objects. diff --git a/docs/api/shell.md b/docs/api/shell.md index b340acaebf6..8ede115f7c6 100644 --- a/docs/api/shell.md +++ b/docs/api/shell.md @@ -1,6 +1,6 @@ # shell -Manage files and URLs using their default applications. +> Manage files and URLs using their default applications. The `shell` module provides functions related to desktop integration. diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index d79942531e3..641df7e2609 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -1,6 +1,6 @@ # Synopsis -Info about Node.js and the main and renderer processes. +> Info about Node.js and the main and renderer processes. All of [Node.js's built-in modules](http://nodejs.org/api/) are available in Electron and third-party node modules also fully supported as well (including diff --git a/docs/api/tray.md b/docs/api/tray.md index d6bf2b3c73e..1ea0859f14a 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -1,6 +1,6 @@ # Tray -Add icons and context menus to the system's notification area. +> Add icons and context menus to the system's notification area. ```javascript const electron = require('electron'); diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index e49e220dbbd..5c0f457538e 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1,6 +1,6 @@ # webContents -Render and control web pages using lifecycle events. +> Render and control web pages using lifecycle events. `webContents` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index 109bfa103d5..b2d8aa0f41e 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -1,6 +1,6 @@ # webFrame -Customize the rendering of the current web page. +> Customize the rendering of the current web page. An example of zooming current page to 200%. diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index 36b0513e556..5f4a422a13a 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -1,6 +1,6 @@ # The `` tag -Display external web content in an isolated frame and process. +> Display external web content in an isolated frame and process. Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. diff --git a/docs/api/window-open.md b/docs/api/window-open.md index 14a0dce65f2..b4f5057dae0 100644 --- a/docs/api/window-open.md +++ b/docs/api/window-open.md @@ -1,6 +1,6 @@ # The `window.open` function -Create a new window in a web page. +> Create a new window in a web page. When `window.open` is called to create a new window in a web page, a new instance of `BrowserWindow` will be created for the `url` and a proxy will be returned From 2c8261b4292413b926f2d31da6cad39c4baf486d Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 22 Apr 2016 10:30:49 -0700 Subject: [PATCH 0584/1265] update excerpts based on feedback --- docs/api/content-tracing.md | 3 ++- docs/api/desktop-capturer.md | 4 ++-- docs/api/download-item.md | 6 +++--- docs/api/protocol.md | 3 +-- docs/api/remote.md | 2 +- docs/api/session.md | 2 +- docs/api/synopsis.md | 2 +- docs/api/web-contents.md | 2 +- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index c69031850a3..85036c0d707 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -1,6 +1,7 @@ # contentTracing -> Debug your application using Chromium's content module. +> Collect tracing data from Chromium's content module for finding performance +bottlenecks and slow operations. This module does not include a web interface so you need to open `chrome://tracing/` in a Chrome browser and load the diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index 505dd9596a9..dc523c3a42f 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -1,7 +1,7 @@ # desktopCapturer -> Capture audio, video, and images from a microphone, camera, or -screen using the `getUserMedia` API. +> List `getUserMedia` sources for capturing audio, video, and images from a +microphone, camera, or screen. ```javascript // In the renderer process. diff --git a/docs/api/download-item.md b/docs/api/download-item.md index 0f38ceedac9..4418f61c19f 100644 --- a/docs/api/download-item.md +++ b/docs/api/download-item.md @@ -1,9 +1,9 @@ # DownloadItem -> Trigger file downloads from remote sources. +> Control file downloads from remote sources. -`DownloadItem` is an EventEmitter represents a download item in Electron. It -is used in `will-download` event of `Session` module, and allows users to +`DownloadItem` is an EventEmitter that represents a download item in Electron. +It is used in `will-download` event of `Session` module, and allows users to control the download item. ```javascript diff --git a/docs/api/protocol.md b/docs/api/protocol.md index b3062bb6325..fe7dfabc64c 100644 --- a/docs/api/protocol.md +++ b/docs/api/protocol.md @@ -1,7 +1,6 @@ # protocol -> Register a custom protocol to intercept click events from other running -applications. +> Register a custom protocol and intercept existing protocols. An example of implementing a protocol that has the same effect as the `file://` protocol: diff --git a/docs/api/remote.md b/docs/api/remote.md index 65f58f01b0c..454758c9139 100644 --- a/docs/api/remote.md +++ b/docs/api/remote.md @@ -1,6 +1,6 @@ # remote -> Communicate between the renderer process and the main process. +> Use main process modules from the renderer process. The `remote` module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process. diff --git a/docs/api/session.md b/docs/api/session.md index 390a9a5e4d8..5bc819fb2bd 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1,6 +1,6 @@ # session -> Manage browser cookies, cache, and other session data. +> Manage browser sessions, cookies, cache, proxy settings, etc. The `session` module can be used to create new `Session` objects. diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md index 641df7e2609..a2aa58f57f1 100644 --- a/docs/api/synopsis.md +++ b/docs/api/synopsis.md @@ -1,6 +1,6 @@ # Synopsis -> Info about Node.js and the main and renderer processes. +> How to use Node.js and Electron APIs. All of [Node.js's built-in modules](http://nodejs.org/api/) are available in Electron and third-party node modules also fully supported as well (including diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 5c0f457538e..64e7cea60e7 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1,6 +1,6 @@ # webContents -> Render and control web pages using lifecycle events. +> Render and control web pages. `webContents` is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter). From 799fd13c503c52deb095dfd234c88825a5ecab55 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 22 Apr 2016 11:42:54 -0700 Subject: [PATCH 0585/1265] more updates to api summaries based on feedback --- docs/api/auto-updater.md | 4 ++-- docs/api/chrome-command-line-switches.md | 4 ++-- docs/api/content-tracing.md | 6 +++--- docs/api/menu-item.md | 2 +- docs/api/protocol.md | 2 +- docs/api/window-open.md | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 8ad3f8f16ed..211d0c69a5f 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -1,8 +1,8 @@ # autoUpdater -> Enable apps to update themselves automatically. +> Enable apps to automatically update themselves. -The `autoUpdater` module provides and interface for the [Squirrel](https://github.com/Squirrel) framework. +The `autoUpdater` module provides an interface for the [Squirrel](https://github.com/Squirrel) framework. You can quickly launch a multi-platform release server for distributing your application by using one of these projects: diff --git a/docs/api/chrome-command-line-switches.md b/docs/api/chrome-command-line-switches.md index 71a5ce6a40e..17059435eaa 100644 --- a/docs/api/chrome-command-line-switches.md +++ b/docs/api/chrome-command-line-switches.md @@ -3,8 +3,8 @@ > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in -your app's main script before the [ready][ready] event of [app][app] module is -emitted: +your app's main script before the [ready][ready] event of the [app][app] module +is emitted: ```javascript const app = require('electron').app; diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index 85036c0d707..a9414d34876 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -3,9 +3,9 @@ > Collect tracing data from Chromium's content module for finding performance bottlenecks and slow operations. -This module does not include a web interface -so you need to open `chrome://tracing/` in a Chrome browser and load the -generated file to view the result. +This module does not include a web interface so you need to open +`chrome://tracing/` in a Chrome browser and load the generated file to view the +result. ```javascript const contentTracing = require('electron').contentTracing; diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index 0b5db943113..b67032271e6 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -1,6 +1,6 @@ # MenuItem -> Add items to application and context menus. +> Add items to native application menus and context menus. See [`menu`](menu.md) for examples. diff --git a/docs/api/protocol.md b/docs/api/protocol.md index fe7dfabc64c..aa9b43486d0 100644 --- a/docs/api/protocol.md +++ b/docs/api/protocol.md @@ -1,6 +1,6 @@ # protocol -> Register a custom protocol and intercept existing protocols. +> Register a custom protocol and intercept existing protocol requests. An example of implementing a protocol that has the same effect as the `file://` protocol: diff --git a/docs/api/window-open.md b/docs/api/window-open.md index b4f5057dae0..abb0760f121 100644 --- a/docs/api/window-open.md +++ b/docs/api/window-open.md @@ -1,6 +1,6 @@ # The `window.open` function -> Create a new window in a web page. +> Open a new window and load a URL. When `window.open` is called to create a new window in a web page, a new instance of `BrowserWindow` will be created for the `url` and a proxy will be returned From 28381757d5e6ad7408c2e1fe989131d075ef6308 Mon Sep 17 00:00:00 2001 From: Alejandro Betancourt Date: Fri, 22 Apr 2016 14:34:46 -0500 Subject: [PATCH 0586/1265] Fix translations to spanish --- docs-translations/es/api/synopsis.md | 2 +- docs-translations/es/tutorial/application-packaging.md | 4 ++-- docs-translations/es/tutorial/devtools-extension.md | 6 +++--- docs-translations/es/tutorial/quick-start.md | 4 +--- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/docs-translations/es/api/synopsis.md b/docs-translations/es/api/synopsis.md index 534fafcf2f7..54c264a1aa7 100644 --- a/docs-translations/es/api/synopsis.md +++ b/docs-translations/es/api/synopsis.md @@ -1,4 +1,4 @@ -# Synopsis +# Sinopsis Todos los [Módulos integrados de Node.js](http://nodejs.org/api/) se encuentran disponibles en Electron y módulos de terceros son támbien totalmente compatibles diff --git a/docs-translations/es/tutorial/application-packaging.md b/docs-translations/es/tutorial/application-packaging.md index f8768c49dd0..0e46a44d2b4 100644 --- a/docs-translations/es/tutorial/application-packaging.md +++ b/docs-translations/es/tutorial/application-packaging.md @@ -105,7 +105,7 @@ originalFs.readFileSync('/path/to/example.asar'); A pesar de que hemos intentado que los paquetes `asar` funcionen como directorios de la mejor forma posible, aún existen limitaciones debido a la naturaleza de bajo nivel de la API Node. -### Los paquetes son de sólo lecutra +### Los paquetes son de sólo lectura Los paquetes `asar` no pueden ser modificados, por lo cual todas las funciones que modifiquen archivos no funcionarán. @@ -132,7 +132,7 @@ Las APIs que requieren el desempaquetamiento adicional son: ### Información falsa en `fs.stat` El objeto `Stats` retornado por `fs.stat` y otras funciones relacionadas, -no es preciso, ya que los archivos del paquete `asar` no existen el sistema de archivos. +no es preciso, ya que los archivos del paquete `asar` no existen en el sistema de archivos. La utilización del objeto `Stats` sólo es recomendable para obtener el tamaño del archivo y/o comprobar el tipo de archivo. diff --git a/docs-translations/es/tutorial/devtools-extension.md b/docs-translations/es/tutorial/devtools-extension.md index f54c3e0eaa8..495f56058d5 100644 --- a/docs-translations/es/tutorial/devtools-extension.md +++ b/docs-translations/es/tutorial/devtools-extension.md @@ -1,13 +1,13 @@ # Extensión DevTools -Para facilitar la depuración, Electron provee un soporte básico para la extensión -[Chrome DevTools Extension][devtools-extension]. +Para facilitar la depuración, Electron provee un soporte básico para la extensión +[Chrome DevTools][devtools-extension]. Para la mayoría de las extensiones devtools, simplemente puedes descargar el código fuente y utilizar `BrowserWindow.addDevToolsExtension` para cargarlas, las extensiones cargadas serán recordadas para que no sea necesario llamar a la función cada vez que creas una ventana. -Por ejemplo, para usar la extensión [React DevTools Extension](https://github.com/facebook/react-devtools), primero debes descargar el código fuente: +Por ejemplo, para usar la extensión [React DevTools](https://github.com/facebook/react-devtools), primero debes descargar el código fuente: ```bash $ cd /some-directory diff --git a/docs-translations/es/tutorial/quick-start.md b/docs-translations/es/tutorial/quick-start.md index 2e6825669fa..a760fccad2c 100644 --- a/docs-translations/es/tutorial/quick-start.md +++ b/docs-translations/es/tutorial/quick-start.md @@ -1,8 +1,6 @@ -# Intro - ## Introducción -Electron permite la creación de aplicaciones de escritorio utilizando JavaScript puro, a través de un runtime con APIs nativas. Puedes verlo como una variante de io.js, enfocado en aplicaciones de escritorio, en vez de servidores web. +Electron permite la creación de aplicaciones de escritorio utilizando JavaScript puro, a través de un runtime con APIs nativas. Puedes verlo como una variante de io.js, enfocado a aplicaciones de escritorio, en vez de servidores web. Esto no significa que Electron sea un binding de librerías GUI para JavaScript. Electron utiliza páginas web como su GUI, por lo cual puedes verlo como un navegador Chromium mínimo, From dfd1a469562f63096b3ef75d4c0eaaf2778ea5ac Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Fri, 22 Apr 2016 23:58:41 +0200 Subject: [PATCH 0587/1265] Document process.crash method --- docs/api/process.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/api/process.md b/docs/api/process.md index b2d9c765a03..4aaa84f89d8 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -44,6 +44,10 @@ built-in modules. The `process` object has the following method: +### `process.crash()` + +Causes the main thread of the current process crash. + ### `process.hang()` Causes the main thread of the current process hang. From 778d18a51058fa2f47aa2a1449ddf452c3661e6f Mon Sep 17 00:00:00 2001 From: Alejandro Betancourt Date: Fri, 22 Apr 2016 17:13:51 -0500 Subject: [PATCH 0588/1265] Fix links in readme for spanish translation --- docs-translations/es/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs-translations/es/README.md b/docs-translations/es/README.md index e69e76b1c4c..c2358bbb016 100644 --- a/docs-translations/es/README.md +++ b/docs-translations/es/README.md @@ -35,7 +35,7 @@ * [content-tracing](../../docs/api/content-tracing.md) * [dialog](../../docs/api/dialog.md) * [global-shortcut](../../docs/api/global-shortcut.md) -* [ipc (proceso principal)](../../docs/api/ipc-main-process.md) +* [ipc (proceso principal)](../../docs/api/ipc-main.md) * [menu](../../docs/api/menu.md) * [menu-item](../../docs/api/menu-item.md) * [power-monitor](../../docs/api/power-monitor.md) @@ -66,6 +66,6 @@ * [Diferencias Técnicas con NW.js (anteriormente conocido como node-webkit)](development/atom-shell-vs-node-webkit.md) * [Repaso del 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 (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) +* [Configurando un Servidor de Símbolos en el depurador](development/setting-up-symbol-server.md) From e1516d4244e367223bc3f9c9e4e806a6e105e82e Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sat, 23 Apr 2016 01:15:00 +0200 Subject: [PATCH 0589/1265] Fix BrowserWindow.maximize/unmaximize on Mac --- atom/browser/native_window_mac.mm | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 5f980fed62c..04569d8f50f 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -602,10 +602,16 @@ bool NativeWindowMac::IsVisible() { } void NativeWindowMac::Maximize() { + if (IsMaximized()) + return; + [window_ zoom:nil]; } void NativeWindowMac::Unmaximize() { + if (!IsMaximized()) + return; + [window_ zoom:nil]; } From 2ae52d0ff4fc1c64dcc3be2ccaf0143de75fc8b5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 10:17:54 +0900 Subject: [PATCH 0590/1265] Make Wrappable a template class --- atom/browser/api/atom_api_app.cc | 20 ++++--- atom/browser/api/atom_api_app.h | 13 ++-- atom/browser/api/atom_api_auto_updater.cc | 22 +++---- atom/browser/api/atom_api_auto_updater.h | 13 ++-- atom/browser/api/atom_api_cookies.cc | 8 ++- atom/browser/api/atom_api_cookies.h | 4 +- atom/browser/api/atom_api_debugger.cc | 6 +- atom/browser/api/atom_api_debugger.h | 4 +- atom/browser/api/atom_api_desktop_capturer.cc | 16 ++--- atom/browser/api/atom_api_desktop_capturer.h | 13 ++-- atom/browser/api/atom_api_download_item.cc | 6 +- atom/browser/api/atom_api_download_item.h | 3 +- atom/browser/api/atom_api_global_shortcut.cc | 20 ++++--- atom/browser/api/atom_api_global_shortcut.h | 11 ++-- atom/browser/api/atom_api_menu.cc | 2 +- atom/browser/api/atom_api_menu.h | 4 +- atom/browser/api/atom_api_menu_mac.h | 2 +- atom/browser/api/atom_api_menu_mac.mm | 6 +- atom/browser/api/atom_api_menu_views.cc | 4 +- atom/browser/api/atom_api_menu_views.h | 2 +- atom/browser/api/atom_api_power_monitor.cc | 10 +++- atom/browser/api/atom_api_power_monitor.h | 5 +- .../api/atom_api_power_save_blocker.cc | 22 +++---- .../browser/api/atom_api_power_save_blocker.h | 11 ++-- atom/browser/api/atom_api_protocol.cc | 60 ++++++++++--------- atom/browser/api/atom_api_protocol.h | 11 ++-- atom/browser/api/atom_api_screen.cc | 27 +++++---- atom/browser/api/atom_api_screen.h | 13 ++-- atom/browser/api/atom_api_session.cc | 13 ++-- atom/browser/api/atom_api_session.h | 2 +- atom/browser/api/atom_api_tray.cc | 6 +- atom/browser/api/atom_api_tray.h | 5 +- atom/browser/api/atom_api_web_contents.cc | 14 +++-- atom/browser/api/atom_api_web_contents.h | 9 ++- atom/browser/api/atom_api_web_request.cc | 6 +- atom/browser/api/atom_api_web_request.h | 5 +- atom/browser/api/atom_api_window.cc | 2 +- atom/browser/api/atom_api_window.h | 4 +- atom/browser/api/event.cc | 32 ++++------ atom/browser/api/event.h | 12 ++-- atom/browser/api/event_emitter.cc | 22 ++++--- atom/browser/api/event_emitter.h | 38 ++++++++---- atom/browser/api/trackable_object.cc | 9 --- atom/browser/api/trackable_object.h | 41 ++++--------- atom/common/api/atom_api_asar.cc | 48 +++++++-------- atom/common/api/atom_api_id_weak_map.cc | 6 +- atom/common/api/atom_api_id_weak_map.h | 6 +- atom/common/api/atom_api_native_image.cc | 47 +++++++-------- atom/common/api/atom_api_native_image.h | 14 ++--- atom/renderer/api/atom_api_web_frame.cc | 22 +++---- atom/renderer/api/atom_api_web_frame.h | 13 ++-- vendor/native_mate | 2 +- 52 files changed, 367 insertions(+), 349 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index d239a63d058..a7842c42ce0 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -194,10 +194,11 @@ int ImportIntoCertStore( } // namespace -App::App() { +App::App(v8::Isolate* isolate) { static_cast(AtomBrowserClient::Get())->set_delegate(this); Browser::Get()->AddObserver(this); content::GpuDataManager::GetInstance()->AddObserver(this); + Init(isolate); } App::~App() { @@ -439,10 +440,16 @@ void App::OnCertificateManagerModelCreated( } #endif -mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( - v8::Isolate* isolate) { +// static +mate::Handle App::Create(v8::Isolate* isolate) { + return CreateHandle(isolate, new App(isolate)); +} + +// static +void App::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { auto browser = base::Unretained(Browser::Get()); - return mate::ObjectTemplateBuilder(isolate) + mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("quit", base::Bind(&Browser::Quit, browser)) .SetMethod("exit", base::Bind(&Browser::Exit, browser)) .SetMethod("focus", base::Bind(&Browser::Focus, browser)) @@ -484,11 +491,6 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder( .SetMethod("makeSingleInstance", &App::MakeSingleInstance); } -// static -mate::Handle App::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new App); -} - } // namespace api } // namespace atom diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index d4102521c0b..354ea38d884 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -33,12 +33,15 @@ namespace atom { namespace api { class App : public AtomBrowserClient::Delegate, - public mate::EventEmitter, + public mate::EventEmitter, public BrowserObserver, public content::GpuDataManagerObserver { public: static mate::Handle Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + // Called when window with disposition needs to be created. void OnCreateWindow(const GURL& target_url, const std::string& frame_name, @@ -54,8 +57,8 @@ class App : public AtomBrowserClient::Delegate, #endif protected: - App(); - virtual ~App(); + explicit App(v8::Isolate* isolate); + ~App() override; // BrowserObserver: void OnBeforeQuit(bool* prevent_default) override; @@ -93,10 +96,6 @@ class App : public AtomBrowserClient::Delegate, void OnPlatformThemeChanged() override; #endif - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; - private: // Get/Set the pre-defined path in PathService. base::FilePath GetPath(mate::Arguments* args, const std::string& name); diff --git a/atom/browser/api/atom_api_auto_updater.cc b/atom/browser/api/atom_api_auto_updater.cc index 1a02a54d453..102bffb7118 100644 --- a/atom/browser/api/atom_api_auto_updater.cc +++ b/atom/browser/api/atom_api_auto_updater.cc @@ -34,8 +34,9 @@ namespace atom { namespace api { -AutoUpdater::AutoUpdater() { +AutoUpdater::AutoUpdater(v8::Isolate* isolate) { auto_updater::AutoUpdater::SetDelegate(this); + Init(isolate); } AutoUpdater::~AutoUpdater() { @@ -78,14 +79,6 @@ void AutoUpdater::OnWindowAllClosed() { QuitAndInstall(); } -mate::ObjectTemplateBuilder AutoUpdater::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) - .SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL) - .SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates) - .SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall); -} - void AutoUpdater::QuitAndInstall() { // If we don't have any window then quitAndInstall immediately. WindowList* window_list = WindowList::GetInstance(); @@ -102,7 +95,16 @@ void AutoUpdater::QuitAndInstall() { // static mate::Handle AutoUpdater::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new AutoUpdater); + return CreateHandle(isolate, new AutoUpdater(isolate)); +} + +// static +void AutoUpdater::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL) + .SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates) + .SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall); } } // namespace api diff --git a/atom/browser/api/atom_api_auto_updater.h b/atom/browser/api/atom_api_auto_updater.h index 95b91041e9e..857647258ad 100644 --- a/atom/browser/api/atom_api_auto_updater.h +++ b/atom/browser/api/atom_api_auto_updater.h @@ -16,15 +16,18 @@ namespace atom { namespace api { -class AutoUpdater : public mate::EventEmitter, +class AutoUpdater : public mate::EventEmitter, public auto_updater::Delegate, public WindowListObserver { public: static mate::Handle Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + protected: - AutoUpdater(); - virtual ~AutoUpdater(); + explicit AutoUpdater(v8::Isolate* isolate); + ~AutoUpdater() override; // Delegate implementations. void OnError(const std::string& error) override; @@ -39,10 +42,6 @@ class AutoUpdater : public mate::EventEmitter, // WindowListObserver: void OnWindowAllClosed() override; - // mate::Wrappable implementations: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; - private: void QuitAndInstall(); diff --git a/atom/browser/api/atom_api_cookies.cc b/atom/browser/api/atom_api_cookies.cc index e49a2ee2f67..8698b43485b 100644 --- a/atom/browser/api/atom_api_cookies.cc +++ b/atom/browser/api/atom_api_cookies.cc @@ -186,8 +186,10 @@ void SetCookieOnIO(scoped_refptr getter, } // namespace -Cookies::Cookies(content::BrowserContext* browser_context) - : request_context_getter_(browser_context->GetRequestContext()) { +Cookies::Cookies(v8::Isolate* isolate, + content::BrowserContext* browser_context) + : request_context_getter_(browser_context->GetRequestContext()) { + Init(isolate); } Cookies::~Cookies() { @@ -223,7 +225,7 @@ void Cookies::Set(const base::DictionaryValue& details, mate::Handle Cookies::Create( v8::Isolate* isolate, content::BrowserContext* browser_context) { - return mate::CreateHandle(isolate, new Cookies(browser_context)); + return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } // static diff --git a/atom/browser/api/atom_api_cookies.h b/atom/browser/api/atom_api_cookies.h index 302fd1b2511..33fee56960f 100644 --- a/atom/browser/api/atom_api_cookies.h +++ b/atom/browser/api/atom_api_cookies.h @@ -46,8 +46,8 @@ class Cookies : public mate::TrackableObject { v8::Local prototype); protected: - explicit Cookies(content::BrowserContext* browser_context); - ~Cookies(); + Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context); + ~Cookies() override; void Get(const base::DictionaryValue& filter, const GetCallback& callback); void Remove(const GURL& url, const std::string& name, diff --git a/atom/browser/api/atom_api_debugger.cc b/atom/browser/api/atom_api_debugger.cc index eab60311f3d..828c573188d 100644 --- a/atom/browser/api/atom_api_debugger.cc +++ b/atom/browser/api/atom_api_debugger.cc @@ -31,9 +31,10 @@ WrapDebuggerCallback g_wrap_debugger; } // namespace -Debugger::Debugger(content::WebContents* web_contents) +Debugger::Debugger(v8::Isolate* isolate, content::WebContents* web_contents) : web_contents_(web_contents), previous_request_id_(0) { + Init(isolate); } Debugger::~Debugger() { @@ -150,7 +151,8 @@ void Debugger::SendCommand(mate::Arguments* args) { mate::Handle Debugger::Create( v8::Isolate* isolate, content::WebContents* web_contents) { - auto handle = mate::CreateHandle(isolate, new Debugger(web_contents)); + auto handle = mate::CreateHandle( + isolate, new Debugger(isolate, web_contents)); g_wrap_debugger.Run(handle.ToV8()); return handle; } diff --git a/atom/browser/api/atom_api_debugger.h b/atom/browser/api/atom_api_debugger.h index 5454108e8b0..1e97fa89abd 100644 --- a/atom/browser/api/atom_api_debugger.h +++ b/atom/browser/api/atom_api_debugger.h @@ -42,8 +42,8 @@ class Debugger: public mate::TrackableObject, v8::Local prototype); protected: - explicit Debugger(content::WebContents* web_contents); - ~Debugger(); + Debugger(v8::Isolate* isolate, content::WebContents* web_contents); + ~Debugger() override; // content::DevToolsAgentHostClient: void AgentHostClosed(content::DevToolsAgentHost* agent_host, diff --git a/atom/browser/api/atom_api_desktop_capturer.cc b/atom/browser/api/atom_api_desktop_capturer.cc index cdae6f0c44c..cc978a40b39 100644 --- a/atom/browser/api/atom_api_desktop_capturer.cc +++ b/atom/browser/api/atom_api_desktop_capturer.cc @@ -38,7 +38,8 @@ namespace atom { namespace api { -DesktopCapturer::DesktopCapturer() { +DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) { + Init(isolate); } DesktopCapturer::~DesktopCapturer() { @@ -92,15 +93,16 @@ bool DesktopCapturer::OnRefreshFinished() { return false; } -mate::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) - .SetMethod("startHandling", &DesktopCapturer::StartHandling); +// static +mate::Handle DesktopCapturer::Create(v8::Isolate* isolate) { + return mate::CreateHandle(isolate, new DesktopCapturer(isolate)); } // static -mate::Handle DesktopCapturer::Create(v8::Isolate* isolate) { - return mate::CreateHandle(isolate, new DesktopCapturer); +void DesktopCapturer::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("startHandling", &DesktopCapturer::StartHandling); } } // namespace api diff --git a/atom/browser/api/atom_api_desktop_capturer.h b/atom/browser/api/atom_api_desktop_capturer.h index c22c8a44835..e71141fa521 100644 --- a/atom/browser/api/atom_api_desktop_capturer.h +++ b/atom/browser/api/atom_api_desktop_capturer.h @@ -14,18 +14,21 @@ namespace atom { namespace api { -class DesktopCapturer: public mate::EventEmitter, +class DesktopCapturer: public mate::EventEmitter, public DesktopMediaListObserver { public: static mate::Handle Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + void StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size); protected: - DesktopCapturer(); - ~DesktopCapturer(); + explicit DesktopCapturer(v8::Isolate* isolate); + ~DesktopCapturer() override; // DesktopMediaListObserver overrides. void OnSourceAdded(int index) override; @@ -36,10 +39,6 @@ class DesktopCapturer: public mate::EventEmitter, bool OnRefreshFinished() override; private: - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; - scoped_ptr media_list_; DISALLOW_COPY_AND_ASSIGN(DesktopCapturer); diff --git a/atom/browser/api/atom_api_download_item.cc b/atom/browser/api/atom_api_download_item.cc index 3edd5f9c254..10f7c454625 100644 --- a/atom/browser/api/atom_api_download_item.cc +++ b/atom/browser/api/atom_api_download_item.cc @@ -57,9 +57,11 @@ std::map>> g_download_item_objects; } // namespace -DownloadItem::DownloadItem(content::DownloadItem* download_item) +DownloadItem::DownloadItem(v8::Isolate* isolate, + content::DownloadItem* download_item) : download_item_(download_item) { download_item_->AddObserver(this); + Init(isolate); AttachAsUserData(download_item); } @@ -173,7 +175,7 @@ mate::Handle DownloadItem::Create( if (existing) return mate::CreateHandle(isolate, static_cast(existing)); - auto handle = mate::CreateHandle(isolate, new DownloadItem(item)); + auto handle = mate::CreateHandle(isolate, new DownloadItem(isolate, item)); g_wrap_download_item.Run(handle.ToV8()); // Reference this object in case it got garbage collected. diff --git a/atom/browser/api/atom_api_download_item.h b/atom/browser/api/atom_api_download_item.h index 64469b9b34d..bc7ddd821bb 100644 --- a/atom/browser/api/atom_api_download_item.h +++ b/atom/browser/api/atom_api_download_item.h @@ -23,7 +23,6 @@ class DownloadItem : public mate::TrackableObject, static mate::Handle Create(v8::Isolate* isolate, content::DownloadItem* item); - // mate::TrackableObject: static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); @@ -41,7 +40,7 @@ class DownloadItem : public mate::TrackableObject, base::FilePath GetSavePath() const; protected: - explicit DownloadItem(content::DownloadItem* download_item); + DownloadItem(v8::Isolate* isolate, content::DownloadItem* download_item); ~DownloadItem(); // Override content::DownloadItem::Observer methods diff --git a/atom/browser/api/atom_api_global_shortcut.cc b/atom/browser/api/atom_api_global_shortcut.cc index f5a03e4abf9..3a9a3e7ddbe 100644 --- a/atom/browser/api/atom_api_global_shortcut.cc +++ b/atom/browser/api/atom_api_global_shortcut.cc @@ -19,7 +19,8 @@ namespace atom { namespace api { -GlobalShortcut::GlobalShortcut() { +GlobalShortcut::GlobalShortcut(v8::Isolate* isolate) { + Init(isolate); } GlobalShortcut::~GlobalShortcut() { @@ -66,20 +67,21 @@ void GlobalShortcut::UnregisterAll() { GlobalShortcutListener::GetInstance()->UnregisterAccelerators(this); } -mate::ObjectTemplateBuilder GlobalShortcut::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) +// static +mate::Handle GlobalShortcut::Create(v8::Isolate* isolate) { + return CreateHandle(isolate, new GlobalShortcut(isolate)); +} + +// static +void GlobalShortcut::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("register", &GlobalShortcut::Register) .SetMethod("isRegistered", &GlobalShortcut::IsRegistered) .SetMethod("unregister", &GlobalShortcut::Unregister) .SetMethod("unregisterAll", &GlobalShortcut::UnregisterAll); } -// static -mate::Handle GlobalShortcut::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new GlobalShortcut); -} - } // namespace api } // namespace atom diff --git a/atom/browser/api/atom_api_global_shortcut.h b/atom/browser/api/atom_api_global_shortcut.h index d7057b00032..41eb42f8556 100644 --- a/atom/browser/api/atom_api_global_shortcut.h +++ b/atom/browser/api/atom_api_global_shortcut.h @@ -23,13 +23,12 @@ class GlobalShortcut : public extensions::GlobalShortcutListener::Observer, public: static mate::Handle Create(v8::Isolate* isolate); - protected: - GlobalShortcut(); - ~GlobalShortcut() override; + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); - // mate::Wrappable implementations: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; + protected: + explicit GlobalShortcut(v8::Isolate* isolate); + ~GlobalShortcut() override; private: typedef std::map AcceleratorCallbackMap; diff --git a/atom/browser/api/atom_api_menu.cc b/atom/browser/api/atom_api_menu.cc index e40ba17f464..ec222ba1540 100644 --- a/atom/browser/api/atom_api_menu.cc +++ b/atom/browser/api/atom_api_menu.cc @@ -19,7 +19,7 @@ namespace atom { namespace api { -Menu::Menu() +Menu::Menu(v8::Isolate* isolate) : model_(new AtomMenuModel(this)), parent_(NULL) { } diff --git a/atom/browser/api/atom_api_menu.h b/atom/browser/api/atom_api_menu.h index 1ae708863a7..5701985ab10 100644 --- a/atom/browser/api/atom_api_menu.h +++ b/atom/browser/api/atom_api_menu.h @@ -20,7 +20,7 @@ namespace api { class Menu : public mate::TrackableObject

, public AtomMenuModel::Delegate { public: - static mate::Wrappable* Create(); + static mate::WrappableBase* Create(v8::Isolate* isolate); static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); @@ -36,7 +36,7 @@ class Menu : public mate::TrackableObject, AtomMenuModel* model() const { return model_.get(); } protected: - Menu(); + explicit Menu(v8::Isolate* isolate); ~Menu() override; // mate::Wrappable: diff --git a/atom/browser/api/atom_api_menu_mac.h b/atom/browser/api/atom_api_menu_mac.h index 85227fa2a9d..293e8ec4eda 100644 --- a/atom/browser/api/atom_api_menu_mac.h +++ b/atom/browser/api/atom_api_menu_mac.h @@ -17,7 +17,7 @@ namespace api { class MenuMac : public Menu { protected: - MenuMac(); + explicit MenuMac(v8::Isolate* isolate); void PopupAt(Window* window, int x, int y, int positioning_item = 0) override; diff --git a/atom/browser/api/atom_api_menu_mac.mm b/atom/browser/api/atom_api_menu_mac.mm index 71c677b0476..d8ee089c1cb 100644 --- a/atom/browser/api/atom_api_menu_mac.mm +++ b/atom/browser/api/atom_api_menu_mac.mm @@ -15,7 +15,7 @@ namespace atom { namespace api { -MenuMac::MenuMac() { +MenuMac::MenuMac(v8::Isolate* isolate) : Menu(isolate) { } void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) { @@ -68,8 +68,8 @@ void Menu::SendActionToFirstResponder(const std::string& action) { } // static -mate::Wrappable* Menu::Create() { - return new MenuMac(); +mate::WrappableBase* Menu::Create(v8::Isolate* isolate) { + return new MenuMac(isolate); } } // namespace api diff --git a/atom/browser/api/atom_api_menu_views.cc b/atom/browser/api/atom_api_menu_views.cc index 4a3a97dd906..f0422ed7ba5 100644 --- a/atom/browser/api/atom_api_menu_views.cc +++ b/atom/browser/api/atom_api_menu_views.cc @@ -13,7 +13,7 @@ namespace atom { namespace api { -MenuViews::MenuViews() { +MenuViews::MenuViews(v8::Isolate* isolate) : Menu(isolate) { } void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) { @@ -49,7 +49,7 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) { } // static -mate::Wrappable* Menu::Create() { +mate::WrappableBase* Menu::Create() { return new MenuViews(); } diff --git a/atom/browser/api/atom_api_menu_views.h b/atom/browser/api/atom_api_menu_views.h index e4d17c77ca6..e1daa490402 100644 --- a/atom/browser/api/atom_api_menu_views.h +++ b/atom/browser/api/atom_api_menu_views.h @@ -14,7 +14,7 @@ namespace api { class MenuViews : public Menu { public: - MenuViews(); + explicit MenuViews(v8::Isolate* isolate); protected: void PopupAt(Window* window, int x, int y, int positioning_item = 0) override; diff --git a/atom/browser/api/atom_api_power_monitor.cc b/atom/browser/api/atom_api_power_monitor.cc index 31b35e10cea..c72620c809d 100644 --- a/atom/browser/api/atom_api_power_monitor.cc +++ b/atom/browser/api/atom_api_power_monitor.cc @@ -14,8 +14,9 @@ namespace atom { namespace api { -PowerMonitor::PowerMonitor() { +PowerMonitor::PowerMonitor(v8::Isolate* isolate) { base::PowerMonitor::Get()->AddObserver(this); + Init(isolate); } PowerMonitor::~PowerMonitor() { @@ -46,7 +47,12 @@ v8::Local PowerMonitor::Create(v8::Isolate* isolate) { return v8::Null(isolate); } - return CreateHandle(isolate, new PowerMonitor).ToV8(); + return CreateHandle(isolate, new PowerMonitor(isolate)).ToV8(); +} + +// static +void PowerMonitor::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { } } // namespace api diff --git a/atom/browser/api/atom_api_power_monitor.h b/atom/browser/api/atom_api_power_monitor.h index 8fb52eeec95..50d4bb466ca 100644 --- a/atom/browser/api/atom_api_power_monitor.h +++ b/atom/browser/api/atom_api_power_monitor.h @@ -19,8 +19,11 @@ class PowerMonitor : public mate::TrackableObject, public: static v8::Local Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + protected: - PowerMonitor(); + explicit PowerMonitor(v8::Isolate* isolate); ~PowerMonitor() override; // base::PowerObserver implementations: diff --git a/atom/browser/api/atom_api_power_save_blocker.cc b/atom/browser/api/atom_api_power_save_blocker.cc index 58983e6c846..5f8272b9848 100644 --- a/atom/browser/api/atom_api_power_save_blocker.cc +++ b/atom/browser/api/atom_api_power_save_blocker.cc @@ -37,9 +37,10 @@ namespace atom { namespace api { -PowerSaveBlocker::PowerSaveBlocker() +PowerSaveBlocker::PowerSaveBlocker(v8::Isolate* isolate) : current_blocker_type_( - content::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension) { + content::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension) { + Init(isolate); } PowerSaveBlocker::~PowerSaveBlocker() { @@ -97,17 +98,18 @@ bool PowerSaveBlocker::IsStarted(int id) { return power_save_blocker_types_.find(id) != power_save_blocker_types_.end(); } -mate::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) - .SetMethod("start", &PowerSaveBlocker::Start) - .SetMethod("stop", &PowerSaveBlocker::Stop) - .SetMethod("isStarted", &PowerSaveBlocker::IsStarted); +// static +mate::Handle PowerSaveBlocker::Create(v8::Isolate* isolate) { + return CreateHandle(isolate, new PowerSaveBlocker(isolate)); } // static -mate::Handle PowerSaveBlocker::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new PowerSaveBlocker); +void PowerSaveBlocker::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("start", &PowerSaveBlocker::Start) + .SetMethod("stop", &PowerSaveBlocker::Stop) + .SetMethod("isStarted", &PowerSaveBlocker::IsStarted); } } // namespace api diff --git a/atom/browser/api/atom_api_power_save_blocker.h b/atom/browser/api/atom_api_power_save_blocker.h index a698d746ceb..c24ae0aa4b6 100644 --- a/atom/browser/api/atom_api_power_save_blocker.h +++ b/atom/browser/api/atom_api_power_save_blocker.h @@ -24,13 +24,12 @@ class PowerSaveBlocker : public mate::TrackableObject { public: static mate::Handle Create(v8::Isolate* isolate); - protected: - PowerSaveBlocker(); - ~PowerSaveBlocker() override; + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); - // mate::Wrappable implementations: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; + protected: + explicit PowerSaveBlocker(v8::Isolate* isolate); + ~PowerSaveBlocker() override; private: void UpdatePowerSaveBlocker(); diff --git a/atom/browser/api/atom_api_protocol.cc b/atom/browser/api/atom_api_protocol.cc index 09da9c71cad..3835fac62d7 100644 --- a/atom/browser/api/atom_api_protocol.cc +++ b/atom/browser/api/atom_api_protocol.cc @@ -22,37 +22,11 @@ namespace atom { namespace api { -Protocol::Protocol(AtomBrowserContext* browser_context) +Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context) : request_context_getter_(browser_context->GetRequestContext()), job_factory_(browser_context->job_factory()) { CHECK(job_factory_); -} - -mate::ObjectTemplateBuilder Protocol::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) - .SetMethod("registerStandardSchemes", &Protocol::RegisterStandardSchemes) - .SetMethod("registerServiceWorkerSchemes", - &Protocol::RegisterServiceWorkerSchemes) - .SetMethod("registerStringProtocol", - &Protocol::RegisterProtocol) - .SetMethod("registerBufferProtocol", - &Protocol::RegisterProtocol) - .SetMethod("registerFileProtocol", - &Protocol::RegisterProtocol) - .SetMethod("registerHttpProtocol", - &Protocol::RegisterProtocol) - .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol) - .SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled) - .SetMethod("interceptStringProtocol", - &Protocol::InterceptProtocol) - .SetMethod("interceptBufferProtocol", - &Protocol::InterceptProtocol) - .SetMethod("interceptFileProtocol", - &Protocol::InterceptProtocol) - .SetMethod("interceptHttpProtocol", - &Protocol::InterceptProtocol) - .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol); + Init(isolate); } void Protocol::RegisterStandardSchemes( @@ -150,7 +124,35 @@ std::string Protocol::ErrorCodeToString(ProtocolError error) { // static mate::Handle Protocol::Create( v8::Isolate* isolate, AtomBrowserContext* browser_context) { - return mate::CreateHandle(isolate, new Protocol(browser_context)); + return mate::CreateHandle(isolate, new Protocol(isolate, browser_context)); +} + +// static +void Protocol::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("registerStandardSchemes", &Protocol::RegisterStandardSchemes) + .SetMethod("registerServiceWorkerSchemes", + &Protocol::RegisterServiceWorkerSchemes) + .SetMethod("registerStringProtocol", + &Protocol::RegisterProtocol) + .SetMethod("registerBufferProtocol", + &Protocol::RegisterProtocol) + .SetMethod("registerFileProtocol", + &Protocol::RegisterProtocol) + .SetMethod("registerHttpProtocol", + &Protocol::RegisterProtocol) + .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol) + .SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled) + .SetMethod("interceptStringProtocol", + &Protocol::InterceptProtocol) + .SetMethod("interceptBufferProtocol", + &Protocol::InterceptProtocol) + .SetMethod("interceptFileProtocol", + &Protocol::InterceptProtocol) + .SetMethod("interceptHttpProtocol", + &Protocol::InterceptProtocol) + .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol); } } // namespace api diff --git a/atom/browser/api/atom_api_protocol.h b/atom/browser/api/atom_api_protocol.h index 107fbf1ce71..d7fa7f5211f 100644 --- a/atom/browser/api/atom_api_protocol.h +++ b/atom/browser/api/atom_api_protocol.h @@ -30,7 +30,7 @@ class AtomURLRequestJobFactory; namespace api { -class Protocol : public mate::Wrappable { +class Protocol : public mate::Wrappable { public: using Handler = base::Callback)>; @@ -40,12 +40,11 @@ class Protocol : public mate::Wrappable { static mate::Handle Create( v8::Isolate* isolate, AtomBrowserContext* browser_context); - protected: - explicit Protocol(AtomBrowserContext* browser_context); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); - // mate::Wrappable implementations: - virtual mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate); + protected: + Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context); private: // Possible errors. diff --git a/atom/browser/api/atom_api_screen.cc b/atom/browser/api/atom_api_screen.cc index 407a71f0cc4..61b722d7a44 100644 --- a/atom/browser/api/atom_api_screen.cc +++ b/atom/browser/api/atom_api_screen.cc @@ -47,9 +47,11 @@ std::vector MetricsToArray(uint32_t metrics) { } // namespace -Screen::Screen(gfx::Screen* screen) : screen_(screen) { +Screen::Screen(v8::Isolate* isolate, gfx::Screen* screen) + : screen_(screen) { displays_ = screen_->GetAllDisplays(); screen_->AddObserver(this); + Init(isolate); } Screen::~Screen() { @@ -100,16 +102,6 @@ void Screen::OnDisplayMetricsChanged(const gfx::Display& display, Emit("display-metrics-changed", display, MetricsToArray(changed_metrics)); } -mate::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) - .SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint) - .SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay) - .SetMethod("getAllDisplays", &Screen::GetAllDisplays) - .SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint) - .SetMethod("getDisplayMatching", &Screen::GetDisplayMatching); -} - // static v8::Local Screen::Create(v8::Isolate* isolate) { if (!Browser::Get()->is_ready()) { @@ -126,7 +118,18 @@ v8::Local Screen::Create(v8::Isolate* isolate) { return v8::Null(isolate); } - return mate::CreateHandle(isolate, new Screen(screen)).ToV8(); + return mate::CreateHandle(isolate, new Screen(isolate, screen)).ToV8(); +} + +// static +void Screen::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint) + .SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay) + .SetMethod("getAllDisplays", &Screen::GetAllDisplays) + .SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint) + .SetMethod("getDisplayMatching", &Screen::GetDisplayMatching); } } // namespace api diff --git a/atom/browser/api/atom_api_screen.h b/atom/browser/api/atom_api_screen.h index f724130fa7f..14fc8ce30e7 100644 --- a/atom/browser/api/atom_api_screen.h +++ b/atom/browser/api/atom_api_screen.h @@ -21,14 +21,17 @@ namespace atom { namespace api { -class Screen : public mate::EventEmitter, +class Screen : public mate::EventEmitter, public gfx::DisplayObserver { public: static v8::Local Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + protected: - explicit Screen(gfx::Screen* screen); - virtual ~Screen(); + Screen(v8::Isolate* isolate, gfx::Screen* screen); + ~Screen() override; gfx::Point GetCursorScreenPoint(); gfx::Display GetPrimaryDisplay(); @@ -42,10 +45,6 @@ class Screen : public mate::EventEmitter, void OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) override; - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; - private: gfx::Screen* screen_; std::vector displays_; diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 222591e92e9..140135d329e 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -288,14 +288,15 @@ void ClearHostResolverCacheInIO( } // namespace -Session::Session(AtomBrowserContext* browser_context) +Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context) : devtools_network_emulation_client_id_(base::GenerateGUID()), browser_context_(browser_context) { - AttachAsUserData(browser_context); - // Observe DownloadManger to get download notifications. content::BrowserContext::GetDownloadManager(browser_context)-> AddObserver(this); + + Init(isolate); + AttachAsUserData(browser_context); } Session::~Session() { @@ -308,6 +309,9 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, auto web_contents = item->GetWebContents(); if (SavePageHandler::IsSavePageTypes(item->GetMimeType())) return; + + v8::Locker locker(isolate()); + v8::HandleScope handle_scope(isolate()); bool prevent_default = Emit( "will-download", DownloadItem::Create(isolate(), item), @@ -454,7 +458,8 @@ mate::Handle Session::CreateFrom( if (existing) return mate::CreateHandle(isolate, static_cast(existing)); - auto handle = mate::CreateHandle(isolate, new Session(browser_context)); + auto handle = mate::CreateHandle( + isolate, new Session(isolate, browser_context)); g_wrap_session.Run(handle.ToV8()); return handle; } diff --git a/atom/browser/api/atom_api_session.h b/atom/browser/api/atom_api_session.h index 7da01acdaaa..5e08a85aa7d 100644 --- a/atom/browser/api/atom_api_session.h +++ b/atom/browser/api/atom_api_session.h @@ -58,7 +58,7 @@ class Session: public mate::TrackableObject, v8::Local prototype); protected: - explicit Session(AtomBrowserContext* browser_context); + Session(v8::Isolate* isolate, AtomBrowserContext* browser_context); ~Session(); // content::DownloadManager::Observer: diff --git a/atom/browser/api/atom_api_tray.cc b/atom/browser/api/atom_api_tray.cc index 5f351f48504..34fe81b92b2 100644 --- a/atom/browser/api/atom_api_tray.cc +++ b/atom/browser/api/atom_api_tray.cc @@ -22,7 +22,7 @@ namespace atom { namespace api { -Tray::Tray(const gfx::Image& image) +Tray::Tray(v8::Isolate* isolate, const gfx::Image& image) : tray_icon_(TrayIcon::Create()) { tray_icon_->SetImage(image); tray_icon_->AddObserver(this); @@ -32,13 +32,13 @@ Tray::~Tray() { } // static -mate::Wrappable* Tray::New(v8::Isolate* isolate, const gfx::Image& image) { +mate::WrappableBase* Tray::New(v8::Isolate* isolate, const gfx::Image& image) { if (!Browser::Get()->is_ready()) { isolate->ThrowException(v8::Exception::Error(mate::StringToV8( isolate, "Cannot create Tray before app is ready"))); return nullptr; } - return new Tray(image); + return new Tray(isolate, image); } void Tray::OnClicked(const gfx::Rect& bounds, int modifiers) { diff --git a/atom/browser/api/atom_api_tray.h b/atom/browser/api/atom_api_tray.h index 0e0d153ad0d..84e68220dba 100644 --- a/atom/browser/api/atom_api_tray.h +++ b/atom/browser/api/atom_api_tray.h @@ -32,13 +32,14 @@ class Menu; class Tray : public mate::TrackableObject, public TrayIconObserver { public: - static mate::Wrappable* New(v8::Isolate* isolate, const gfx::Image& image); + static mate::WrappableBase* New( + v8::Isolate* isolate, const gfx::Image& image); static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); protected: - explicit Tray(const gfx::Image& image); + Tray(v8::Isolate* isolate, const gfx::Image& image); ~Tray() override; // TrayIconObserver: diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 73aa8ba577a..cec998a8722 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -215,14 +215,17 @@ content::ServiceWorkerContext* GetServiceWorkerContext( } // namespace -WebContents::WebContents(content::WebContents* web_contents) +WebContents::WebContents(v8::Isolate* isolate, + content::WebContents* web_contents) : content::WebContentsObserver(web_contents), embedder_(nullptr), type_(REMOTE), request_id_(0), background_throttling_(true) { - AttachAsUserData(web_contents); web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent()); + + Init(isolate); + AttachAsUserData(web_contents); } WebContents::WebContents(v8::Isolate* isolate, @@ -270,7 +273,6 @@ WebContents::WebContents(v8::Isolate* isolate, } Observe(web_contents); - AttachAsUserData(web_contents); InitWithWebContents(web_contents); managed_web_contents()->GetView()->SetDelegate(this); @@ -299,6 +301,9 @@ WebContents::WebContents(v8::Isolate* isolate, if (owner_window) SetOwnerWindow(owner_window); } + + Init(isolate); + AttachAsUserData(web_contents); } WebContents::~WebContents() { @@ -1290,7 +1295,8 @@ mate::Handle WebContents::CreateFrom( return mate::CreateHandle(isolate, static_cast(existing)); // Otherwise create a new WebContents wrapper object. - auto handle = mate::CreateHandle(isolate, new WebContents(web_contents)); + auto handle = mate::CreateHandle( + isolate, new WebContents(isolate, web_contents)); g_wrap_web_contents.Run(handle.ToV8()); return handle; } diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index bc2d4106f5f..9deb1696c41 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -55,6 +55,9 @@ class WebContents : public mate::TrackableObject, static mate::Handle Create( v8::Isolate* isolate, const mate::Dictionary& options); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + int GetID() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const mate::Dictionary& options); @@ -156,12 +159,8 @@ class WebContents : public mate::TrackableObject, v8::Local DevToolsWebContents(v8::Isolate* isolate); v8::Local Debugger(v8::Isolate* isolate); - // mate::TrackableObject: - static void BuildPrototype(v8::Isolate* isolate, - v8::Local prototype); - protected: - explicit WebContents(content::WebContents* web_contents); + WebContents(v8::Isolate* isolate, content::WebContents* web_contents); WebContents(v8::Isolate* isolate, const mate::Dictionary& options); ~WebContents(); diff --git a/atom/browser/api/atom_api_web_request.cc b/atom/browser/api/atom_api_web_request.cc index a987369ed82..867901df065 100644 --- a/atom/browser/api/atom_api_web_request.cc +++ b/atom/browser/api/atom_api_web_request.cc @@ -36,8 +36,10 @@ namespace atom { namespace api { -WebRequest::WebRequest(AtomBrowserContext* browser_context) +WebRequest::WebRequest(v8::Isolate* isolate, + AtomBrowserContext* browser_context) : browser_context_(browser_context) { + Init(isolate); } WebRequest::~WebRequest() { @@ -81,7 +83,7 @@ void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) { mate::Handle WebRequest::Create( v8::Isolate* isolate, AtomBrowserContext* browser_context) { - return mate::CreateHandle(isolate, new WebRequest(browser_context)); + return mate::CreateHandle(isolate, new WebRequest(isolate, browser_context)); } // static diff --git a/atom/browser/api/atom_api_web_request.h b/atom/browser/api/atom_api_web_request.h index 9a6e17a0460..edcdcc5339e 100644 --- a/atom/browser/api/atom_api_web_request.h +++ b/atom/browser/api/atom_api_web_request.h @@ -21,13 +21,12 @@ class WebRequest : public mate::TrackableObject { static mate::Handle Create(v8::Isolate* isolate, AtomBrowserContext* browser_context); - // mate::TrackableObject: static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); protected: - explicit WebRequest(AtomBrowserContext* browser_context); - ~WebRequest(); + WebRequest(v8::Isolate* isolate, AtomBrowserContext* browser_context); + ~WebRequest() override; // C++ can not distinguish overloaded member function. template diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index 2bac6fa808d..c61a7f566c0 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -287,7 +287,7 @@ void Window::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { #endif // static -mate::Wrappable* Window::New(v8::Isolate* isolate, mate::Arguments* args) { +mate::WrappableBase* Window::New(v8::Isolate* isolate, mate::Arguments* args) { if (!Browser::Get()->is_ready()) { isolate->ThrowException(v8::Exception::Error(mate::StringToV8( isolate, "Cannot create BrowserWindow before app is ready"))); diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 0b8f0e3c491..a00e063d99f 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -38,7 +38,7 @@ class WebContents; class Window : public mate::TrackableObject, public NativeWindowObserver { public: - static mate::Wrappable* New(v8::Isolate* isolate, mate::Arguments* args); + static mate::WrappableBase* New(v8::Isolate* isolate, mate::Arguments* args); static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); @@ -51,7 +51,7 @@ class Window : public mate::TrackableObject, protected: Window(v8::Isolate* isolate, const mate::Dictionary& options); - virtual ~Window(); + ~Window() override; // NativeWindowObserver: void WillCloseWindow(bool* prevent_default) override; diff --git a/atom/browser/api/event.cc b/atom/browser/api/event.cc index 5c87292ea52..74e78a85cd1 100644 --- a/atom/browser/api/event.cc +++ b/atom/browser/api/event.cc @@ -11,31 +11,15 @@ namespace mate { -namespace { - -v8::Persistent template_; - -} // namespace - -Event::Event() +Event::Event(v8::Isolate* isolate) : sender_(NULL), message_(NULL) { + Init(isolate); } Event::~Event() { } -ObjectTemplateBuilder Event::GetObjectTemplateBuilder(v8::Isolate* isolate) { - if (template_.IsEmpty()) - template_.Reset(isolate, ObjectTemplateBuilder(isolate) - .SetMethod("preventDefault", &Event::PreventDefault) - .SetMethod("sendReply", &Event::SendReply) - .Build()); - - return ObjectTemplateBuilder( - isolate, v8::Local::New(isolate, template_)); -} - void Event::SetSenderAndMessage(content::WebContents* sender, IPC::Message* message) { DCHECK(!sender_); @@ -52,7 +36,7 @@ void Event::WebContentsDestroyed() { } void Event::PreventDefault(v8::Isolate* isolate) { - GetWrapper(isolate)->Set(StringToV8(isolate, "defaultPrevented"), + GetWrapper()->Set(StringToV8(isolate, "defaultPrevented"), v8::True(isolate)); } @@ -66,7 +50,15 @@ bool Event::SendReply(const base::string16& json) { // static Handle Event::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new Event); + return CreateHandle(isolate, new Event(isolate)); +} + +// static +void Event::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("preventDefault", &Event::PreventDefault) + .SetMethod("sendReply", &Event::SendReply); } } // namespace mate diff --git a/atom/browser/api/event.h b/atom/browser/api/event.h index 5cdc08324b7..81db638a0dc 100644 --- a/atom/browser/api/event.h +++ b/atom/browser/api/event.h @@ -15,11 +15,14 @@ class Message; namespace mate { -class Event : public Wrappable, +class Event : public Wrappable, public content::WebContentsObserver { public: static Handle Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + // Pass the sender and message to be replied. void SetSenderAndMessage(content::WebContents* sender, IPC::Message* message); @@ -30,11 +33,8 @@ class Event : public Wrappable, bool SendReply(const base::string16& json); protected: - Event(); - virtual ~Event(); - - // Wrappable implementations: - ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate* isolate) override; + explicit Event(v8::Isolate* isolate); + ~Event() override; // content::WebContentsObserver implementations: void WebContentsDestroyed() override; diff --git a/atom/browser/api/event_emitter.cc b/atom/browser/api/event_emitter.cc index be7018dafa4..7e392fddee3 100644 --- a/atom/browser/api/event_emitter.cc +++ b/atom/browser/api/event_emitter.cc @@ -34,11 +34,13 @@ v8::Local CreateEventObject(v8::Isolate* isolate) { } // namespace -EventEmitter::EventEmitter() { -} +namespace internal { -v8::Local EventEmitter::CreateJSEvent( - v8::Isolate* isolate, content::WebContents* sender, IPC::Message* message) { +v8::Local CreateJSEvent( + v8::Isolate* isolate, + v8::Local object, + content::WebContents* sender, + IPC::Message* message) { v8::Local event; bool use_native_event = sender && message; @@ -49,16 +51,20 @@ v8::Local EventEmitter::CreateJSEvent( } else { event = CreateEventObject(isolate); } - mate::Dictionary(isolate, event).Set("sender", GetWrapper(isolate)); + mate::Dictionary(isolate, event).Set("sender", object); return event; } -v8::Local EventEmitter::CreateCustomEvent( - v8::Isolate* isolate, v8::Local custom_event) { +v8::Local CreateCustomEvent( + v8::Isolate* isolate, + v8::Local object, + v8::Local custom_event) { v8::Local event = CreateEventObject(isolate); (void)event->SetPrototype(custom_event->CreationContext(), custom_event); - mate::Dictionary(isolate, event).Set("sender", GetWrapper(isolate)); + mate::Dictionary(isolate, event).Set("sender", object); return event; } +} // namespace internal + } // namespace mate diff --git a/atom/browser/api/event_emitter.h b/atom/browser/api/event_emitter.h index 42816d42a45..226accfe626 100644 --- a/atom/browser/api/event_emitter.h +++ b/atom/browser/api/event_emitter.h @@ -20,17 +20,40 @@ class Message; namespace mate { +namespace internal { + +v8::Local CreateJSEvent(v8::Isolate* isolate, + v8::Local object, + content::WebContents* sender, + IPC::Message* message); +v8::Local CreateCustomEvent( + v8::Isolate* isolate, + v8::Local object, + v8::Local event); + +} // namespace internal + // Provide helperers to emit event in JavaScript. -class EventEmitter : public Wrappable { +template +class EventEmitter : public Wrappable { public: typedef std::vector> ValueArray; + // Make the convinient methods visible: + // https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members + v8::Local GetWrapper(v8::Isolate* isolate = nullptr) { + return Wrappable::GetWrapper(); + } + v8::Isolate* isolate() const { return Wrappable::isolate(); } + // this.emit(name, event, args...); template bool EmitCustomEvent(const base::StringPiece& name, v8::Local event, const Args&... args) { - return EmitWithEvent(name, CreateCustomEvent(isolate(), event), args...); + return EmitWithEvent( + name, + internal::CreateCustomEvent(isolate(), GetWrapper(), event), args...); } // this.emit(name, new Event(), args...); @@ -47,12 +70,13 @@ class EventEmitter : public Wrappable { const Args&... args) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - v8::Local event = CreateJSEvent(isolate(), sender, message); + v8::Local event = internal::CreateJSEvent( + isolate(), GetWrapper(), sender, message); return EmitWithEvent(name, event, args...); } protected: - EventEmitter(); + EventEmitter() {} private: // this.emit(name, event, args...); @@ -67,12 +91,6 @@ class EventEmitter : public Wrappable { StringToV8(isolate(), "defaultPrevented"))->BooleanValue(); } - v8::Local CreateJSEvent(v8::Isolate* isolate, - content::WebContents* sender, - IPC::Message* message); - v8::Local CreateCustomEvent( - v8::Isolate* isolate, v8::Local event); - DISALLOW_COPY_AND_ASSIGN(EventEmitter); }; diff --git a/atom/browser/api/trackable_object.cc b/atom/browser/api/trackable_object.cc index 77a936cde02..5148df627c8 100644 --- a/atom/browser/api/trackable_object.cc +++ b/atom/browser/api/trackable_object.cc @@ -37,15 +37,6 @@ TrackableObjectBase::~TrackableObjectBase() { cleanup_.Run(); } -void TrackableObjectBase::AfterInit(v8::Isolate* isolate) { - if (wrapped_) - AttachAsUserData(wrapped_); -} - -void TrackableObjectBase::MarkDestroyed() { - GetWrapper(isolate())->SetAlignedPointerInInternalField(0, nullptr); -} - base::Closure TrackableObjectBase::GetDestroyClosure() { return base::Bind(&TrackableObjectBase::Destroy, weak_factory_.GetWeakPtr()); } diff --git a/atom/browser/api/trackable_object.h b/atom/browser/api/trackable_object.h index 7c4ed03fe05..5a036f4297d 100644 --- a/atom/browser/api/trackable_object.h +++ b/atom/browser/api/trackable_object.h @@ -21,7 +21,7 @@ class SupportsUserData; namespace mate { // Users should use TrackableObject instead. -class TrackableObjectBase : public mate::EventEmitter { +class TrackableObjectBase { public: TrackableObjectBase(); @@ -32,13 +32,7 @@ class TrackableObjectBase : public mate::EventEmitter { void AttachAsUserData(base::SupportsUserData* wrapped); protected: - ~TrackableObjectBase() override; - - // mate::Wrappable: - void AfterInit(v8::Isolate* isolate) override; - - // Mark the JS object as destroyed. - void MarkDestroyed(); + virtual ~TrackableObjectBase(); // Returns a closure that can destroy the native class. base::Closure GetDestroyClosure(); @@ -65,8 +59,14 @@ class TrackableObjectBase : public mate::EventEmitter { // All instances of TrackableObject will be kept in a weak map and can be got // from its ID. template -class TrackableObject : public TrackableObjectBase { +class TrackableObject : public TrackableObjectBase, + public mate::EventEmitter { public: + // Mark the JS object as destroyed. + void MarkDestroyed() { + Wrappable::GetWrapper()->SetAlignedPointerInInternalField(0, nullptr); + } + // Finds out the TrackableObject from its ID in weak map. static T* FromWeakMapID(v8::Isolate* isolate, int32_t id) { if (!weak_map_) @@ -106,6 +106,7 @@ class TrackableObject : public TrackableObjectBase { protected: TrackableObject() {} + ~TrackableObject() override { RemoveFromWeakMap(); } @@ -116,38 +117,22 @@ class TrackableObject : public TrackableObjectBase { RegisterDestructionCallback( base::Bind(&TrackableObject::ReleaseAllWeakReferences)); } - weak_map_id_ = weak_map_->Add(isolate, GetWrapper(isolate)); - TrackableObjectBase::AfterInit(isolate); + weak_map_id_ = weak_map_->Add(isolate, Wrappable::GetWrapper()); + if (wrapped_) + AttachAsUserData(wrapped_); } private: - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override { - if (template_.IsEmpty()) { - auto templ = v8::ObjectTemplate::New(isolate); - T::BuildPrototype(isolate, templ); - template_.Reset(isolate, templ); - } - - return ObjectTemplateBuilder( - isolate, v8::Local::New(isolate, template_)); - } - // Releases all weak references in weak map, called when app is terminating. static void ReleaseAllWeakReferences() { weak_map_.reset(); } - static v8::Persistent template_; static scoped_ptr weak_map_; DISALLOW_COPY_AND_ASSIGN(TrackableObject); }; -template -v8::Persistent TrackableObject::template_; - template scoped_ptr TrackableObject::weak_map_; diff --git a/atom/common/api/atom_api_asar.cc b/atom/common/api/atom_api_asar.cc index 4bfb0ed4c1b..1b0ea799e7d 100644 --- a/atom/common/api/atom_api_asar.cc +++ b/atom/common/api/atom_api_asar.cc @@ -18,21 +18,39 @@ namespace { -v8::Persistent template_; - -class Archive : public mate::Wrappable { +class Archive : public mate::Wrappable { public: static v8::Local Create(v8::Isolate* isolate, const base::FilePath& path) { scoped_ptr archive(new asar::Archive(path)); if (!archive->Init()) return v8::False(isolate); - return (new Archive(std::move(archive)))->GetWrapper(isolate); + return (new Archive(isolate, std::move(archive)))->GetWrapper(); + } + + static void BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetProperty("path", &Archive::GetPath) + .SetMethod("getFileInfo", &Archive::GetFileInfo) + .SetMethod("stat", &Archive::Stat) + .SetMethod("readdir", &Archive::Readdir) + .SetMethod("realpath", &Archive::Realpath) + .SetMethod("copyFileOut", &Archive::CopyFileOut) + .SetMethod("getFd", &Archive::GetFD) + .SetMethod("destroy", &Archive::Destroy); } protected: - explicit Archive(scoped_ptr archive) - : archive_(std::move(archive)) {} + Archive(v8::Isolate* isolate, scoped_ptr archive) + : archive_(std::move(archive)) { + Init(isolate); + } + + // Returns the path of the file. + base::FilePath GetPath() { + return archive_->path(); + } // Reads the offset and size of file. v8::Local GetFileInfo(v8::Isolate* isolate, @@ -101,24 +119,6 @@ class Archive : public mate::Wrappable { archive_.reset(); } - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate* isolate) { - if (template_.IsEmpty()) - template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) - .SetValue("path", archive_->path()) - .SetMethod("getFileInfo", &Archive::GetFileInfo) - .SetMethod("stat", &Archive::Stat) - .SetMethod("readdir", &Archive::Readdir) - .SetMethod("realpath", &Archive::Realpath) - .SetMethod("copyFileOut", &Archive::CopyFileOut) - .SetMethod("getFd", &Archive::GetFD) - .SetMethod("destroy", &Archive::Destroy) - .Build()); - - return mate::ObjectTemplateBuilder( - isolate, v8::Local::New(isolate, template_)); - } - private: scoped_ptr archive_; diff --git a/atom/common/api/atom_api_id_weak_map.cc b/atom/common/api/atom_api_id_weak_map.cc index f32e33682df..0d3ddae3cc0 100644 --- a/atom/common/api/atom_api_id_weak_map.cc +++ b/atom/common/api/atom_api_id_weak_map.cc @@ -12,7 +12,7 @@ namespace atom { namespace api { -IDWeakMap::IDWeakMap() { +IDWeakMap::IDWeakMap(v8::Isolate* isolate) { } IDWeakMap::~IDWeakMap() { @@ -52,8 +52,8 @@ void IDWeakMap::BuildPrototype(v8::Isolate* isolate, } // static -mate::Wrappable* IDWeakMap::Create(v8::Isolate* isolate) { - return new IDWeakMap; +mate::WrappableBase* IDWeakMap::Create(v8::Isolate* isolate) { + return new IDWeakMap(isolate); } } // namespace api diff --git a/atom/common/api/atom_api_id_weak_map.h b/atom/common/api/atom_api_id_weak_map.h index 0cf656f455b..616112ffe6f 100644 --- a/atom/common/api/atom_api_id_weak_map.h +++ b/atom/common/api/atom_api_id_weak_map.h @@ -13,15 +13,15 @@ namespace atom { namespace api { -class IDWeakMap : public mate::Wrappable { +class IDWeakMap : public mate::Wrappable { public: - static mate::Wrappable* Create(v8::Isolate* isolate); + static mate::WrappableBase* Create(v8::Isolate* isolate); static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); protected: - IDWeakMap(); + explicit IDWeakMap(v8::Isolate* isolate); ~IDWeakMap(); private: diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index 3dda326f59f..1c90fe7080f 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -168,35 +168,15 @@ bool ReadImageSkiaFromICO(gfx::ImageSkia* image, const base::FilePath& path) { } #endif -v8::Persistent template_; - } // namespace -NativeImage::NativeImage() {} - -NativeImage::NativeImage(const gfx::Image& image) : image_(image) {} +NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image) + : image_(image) { + Init(isolate); +} NativeImage::~NativeImage() {} -mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - if (template_.IsEmpty()) - template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate) - .SetMethod("toPng", &NativeImage::ToPNG) - .SetMethod("toJpeg", &NativeImage::ToJPEG) - .SetMethod("getNativeHandle", &NativeImage::GetNativeHandle) - .SetMethod("toDataURL", &NativeImage::ToDataURL) - .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. - .SetMethod("isEmpty", &NativeImage::IsEmpty) - .SetMethod("getSize", &NativeImage::GetSize) - .SetMethod("setTemplateImage", &NativeImage::SetTemplateImage) - .SetMethod("isTemplateImage", &NativeImage::IsTemplateImage) - .Build()); - - return mate::ObjectTemplateBuilder( - isolate, v8::Local::New(isolate, template_)); -} - v8::Local NativeImage::ToPNG(v8::Isolate* isolate) { scoped_refptr png = image_.As1xPNGBytes(); return node::Buffer::Copy(isolate, @@ -255,13 +235,13 @@ bool NativeImage::IsTemplateImage() { // static mate::Handle NativeImage::CreateEmpty(v8::Isolate* isolate) { - return mate::CreateHandle(isolate, new NativeImage); + return mate::CreateHandle(isolate, new NativeImage(isolate, gfx::Image())); } // static mate::Handle NativeImage::Create( v8::Isolate* isolate, const gfx::Image& image) { - return mate::CreateHandle(isolate, new NativeImage(image)); + return mate::CreateHandle(isolate, new NativeImage(isolate, image)); } // static @@ -330,6 +310,21 @@ mate::Handle NativeImage::CreateFromDataURL( return CreateEmpty(isolate); } +// static +void NativeImage::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) + .SetMethod("toPng", &NativeImage::ToPNG) + .SetMethod("toJpeg", &NativeImage::ToJPEG) + .SetMethod("getNativeHandle", &NativeImage::GetNativeHandle) + .SetMethod("toDataURL", &NativeImage::ToDataURL) + .SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated. + .SetMethod("isEmpty", &NativeImage::IsEmpty) + .SetMethod("getSize", &NativeImage::GetSize) + .SetMethod("setTemplateImage", &NativeImage::SetTemplateImage) + .SetMethod("isTemplateImage", &NativeImage::IsTemplateImage); +} + } // namespace api } // namespace atom diff --git a/atom/common/api/atom_api_native_image.h b/atom/common/api/atom_api_native_image.h index 145f5ff1dcd..79844604706 100644 --- a/atom/common/api/atom_api_native_image.h +++ b/atom/common/api/atom_api_native_image.h @@ -29,7 +29,7 @@ namespace atom { namespace api { -class NativeImage : public mate::Wrappable { +class NativeImage : public mate::Wrappable { public: static mate::Handle CreateEmpty(v8::Isolate* isolate); static mate::Handle Create( @@ -45,18 +45,14 @@ class NativeImage : public mate::Wrappable { static mate::Handle CreateFromDataURL( v8::Isolate* isolate, const GURL& url); - // The default constructor should only be used by image_converter.cc. - NativeImage(); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); const gfx::Image& image() const { return image_; } protected: - explicit NativeImage(const gfx::Image& image); - virtual ~NativeImage(); - - // mate::Wrappable: - mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate) override; + NativeImage(v8::Isolate* isolate, const gfx::Image& image); + ~NativeImage() override; private: v8::Local ToPNG(v8::Isolate* isolate); diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index e00b901bfff..32b8a84f26d 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -54,8 +54,9 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { } // namespace -WebFrame::WebFrame() +WebFrame::WebFrame(v8::Isolate* isolate) : web_frame_(blink::WebLocalFrame::frameForCurrentContext()) { + Init(isolate); } WebFrame::~WebFrame() { @@ -67,7 +68,7 @@ void WebFrame::SetName(const std::string& name) { double WebFrame::SetZoomLevel(double level) { double ret = web_frame_->view()->setZoomLevel(level); - mate::EmitEvent(isolate(), GetWrapper(isolate()), "zoom-level-changed", ret); + mate::EmitEvent(isolate(), GetWrapper(), "zoom-level-changed", ret); return ret; } @@ -162,9 +163,15 @@ void WebFrame::ExecuteJavaScript(const base::string16& code, callback.release()); } -mate::ObjectTemplateBuilder WebFrame::GetObjectTemplateBuilder( - v8::Isolate* isolate) { - return mate::ObjectTemplateBuilder(isolate) +// static +mate::Handle WebFrame::Create(v8::Isolate* isolate) { + return CreateHandle(isolate, new WebFrame(isolate)); +} + +// static +void WebFrame::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("setName", &WebFrame::SetName) .SetMethod("setZoomLevel", &WebFrame::SetZoomLevel) .SetMethod("getZoomLevel", &WebFrame::GetZoomLevel) @@ -187,11 +194,6 @@ mate::ObjectTemplateBuilder WebFrame::GetObjectTemplateBuilder( .SetMethod("executeJavaScript", &WebFrame::ExecuteJavaScript); } -// static -mate::Handle WebFrame::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new WebFrame); -} - } // namespace api } // namespace atom diff --git a/atom/renderer/api/atom_api_web_frame.h b/atom/renderer/api/atom_api_web_frame.h index d55b24fd25e..e1eeb224930 100644 --- a/atom/renderer/api/atom_api_web_frame.h +++ b/atom/renderer/api/atom_api_web_frame.h @@ -26,13 +26,16 @@ namespace api { class SpellCheckClient; -class WebFrame : public mate::Wrappable { +class WebFrame : public mate::Wrappable { public: static mate::Handle Create(v8::Isolate* isolate); + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + private: - WebFrame(); - virtual ~WebFrame(); + explicit WebFrame(v8::Isolate* isolate); + ~WebFrame() override; void SetName(const std::string& name); @@ -66,10 +69,6 @@ class WebFrame : public mate::Wrappable { // Excecuting scripts. void ExecuteJavaScript(const base::string16& code, mate::Arguments* args); - // mate::Wrappable: - virtual mate::ObjectTemplateBuilder GetObjectTemplateBuilder( - v8::Isolate* isolate); - scoped_ptr spell_check_client_; blink::WebLocalFrame* web_frame_; diff --git a/vendor/native_mate b/vendor/native_mate index 553326b0069..0df2d882ea2 160000 --- a/vendor/native_mate +++ b/vendor/native_mate @@ -1 +1 @@ -Subproject commit 553326b00696fcda106a8866872a8f2ad6caff0d +Subproject commit 0df2d882ea2286e6335f206b7002037fce66c4a5 From 60d2cb8a84d9dd74b5178d5da923e6da66c871fc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 10:19:25 +0900 Subject: [PATCH 0591/1265] Remove the isolate parameter of GetWrapper --- atom/browser/api/atom_api_menu.cc | 2 +- atom/browser/api/atom_api_window.cc | 4 ++-- atom/browser/api/event_emitter.h | 6 ++---- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/atom/browser/api/atom_api_menu.cc b/atom/browser/api/atom_api_menu.cc index ec222ba1540..996c71739bc 100644 --- a/atom/browser/api/atom_api_menu.cc +++ b/atom/browser/api/atom_api_menu.cc @@ -28,7 +28,7 @@ Menu::~Menu() { } void Menu::AfterInit(v8::Isolate* isolate) { - mate::Dictionary wrappable(isolate, GetWrapper(isolate)); + mate::Dictionary wrappable(isolate, GetWrapper()); mate::Dictionary delegate; if (!wrappable.Get("delegate", &delegate)) return; diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index c61a7f566c0..ae5eec64cf9 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -151,7 +151,7 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { api_web_contents_ = web_contents.get(); // Keep a copy of the options for later use. - mate::Dictionary(isolate, web_contents->GetWrapper(isolate)).Set( + mate::Dictionary(isolate, web_contents->GetWrapper()).Set( "browserWindowOptions", options); // Creates BrowserWindow. @@ -817,7 +817,7 @@ v8::Local Window::From(v8::Isolate* isolate, NativeWindow* native_window) { auto existing = TrackableObject::FromWrappedClass(isolate, native_window); if (existing) - return existing->GetWrapper(isolate); + return existing->GetWrapper(); else return v8::Null(isolate); } diff --git a/atom/browser/api/event_emitter.h b/atom/browser/api/event_emitter.h index 226accfe626..99f6ed46e48 100644 --- a/atom/browser/api/event_emitter.h +++ b/atom/browser/api/event_emitter.h @@ -41,9 +41,7 @@ class EventEmitter : public Wrappable { // Make the convinient methods visible: // https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members - v8::Local GetWrapper(v8::Isolate* isolate = nullptr) { - return Wrappable::GetWrapper(); - } + v8::Local GetWrapper() { return Wrappable::GetWrapper(); } v8::Isolate* isolate() const { return Wrappable::isolate(); } // this.emit(name, event, args...); @@ -86,7 +84,7 @@ class EventEmitter : public Wrappable { const Args&... args) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - EmitEvent(isolate(), GetWrapper(isolate()), name, event, args...); + EmitEvent(isolate(), GetWrapper(), name, event, args...); return event->Get( StringToV8(isolate(), "defaultPrevented"))->BooleanValue(); } From 993695af07a0c59b5e97445939d7536658eb5660 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 10:23:36 +0900 Subject: [PATCH 0592/1265] Remove unneeded cleanup code --- atom/browser/api/atom_api_debugger.cc | 8 -------- atom/browser/api/atom_api_download_item.cc | 8 -------- atom/browser/api/atom_api_session.cc | 8 -------- atom/browser/api/atom_api_web_contents.cc | 8 -------- atom/browser/api/trackable_object.h | 7 ------- 5 files changed, 39 deletions(-) diff --git a/atom/browser/api/atom_api_debugger.cc b/atom/browser/api/atom_api_debugger.cc index 828c573188d..03490360133 100644 --- a/atom/browser/api/atom_api_debugger.cc +++ b/atom/browser/api/atom_api_debugger.cc @@ -167,16 +167,8 @@ void Debugger::BuildPrototype(v8::Isolate* isolate, .SetMethod("sendCommand", &Debugger::SendCommand); } -void ClearWrapDebugger() { - g_wrap_debugger.Reset(); -} - void SetWrapDebugger(const WrapDebuggerCallback& callback) { g_wrap_debugger = callback; - - // Cleanup the wrapper on exit. - atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback( - base::Bind(ClearWrapDebugger)); } } // namespace api diff --git a/atom/browser/api/atom_api_download_item.cc b/atom/browser/api/atom_api_download_item.cc index 10f7c454625..96826a250f5 100644 --- a/atom/browser/api/atom_api_download_item.cc +++ b/atom/browser/api/atom_api_download_item.cc @@ -184,16 +184,8 @@ mate::Handle DownloadItem::Create( return handle; } -void ClearWrapDownloadItem() { - g_wrap_download_item.Reset(); -} - void SetWrapDownloadItem(const WrapDownloadItemCallback& callback) { g_wrap_download_item = callback; - - // Cleanup the wrapper on exit. - atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback( - base::Bind(ClearWrapDownloadItem)); } } // namespace api diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 140135d329e..ec4e2aebe4c 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -494,16 +494,8 @@ void Session::BuildPrototype(v8::Isolate* isolate, .SetProperty("webRequest", &Session::WebRequest); } -void ClearWrapSession() { - g_wrap_session.Reset(); -} - void SetWrapSession(const WrapSessionCallback& callback) { g_wrap_session = callback; - - // Cleanup the wrapper on exit. - atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback( - base::Bind(ClearWrapSession)); } } // namespace api diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index cec998a8722..a48277490b0 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -1309,16 +1309,8 @@ mate::Handle WebContents::Create( return handle; } -void ClearWrapWebContents() { - g_wrap_web_contents.Reset(); -} - void SetWrapWebContents(const WrapWebContentsCallback& callback) { g_wrap_web_contents = callback; - - // Cleanup the wrapper on exit. - atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback( - base::Bind(ClearWrapWebContents)); } } // namespace api diff --git a/atom/browser/api/trackable_object.h b/atom/browser/api/trackable_object.h index 5a036f4297d..1c71d84e42c 100644 --- a/atom/browser/api/trackable_object.h +++ b/atom/browser/api/trackable_object.h @@ -114,8 +114,6 @@ class TrackableObject : public TrackableObjectBase, void AfterInit(v8::Isolate* isolate) override { if (!weak_map_) { weak_map_.reset(new atom::IDWeakMap); - RegisterDestructionCallback( - base::Bind(&TrackableObject::ReleaseAllWeakReferences)); } weak_map_id_ = weak_map_->Add(isolate, Wrappable::GetWrapper()); if (wrapped_) @@ -123,11 +121,6 @@ class TrackableObject : public TrackableObjectBase, } private: - // Releases all weak references in weak map, called when app is terminating. - static void ReleaseAllWeakReferences() { - weak_map_.reset(); - } - static scoped_ptr weak_map_; DISALLOW_COPY_AND_ASSIGN(TrackableObject); From 272592415d84a0390a567f41eb3cb0634911155b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 10:27:54 +0900 Subject: [PATCH 0593/1265] Fix building on non-mac --- atom/browser/api/atom_api_menu_views.cc | 4 ++-- atom/renderer/api/atom_api_web_frame.cc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/atom/browser/api/atom_api_menu_views.cc b/atom/browser/api/atom_api_menu_views.cc index f0422ed7ba5..4d1c902e175 100644 --- a/atom/browser/api/atom_api_menu_views.cc +++ b/atom/browser/api/atom_api_menu_views.cc @@ -49,8 +49,8 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) { } // static -mate::WrappableBase* Menu::Create() { - return new MenuViews(); +mate::WrappableBase* Menu::Create(v8::Isolate* isolate) { + return new MenuViews(isolate); } } // namespace api diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index 32b8a84f26d..0eebc94fc14 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -165,7 +165,7 @@ void WebFrame::ExecuteJavaScript(const base::string16& code, // static mate::Handle WebFrame::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new WebFrame(isolate)); + return mate::CreateHandle(isolate, new WebFrame(isolate)); } // static From 9fe3dbcfe0aeb02ff0323e2ef5d6961fad7e3c31 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 10:40:19 +0900 Subject: [PATCH 0594/1265] Make VS happy --- atom/browser/api/atom_api_app.cc | 2 +- atom/browser/api/atom_api_auto_updater.cc | 2 +- atom/browser/api/atom_api_global_shortcut.cc | 2 +- atom/browser/api/atom_api_power_monitor.cc | 2 +- atom/browser/api/atom_api_power_save_blocker.cc | 2 +- atom/browser/api/event.cc | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index a7842c42ce0..b35589ecad3 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -442,7 +442,7 @@ void App::OnCertificateManagerModelCreated( // static mate::Handle App::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new App(isolate)); + return mate::CreateHandle(isolate, new App(isolate)); } // static diff --git a/atom/browser/api/atom_api_auto_updater.cc b/atom/browser/api/atom_api_auto_updater.cc index 102bffb7118..cdf3406ae78 100644 --- a/atom/browser/api/atom_api_auto_updater.cc +++ b/atom/browser/api/atom_api_auto_updater.cc @@ -95,7 +95,7 @@ void AutoUpdater::QuitAndInstall() { // static mate::Handle AutoUpdater::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new AutoUpdater(isolate)); + return mate::CreateHandle(isolate, new AutoUpdater(isolate)); } // static diff --git a/atom/browser/api/atom_api_global_shortcut.cc b/atom/browser/api/atom_api_global_shortcut.cc index 3a9a3e7ddbe..2b1e5d6591a 100644 --- a/atom/browser/api/atom_api_global_shortcut.cc +++ b/atom/browser/api/atom_api_global_shortcut.cc @@ -69,7 +69,7 @@ void GlobalShortcut::UnregisterAll() { // static mate::Handle GlobalShortcut::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new GlobalShortcut(isolate)); + return mate::CreateHandle(isolate, new GlobalShortcut(isolate)); } // static diff --git a/atom/browser/api/atom_api_power_monitor.cc b/atom/browser/api/atom_api_power_monitor.cc index c72620c809d..15220c117c5 100644 --- a/atom/browser/api/atom_api_power_monitor.cc +++ b/atom/browser/api/atom_api_power_monitor.cc @@ -47,7 +47,7 @@ v8::Local PowerMonitor::Create(v8::Isolate* isolate) { return v8::Null(isolate); } - return CreateHandle(isolate, new PowerMonitor(isolate)).ToV8(); + return mate::CreateHandle(isolate, new PowerMonitor(isolate)).ToV8(); } // static diff --git a/atom/browser/api/atom_api_power_save_blocker.cc b/atom/browser/api/atom_api_power_save_blocker.cc index 5f8272b9848..b8adcb776e5 100644 --- a/atom/browser/api/atom_api_power_save_blocker.cc +++ b/atom/browser/api/atom_api_power_save_blocker.cc @@ -100,7 +100,7 @@ bool PowerSaveBlocker::IsStarted(int id) { // static mate::Handle PowerSaveBlocker::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new PowerSaveBlocker(isolate)); + return mate::CreateHandle(isolate, new PowerSaveBlocker(isolate)); } // static diff --git a/atom/browser/api/event.cc b/atom/browser/api/event.cc index 74e78a85cd1..f456cf2758b 100644 --- a/atom/browser/api/event.cc +++ b/atom/browser/api/event.cc @@ -50,7 +50,7 @@ bool Event::SendReply(const base::string16& json) { // static Handle Event::Create(v8::Isolate* isolate) { - return CreateHandle(isolate, new Event(isolate)); + return mate::CreateHandle(isolate, new Event(isolate)); } // static From 13f8599ba10217ceeac413fb5f4bb9ec460aa9a1 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sun, 24 Apr 2016 21:13:46 +0900 Subject: [PATCH 0595/1265] Add systemPreferences module --- .../api/atom_api_system_preferences.cc | 48 +++++++++++++++++++ .../browser/api/atom_api_system_preferences.h | 34 +++++++++++++ .../api/atom_api_system_preferences_mac.mm | 15 ++++++ atom/common/node_bindings.cc | 1 + filenames.gypi | 4 ++ lib/browser/api/exports/electron.js | 6 +++ lib/browser/api/system-preferences.js | 6 +++ 7 files changed, 114 insertions(+) create mode 100644 atom/browser/api/atom_api_system_preferences.cc create mode 100644 atom/browser/api/atom_api_system_preferences.h create mode 100644 atom/browser/api/atom_api_system_preferences_mac.mm create mode 100644 lib/browser/api/system-preferences.js diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc new file mode 100644 index 00000000000..53aaabd1732 --- /dev/null +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/api/atom_api_system_preferences.h" + +#include "atom/common/node_includes.h" +#include "native_mate/dictionary.h" + +namespace atom { + +namespace api { + +SystemPreferences::SystemPreferences(v8::Isolate* isolate) { + Init(isolate); +} + +SystemPreferences::~SystemPreferences() { +} + +// static +mate::Handle SystemPreferences::Create( + v8::Isolate* isolate) { + return mate::CreateHandle(isolate, new SystemPreferences(isolate)); +} + +// static +void SystemPreferences::BuildPrototype( + v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype); +} + +} // namespace api + +} // namespace atom + +namespace { + +void Initialize(v8::Local exports, v8::Local unused, + v8::Local context, void* priv) { + v8::Isolate* isolate = context->GetIsolate(); + mate::Dictionary dict(isolate, exports); + dict.Set("systemPreferences", atom::api::SystemPreferences::Create(isolate)); +} + +} // namespace + +NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_system_preferences, Initialize); diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h new file mode 100644 index 00000000000..22c68b2e873 --- /dev/null +++ b/atom/browser/api/atom_api_system_preferences.h @@ -0,0 +1,34 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_ +#define ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_ + +#include "atom/browser/api/event_emitter.h" +#include "native_mate/handle.h" + +namespace atom { + +namespace api { + +class SystemPreferences : public mate::EventEmitter { + public: + static mate::Handle Create(v8::Isolate* isolate); + + static void BuildPrototype(v8::Isolate* isolate, + v8::Local prototype); + + protected: + explicit SystemPreferences(v8::Isolate* isolate); + ~SystemPreferences() override; + + private: + DISALLOW_COPY_AND_ASSIGN(SystemPreferences); +}; + +} // namespace api + +} // namespace atom + +#endif // ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_ diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm new file mode 100644 index 00000000000..337d0f87ffc --- /dev/null +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -0,0 +1,15 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/api/atom_api_system_preferences.h" + +namespace atom { + +namespace api { + + + +} // namespace api + +} // namespace atom diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index 86fb3a6d03a..31105886eb7 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -44,6 +44,7 @@ REFERENCE_MODULE(atom_browser_power_save_blocker); REFERENCE_MODULE(atom_browser_protocol); REFERENCE_MODULE(atom_browser_global_shortcut); REFERENCE_MODULE(atom_browser_session); +REFERENCE_MODULE(atom_browser_system_preferences); REFERENCE_MODULE(atom_browser_tray); REFERENCE_MODULE(atom_browser_web_contents); REFERENCE_MODULE(atom_browser_web_view_manager); diff --git a/filenames.gypi b/filenames.gypi index a1c704c348b..c3eca34528d 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -28,6 +28,7 @@ 'lib/browser/api/protocol.js', 'lib/browser/api/session.js', 'lib/browser/api/screen.js', + 'lib/browser/api/system-preferences.js', 'lib/browser/api/tray.js', 'lib/browser/api/web-contents.js', 'lib/browser/chrome-extension.js', @@ -115,6 +116,9 @@ 'atom/browser/api/atom_api_screen.h', 'atom/browser/api/atom_api_session.cc', 'atom/browser/api/atom_api_session.h', + 'atom/browser/api/atom_api_system_preferences.cc', + 'atom/browser/api/atom_api_system_preferences.h', + 'atom/browser/api/atom_api_system_preferences_mac.mm', 'atom/browser/api/atom_api_tray.cc', 'atom/browser/api/atom_api_tray.h', 'atom/browser/api/atom_api_web_contents.cc', diff --git a/lib/browser/api/exports/electron.js b/lib/browser/api/exports/electron.js index bd8285401c7..9d873663029 100644 --- a/lib/browser/api/exports/electron.js +++ b/lib/browser/api/exports/electron.js @@ -89,6 +89,12 @@ Object.defineProperties(exports, { return require('../session') } }, + systemPreferences: { + enumerable: true, + get: function () { + return require('../system-preferences') + } + }, Tray: { enumerable: true, get: function () { diff --git a/lib/browser/api/system-preferences.js b/lib/browser/api/system-preferences.js new file mode 100644 index 00000000000..6ba1750507c --- /dev/null +++ b/lib/browser/api/system-preferences.js @@ -0,0 +1,6 @@ +const {EventEmitter} = require('events') +const {systemPreferences} = process.atomBinding('system_preferences') + +Object.setPrototypeOf(systemPreferences, EventEmitter.prototype) + +module.exports = systemPreferences From d72a0e452f6fdbc8cf080e94c2b973519ba5b057 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 12:24:11 +0900 Subject: [PATCH 0596/1265] BuildPrototype should not be empty --- atom/browser/api/atom_api_power_monitor.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/atom/browser/api/atom_api_power_monitor.cc b/atom/browser/api/atom_api_power_monitor.cc index 15220c117c5..32c50c696c7 100644 --- a/atom/browser/api/atom_api_power_monitor.cc +++ b/atom/browser/api/atom_api_power_monitor.cc @@ -53,6 +53,7 @@ v8::Local PowerMonitor::Create(v8::Isolate* isolate) { // static void PowerMonitor::BuildPrototype( v8::Isolate* isolate, v8::Local prototype) { + mate::ObjectTemplateBuilder(isolate, prototype); } } // namespace api From ddd8eae661cbb912ee19fa2ffa223596219cfc6a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 12:35:09 +0900 Subject: [PATCH 0597/1265] Move isAeroGlassEnabled and isDarkMode to systemPreferences --- atom/browser/api/atom_api_app.cc | 10 --------- atom/browser/api/atom_api_app.h | 4 ---- .../api/atom_api_system_preferences.cc | 22 ++++++++++++++++++- .../browser/api/atom_api_system_preferences.h | 5 +++++ .../api/atom_api_system_preferences_mac.mm | 10 ++++++++- atom/browser/browser.h | 3 --- atom/browser/browser_mac.mm | 5 ----- lib/browser/api/app.js | 22 +++++++++---------- 8 files changed, 46 insertions(+), 35 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index b35589ecad3..683ce452020 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -41,7 +41,6 @@ #if defined(OS_WIN) #include "base/strings/utf_string_conversions.h" -#include "ui/base/win/shell.h" #endif using atom::Browser; @@ -382,12 +381,6 @@ std::string App::GetLocale() { return l10n_util::GetApplicationLocale(""); } -#if defined(OS_WIN) -bool App::IsAeroGlassEnabled() { - return ui::win::IsAeroGlassEnabled(); -} -#endif - bool App::MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback) { if (process_singleton_.get()) @@ -471,13 +464,10 @@ void App::BuildPrototype( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) - .SetMethod("isDarkMode", - base::Bind(&Browser::IsDarkMode, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser)) - .SetMethod("isAeroGlassEnabled", &App::IsAeroGlassEnabled) #endif .SetMethod("setPath", &App::SetPath) .SetMethod("getPath", &App::GetPath) diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 354ea38d884..6a13d4013b6 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -114,10 +114,6 @@ class App : public AtomBrowserClient::Delegate, const net::CompletionCallback& callback); #endif -#if defined(OS_WIN) - bool IsAeroGlassEnabled(); -#endif - scoped_ptr process_singleton_; #if defined(USE_NSS_CERTS) diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 53aaabd1732..6e4774c196e 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -7,6 +7,10 @@ #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" +#if defined(OS_WIN) +#include "ui/base/win/shell.h" +#endif + namespace atom { namespace api { @@ -18,6 +22,18 @@ SystemPreferences::SystemPreferences(v8::Isolate* isolate) { SystemPreferences::~SystemPreferences() { } +#if defined(OS_WIN) +bool SystemPreferences::IsAeroGlassEnabled() { + return ui::win::IsAeroGlassEnabled(); +} +#endif + +#if !defined(OS_MACOSX) +bool SystemPreferences::IsDarkMode() { + return false; +} +#endif + // static mate::Handle SystemPreferences::Create( v8::Isolate* isolate) { @@ -27,7 +43,11 @@ mate::Handle SystemPreferences::Create( // static void SystemPreferences::BuildPrototype( v8::Isolate* isolate, v8::Local prototype) { - mate::ObjectTemplateBuilder(isolate, prototype); + mate::ObjectTemplateBuilder(isolate, prototype) +#if defined(OS_WIN) + .SetMethod("isAeroGlassEnabled", &SystemPreferences::IsAeroGlassEnabled) +#endif + .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); } } // namespace api diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 22c68b2e873..99390451120 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -19,6 +19,11 @@ class SystemPreferences : public mate::EventEmitter { static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); +#if defined(OS_WIN) + bool IsAeroGlassEnabled(); +#endif + bool IsDarkMode(); + protected: explicit SystemPreferences(v8::Isolate* isolate); ~SystemPreferences() override; diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index 337d0f87ffc..8935ab560ec 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -4,11 +4,19 @@ #include "atom/browser/api/atom_api_system_preferences.h" +#import + namespace atom { namespace api { - +#if defined(OS_MACOSX) +bool SystemPreferences::IsDarkMode() { + NSString* mode = [[NSUserDefaults standardUserDefaults] + stringForKey:@"AppleInterfaceStyle"]; + return [mode isEqualToString:@"Dark"]; +} +#endif } // namespace api diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 67aae152c31..366031b5679 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -89,9 +89,6 @@ class Browser : public WindowListObserver { // Show the application. void Show(); - // Check if the system is in Dark Mode. - bool IsDarkMode(); - // Bounce the dock icon. enum BounceType { BOUNCE_CRITICAL = 0, diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 0294894fcd6..11fd3aa6d35 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -27,11 +27,6 @@ void Browser::Show() { [[AtomApplication sharedApplication] unhide:nil]; } -bool Browser::IsDarkMode() { - NSString *mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; - return [mode isEqualToString: @"Dark"]; -} - void Browser::AddRecentDocument(const base::FilePath& path) { NSString* path_string = base::mac::FilePathToNSString(path); if (!path_string) diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index 48a27cfc648..413719a0033 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -1,8 +1,7 @@ 'use strict' -const deprecate = require('electron').deprecate -const session = require('electron').session -const Menu = require('electron').Menu +const electron = require('electron') +const {deprecate, session, Menu} = electron const EventEmitter = require('events').EventEmitter const bindings = process.atomBinding('app') @@ -65,39 +64,40 @@ for (i = 0, len = ref1.length; i < len; i++) { } // Deprecated. - app.getHomeDir = deprecate('app.getHomeDir', 'app.getPath', function () { return this.getPath('home') }) - app.getDataPath = deprecate('app.getDataPath', 'app.getPath', function () { return this.getPath('userData') }) - app.setDataPath = deprecate('app.setDataPath', 'app.setPath', function (path) { return this.setPath('userData', path) }) - app.resolveProxy = deprecate('app.resolveProxy', 'session.defaultSession.resolveProxy', function (url, callback) { return session.defaultSession.resolveProxy(url, callback) }) - deprecate.rename(app, 'terminate', 'quit') - deprecate.event(app, 'finish-launching', 'ready', function () { // give default app a chance to setup default menu. setImmediate(() => { this.emit('finish-launching') }) }) - deprecate.event(app, 'activate-with-no-open-windows', 'activate', function (event, hasVisibleWindows) { if (!hasVisibleWindows) { return this.emit('activate-with-no-open-windows', event) } }) - deprecate.event(app, 'select-certificate', 'select-client-certificate') +if (process.platform === 'win32') { + app.isAeroGlassEnabled = deprecate('app.isAeroGlassEnabled', 'systemPreferences.isAeroGlassEnabled', function () { + return electron.systemPreferences.isAeroGlassEnabled(); + }) +} else if (process.platform === 'darwin') { + app.isDarkMode = deprecate('app.isDarkMode', 'systemPreferences.isDarkMode', function () { + return electron.systemPreferences.isDarkMode(); + }) +} // Wrappers for native classes. var wrapDownloadItem = function (downloadItem) { From 955722622379930fc891372862f35390a0e16ee0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 14:25:14 +0900 Subject: [PATCH 0598/1265] Add systemPreferences.subscribeNotification --- .../api/atom_api_system_preferences.cc | 6 +++ .../browser/api/atom_api_system_preferences.h | 7 ++++ .../api/atom_api_system_preferences_mac.mm | 39 ++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 6e4774c196e..86d3484b670 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -4,6 +4,7 @@ #include "atom/browser/api/atom_api_system_preferences.h" +#include "atom/common/native_mate_converters/callback.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" @@ -46,6 +47,11 @@ void SystemPreferences::BuildPrototype( mate::ObjectTemplateBuilder(isolate, prototype) #if defined(OS_WIN) .SetMethod("isAeroGlassEnabled", &SystemPreferences::IsAeroGlassEnabled) +#elif defined(OS_MACOSX) + .SetMethod("subscribeNotification", + &SystemPreferences::SubscribeNotification) + .SetMethod("unsubscribeNotification", + &SystemPreferences::UnsubscribeNotification) #endif .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); } diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 99390451120..6fd7ca922dc 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -5,7 +5,10 @@ #ifndef ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_ #define ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_ +#include + #include "atom/browser/api/event_emitter.h" +#include "base/callback.h" #include "native_mate/handle.h" namespace atom { @@ -21,6 +24,10 @@ class SystemPreferences : public mate::EventEmitter { #if defined(OS_WIN) bool IsAeroGlassEnabled(); +#elif defined(OS_MACOSX) + int SubscribeNotification(const std::string& name, + const base::Closure& callback); + void UnsubscribeNotification(int id); #endif bool IsDarkMode(); diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index 8935ab560ec..39eb7e6ede8 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -4,19 +4,54 @@ #include "atom/browser/api/atom_api_system_preferences.h" +#include + #import +#include "base/strings/sys_string_conversions.h" + namespace atom { namespace api { -#if defined(OS_MACOSX) +namespace { + +int g_next_id = 0; + +// The map to convert |id| to |int|. +std::map g_id_map; + +} // namespace + +int SystemPreferences::SubscribeNotification(const std::string& name, + const base::Closure& callback) { + int request_id = g_next_id++; + __block base::Closure copied_callback = callback; + g_id_map[request_id] = [[NSDistributedNotificationCenter defaultCenter] + addObserverForName:base::SysUTF8ToNSString(name) + object:nil + queue:nil + usingBlock:^(NSNotification* notification) { + copied_callback.Run(); + } + ]; + return request_id; +} + +void SystemPreferences::UnsubscribeNotification(int request_id) { + auto iter = g_id_map.find(request_id); + if (iter != g_id_map.end()) { + id observer = iter->second; + [[NSDistributedNotificationCenter defaultCenter] removeObserver:observer]; + g_id_map.erase(iter); + } +} + bool SystemPreferences::IsDarkMode() { NSString* mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; return [mode isEqualToString:@"Dark"]; } -#endif } // namespace api From a421c66f3fd194524c751a2ef77c194c9a0ef37e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 14:34:30 +0900 Subject: [PATCH 0599/1265] Deprecate the platform-theme-changed event --- atom/browser/api/atom_api_app.cc | 6 ------ atom/browser/api/atom_api_app.h | 4 ---- atom/browser/browser.cc | 4 ---- atom/browser/browser.h | 3 --- atom/browser/browser_observer.h | 2 -- atom/browser/mac/atom_application_delegate.mm | 7 ------- lib/browser/api/app.js | 13 +++++++++++-- 7 files changed, 11 insertions(+), 28 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 683ce452020..ce20ce96ded 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -331,12 +331,6 @@ void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) { Emit("gpu-process-crashed"); } -#if defined(OS_MACOSX) -void App::OnPlatformThemeChanged() { - Emit("platform-theme-changed"); -} -#endif - base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) { bool succeed = false; base::FilePath path; diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 6a13d4013b6..c99d5df7793 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -92,10 +92,6 @@ class App : public AtomBrowserClient::Delegate, // content::GpuDataManagerObserver: void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; -#if defined(OS_MACOSX) - void OnPlatformThemeChanged() override; -#endif - private: // Get/Set the pre-defined path in PathService. base::FilePath GetPath(mate::Arguments* args, const std::string& name); diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index b60df0dd44a..b3c7a59e08b 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -187,8 +187,4 @@ void Browser::OnWindowAllClosed() { FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed()); } -void Browser::PlatformThemeChanged() { - FOR_EACH_OBSERVER(BrowserObserver, observers_, OnPlatformThemeChanged()); -} - } // namespace atom diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 366031b5679..0f1dbe99311 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -148,9 +148,6 @@ class Browser : public WindowListObserver { // Request basic auth login. void RequestLogin(LoginHandler* login_handler); - // Tell the application that plaform's theme changed. - void PlatformThemeChanged(); - void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); } diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index da327eb90a0..f6d76bc13fb 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -45,8 +45,6 @@ class BrowserObserver { // The browser requests HTTP login. virtual void OnLogin(LoginHandler* login_handler) {} - virtual void OnPlatformThemeChanged() {} - protected: virtual ~BrowserObserver() {} }; diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index f4db929bf57..7662162ab61 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -24,9 +24,6 @@ // Don't add the "Enter Full Screen" menu item automatically. [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"]; - // Add observer to monitor the system's Dark Mode theme. - [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(platformThemeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; - atom::Browser::Get()->WillFinishLaunching(); } @@ -62,8 +59,4 @@ return flag; } -- (void)platformThemeChanged:(NSNotification *)notify { - atom::Browser::Get()->PlatformThemeChanged(); -} - @end diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index 413719a0033..0487270ce7b 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -91,12 +91,21 @@ deprecate.event(app, 'activate-with-no-open-windows', 'activate', function (even deprecate.event(app, 'select-certificate', 'select-client-certificate') if (process.platform === 'win32') { app.isAeroGlassEnabled = deprecate('app.isAeroGlassEnabled', 'systemPreferences.isAeroGlassEnabled', function () { - return electron.systemPreferences.isAeroGlassEnabled(); + return electron.systemPreferences.isAeroGlassEnabled() }) } else if (process.platform === 'darwin') { app.isDarkMode = deprecate('app.isDarkMode', 'systemPreferences.isDarkMode', function () { - return electron.systemPreferences.isDarkMode(); + return electron.systemPreferences.isDarkMode() }) + app.on = app.addListener = function (event, listener) { + if (event === 'platform-theme-changed') { + deprecate.warn('platform-theme-changed event', "systemPreferences.subscribeNotification('AppleInterfaceThemeChangedNotification', callback)") + electron.systemPreferences.subscribeNotification('AppleInterfaceThemeChangedNotification', function () { + app.emit('platform-theme-changed') + }) + } + EventEmitter.prototype.addListener.call(app, event, listener) + } } // Wrappers for native classes. From 067e9c1a850f077943c66a604085c9b38861bcc4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 15:35:52 +0900 Subject: [PATCH 0600/1265] Add systemPreferences.getUserDefault --- .../api/atom_api_system_preferences.cc | 1 + .../browser/api/atom_api_system_preferences.h | 2 ++ .../api/atom_api_system_preferences_mac.mm | 25 +++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 86d3484b670..b8c665456ad 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -52,6 +52,7 @@ void SystemPreferences::BuildPrototype( &SystemPreferences::SubscribeNotification) .SetMethod("unsubscribeNotification", &SystemPreferences::UnsubscribeNotification) + .SetMethod("getUserDefault", &SystemPreferences::GetUserDefault) #endif .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); } diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 6fd7ca922dc..fed1c52247b 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -28,6 +28,8 @@ class SystemPreferences : public mate::EventEmitter { int SubscribeNotification(const std::string& name, const base::Closure& callback); void UnsubscribeNotification(int id); + v8::Local GetUserDefault(const std::string& name, + const std::string& type); #endif bool IsDarkMode(); diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index 39eb7e6ede8..2d12b278ae9 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -8,7 +8,9 @@ #import +#include "atom/common/native_mate_converters/gurl_converter.h" #include "base/strings/sys_string_conversions.h" +#include "net/base/mac/url_conversions.h" namespace atom { @@ -47,6 +49,29 @@ void SystemPreferences::UnsubscribeNotification(int request_id) { } } +v8::Local SystemPreferences::GetUserDefault( + const std::string& name, const std::string& type) { + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSString* key = base::SysUTF8ToNSString(name); + if (type == "string") { + return mate::StringToV8( + isolate(), base::SysNSStringToUTF8([defaults stringForKey:key])); + } else if (type == "boolean") { + return v8::Boolean::New(isolate(), [defaults boolForKey:key]); + } else if (type == "float") { + return v8::Number::New(isolate(), [defaults floatForKey:key]); + } else if (type == "integer") { + return v8::Integer::New(isolate(), [defaults integerForKey:key]); + } else if (type == "double") { + return v8::Number::New(isolate(), [defaults doubleForKey:key]); + } else if (type == "url") { + return mate::ConvertToV8( + isolate(), net::GURLWithNSURL([defaults URLForKey:key])); + } else { + return v8::Undefined(isolate()); + } +} + bool SystemPreferences::IsDarkMode() { NSString* mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; From 11653aa9c8de7ede345fe7bb66195652af47b133 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 15:36:38 +0900 Subject: [PATCH 0601/1265] docs: systemPreferences --- docs/README.md | 1 + docs/api/app.md | 34 --------------- docs/api/system-preferences.md | 79 ++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 34 deletions(-) create mode 100644 docs/api/system-preferences.md diff --git a/docs/README.md b/docs/README.md index 428d2f8bd7b..c8bd425d975 100644 --- a/docs/README.md +++ b/docs/README.md @@ -62,6 +62,7 @@ an issue: * [powerSaveBlocker](api/power-save-blocker.md) * [protocol](api/protocol.md) * [session](api/session.md) +* [systemPreferences](api/system-preferences.md) * [webContents](api/web-contents.md) * [Tray](api/tray.md) diff --git a/docs/api/app.md b/docs/api/app.md index 8a2cdcfd922..dbe65d0864f 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -480,40 +480,6 @@ app.on('ready', function() { Changes the [Application User Model ID][app-user-model-id] to `id`. -### `app.isAeroGlassEnabled()` _Windows_ - -This method returns `true` if [DWM composition](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx) -(Aero Glass) is enabled, and `false` otherwise. You can use it to determine if -you should create a transparent window or not (transparent windows won't work -correctly when DWM composition is disabled). - -Usage example: - -```javascript -let browserOptions = {width: 1000, height: 800}; - -// Make the window transparent only if the platform supports it. -if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { - browserOptions.transparent = true; - browserOptions.frame = false; -} - -// Create the window. -win = new BrowserWindow(browserOptions); - -// Navigate. -if (browserOptions.transparent) { - win.loadURL('file://' + __dirname + '/index.html'); -} else { - // No transparency, so we load a fallback that uses basic styles. - win.loadURL('file://' + __dirname + '/fallback.html'); -} -``` - -### `app.isDarkMode()` _OS X_ - -This method returns `true` if the system is in Dark Mode, and `false` otherwise. - ### `app.importCertificate(options, callback)` _LINUX_ * `options` Object diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md new file mode 100644 index 00000000000..8fdd2b54cb0 --- /dev/null +++ b/docs/api/system-preferences.md @@ -0,0 +1,79 @@ +# systemPreferences + +> Get system preferences. + +## Methods + +### `systemPreferences.isDarkMode()` _OS X_ + +This method returns `true` if the system is in Dark Mode, and `false` otherwise. + +### `systemPreferences.subscribeNotification(event, callback)` _OS X_ + +* `event` String +* `callback` Function + +Subscribes to native notifications of OS X, `callback` will be called when the +corresponding `event` happens. The `id` of the subscriber is returned, which can +be used to unsubscribe the `event`. + +Under the hood this API subscribes to `NSDistributedNotificationCenter`, +possible values of `event` are: + +* `AppleInterfaceThemeChangedNotification` +* `AppleAquaColorVariantChanged` +* `AppleColorPreferencesChangedNotification` +* `AppleShowScrollBarsSettingChanged` + +### `systemPreferences.unsubscribeNotification(id)` _OS X_ + +* `id` Integer + +Removes the subscriber with `id`. + +### `systemPreferences.getUserDefault(key, type)` _OS X_ + +* `key` String +* `type` String - Can be `string`, `boolean`, `integer`, `float`, `double`, + `url`. + +Get the value of `key` in system preferences. + +This API reads from `NSUserDefaults` on OS X, some popular `key` and `type`s +are: + +* `AppleInterfaceStyle: string` +* `AppleAquaColorVariant: integer` +* `AppleHighlightColor: string` +* `AppleShowScrollBars: string` + +### `systemPreferences.isAeroGlassEnabled()` _Windows_ + +This method returns `true` if [DWM composition][dwm-composition] (Aero Glass) is +enabled, and `false` otherwise. + +An example of using it to determine if you should create a transparent window or +not (transparent windows won't work correctly when DWM composition is disabled): + +```javascript +let browserOptions = {width: 1000, height: 800}; + +// Make the window transparent only if the platform supports it. +if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { + browserOptions.transparent = true; + browserOptions.frame = false; +} + +// Create the window. +let win = new BrowserWindow(browserOptions); + +// Navigate. +if (browserOptions.transparent) { + win.loadURL('file://' + __dirname + '/index.html'); +} else { + // No transparency, so we load a fallback that uses basic styles. + win.loadURL('file://' + __dirname + '/fallback.html'); +} +``` + +[dwm-composition]:https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx From b5d2e51100f71adbe5d613f599f7d217a8aed7fc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 25 Apr 2016 22:27:44 +0900 Subject: [PATCH 0602/1265] docs: platform-theme-changed is deprecated --- docs/api/app.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index dbe65d0864f..0aca703ba51 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -228,10 +228,6 @@ app.on('login', function(event, webContents, request, authInfo, callback) { Emitted when the gpu process crashes. -### Event: 'platform-theme-changed' _OS X_ - -Emitted when the system's Dark Mode theme is toggled. - ## Methods The `app` object has the following methods: From 62d00163a858fa078dff5a99a4aed5951500c5da Mon Sep 17 00:00:00 2001 From: michal1106 Date: Mon, 25 Apr 2016 16:45:56 +0300 Subject: [PATCH 0603/1265] Update using-pepper-flash-plugin.md --- docs/tutorial/using-pepper-flash-plugin.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/tutorial/using-pepper-flash-plugin.md b/docs/tutorial/using-pepper-flash-plugin.md index a9918b220ac..cdb4d04ad08 100644 --- a/docs/tutorial/using-pepper-flash-plugin.md +++ b/docs/tutorial/using-pepper-flash-plugin.md @@ -11,6 +11,9 @@ navigating to `chrome://plugins` in the Chrome browser. Its location and version are useful for Electron's Pepper Flash support. You can also copy it to another location. +_**Attention:** On windows, Pepper Flash plugin is win32 and it won't work with Electron x64 version. +
Get win32 version from [Electron Releases](https://github.com/electron/electron/releases)_ + ## Add Electron Switch You can directly add `--ppapi-flash-path` and `ppapi-flash-version` to the @@ -20,19 +23,20 @@ For example: ```javascript // Specify flash path. -// On Windows, it might be /path/to/pepflashplayer.dll +// On Windows, it might be /path/to/pepflashplayer.dll or just pepflashplayer.dll if it resides main.js // On OS X, /path/to/PepperFlashPlayer.plugin // On Linux, /path/to/libpepflashplayer.so app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'); -// Specify flash version, for example, v17.0.0.169 +// Optional: Specify flash version, for example, v17.0.0.169 app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169'); app.on('ready', function() { mainWindow = new BrowserWindow({ 'width': 800, 'height': 600, - 'web-preferences': { + // web-preferences is deprecated. Use webPreferences instead. + 'webPreferences': { 'plugins': true } }); @@ -41,6 +45,8 @@ app.on('ready', function() { }); ``` +_**Attention:** You can check if Flash dll was loaded by running `navigator.plugins` on the Console (although you can't know if the plugin's path is correct)_ + ## Enable Flash Plugin in a `` Tag Add `plugins` attribute to `` tag. From d02125bde5892dc6c696cf73de9f542b404186fb Mon Sep 17 00:00:00 2001 From: arifcakiroglu Date: Tue, 26 Apr 2016 00:49:34 +0300 Subject: [PATCH 0604/1265] Update README --- README.md | 1 + docs-translations/tr-TR/README.md | 86 ++++++++++++++++++++++++ docs-translations/tr-TR/styleguide.md | 95 +++++++++++++++++++++++++++ 3 files changed, 182 insertions(+) create mode 100644 docs-translations/tr-TR/README.md create mode 100644 docs-translations/tr-TR/styleguide.md diff --git a/README.md b/README.md index 52e290f53ef..f8278f18586 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ contains documents describing how to build and contribute to Electron. - [Spanish](https://github.com/electron/electron/tree/master/docs-translations/es) - [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN) - [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW) +- [Turkish](https://github.com/electron/electron/tree/master/docs-translations/tr-TR) - [Ukrainian](https://github.com/electron/electron/tree/master/docs-translations/uk-UA) - [Russian](https://github.com/electron/electron/tree/master/docs-translations/ru-RU) - [French](https://github.com/electron/electron/tree/master/docs-translations/fr-FR) diff --git a/docs-translations/tr-TR/README.md b/docs-translations/tr-TR/README.md new file mode 100644 index 00000000000..1d79da1d667 --- /dev/null +++ b/docs-translations/tr-TR/README.md @@ -0,0 +1,86 @@ +Lütfen kullandığınız dokümanın Electron versiyonunuzla aynı olduğundan emin olun. +Versiyon numarası okuduğunuz dokümanın URL'sindekiyle aynı olmalı. Eğer aynı değilse, muhtemelen geliştirme aşamasındaki API değişikliklerini içerebilecek dokümantasyonudur. +Eğer öyleyse, atom.io üzerinden [mevcut sürümler](http://electron.atom.io/docs/)e göz atabilirsiniz ya da eğer GitHub arayüzünü kullanıyorsanız "Switch branches/tags" açılır menüsünden versiyonunuza uygun olanı seçebilirsiniz. + +## SSS(Sıkça Sorulan Sorular) + +Bir problem(issue) bildirmeden önce sıkça sorulan sorulara göz atın: +* [Electron SSS](faq/electron-faq.md) + +## Klavuzlar + +* [Desteklenen Platformlar ](tutorial/supported-platforms.md) +* [Uygulama Dağıtımı](tutorial/application-distribution.md) +* [Mac Uygulama Mağazası Başvuru Klavuzu](tutorial/mac-app-store-submission-guide.md) +* [Uygulama Paketleme](tutorial/application-packaging.md) +* [Native Node Modüllerini Kullanma](tutorial/using-native-node-modules.md) +* [Ana Süreç(Main Process) Hata ayıklama](tutorial/debugging-main-process.md) +* [Selenium ve WebDriver kullanımı](tutorial/using-selenium-and-webdriver.md) +* [DevTools Eklentisi](tutorial/devtools-extension.md) +* [Pepper Flash Kullanımı](tutorial/using-pepper-flash-plugin.md) +* [Widevine CDM Kullanımı](tutorial/using-widevine-cdm-plugin.md) +* [CI Sistem Testleri (Travis, Jenkins)](tutorial/testing-on-headless-ci.md) + +## Eğitimler + +* [Quick Start](tutorial/quick-start.md) +* [Desktop Environment Integration](tutorial/desktop-environment-integration.md) +* [Online/Offline Event Detection](tutorial/online-offline-events.md) + +## API Kaynakları + +* [Synopsis](api/synopsis.md) +* [Process Object](api/process.md) +* [Desteklenen Chrome Komut Satırı Anahtarları](api/chrome-command-line-switches.md) +* [Environment Değişkenleri](api/environment-variables.md) + +### Özel DOM Elementleri: + +* [`File` Nesnesi](api/file-object.md) +* [`` Etiketi](api/web-view-tag.md) +* [`window.open` Fonksiyonu](api/window-open.md) + +### Ana Süreç(Main Process) Modülleri: + +* [app](api/app.md) +* [autoUpdater](api/auto-updater.md) +* [BrowserWindow](api/browser-window.md) +* [contentTracing](api/content-tracing.md) +* [dialog](api/dialog.md) +* [globalShortcut](api/global-shortcut.md) +* [ipcMain](api/ipc-main.md) +* [Menu](api/menu.md) +* [MenuItem](api/menu-item.md) +* [powerMonitor](api/power-monitor.md) +* [powerSaveBlocker](api/power-save-blocker.md) +* [protocol](api/protocol.md) +* [session](api/session.md) +* [webContents](api/web-contents.md) +* [Tray](api/tray.md) + +### Renderer Process Modülelri (Web Page): + +* [desktopCapturer](api/desktop-capturer.md) +* [ipcRenderer](api/ipc-renderer.md) +* [remote](api/remote.md) +* [webFrame](api/web-frame.md) + +### Her İki Süreç İçin Geçerli Modüller: + +* [clipboard](api/clipboard.md) +* [crashReporter](api/crash-reporter.md) +* [nativeImage](api/native-image.md) +* [screen](api/screen.md) +* [shell](api/shell.md) + +## Geliştirme + +* [Kodlama Stili](development/coding-style.md) +* [Kaynak Kod Dizin Yapısı](development/source-code-directory-structure.md) +* [NW.js(node-webkit adıyla bilinen) İle Arasındaki Teknik Farklılıklar](development/atom-shell-vs-node-webkit.md) +* [Build Sisyem Genel Bakış](development/build-system-overview.md) +* [(OS X) Build Komutları](development/build-instructions-osx.md) +* [(Windows) Build Komutları](development/build-instructions-windows.md) +* [(Linux) Build Komutları](development/build-instructions-linux.md) +* [(Windows) Hata Ayıklama Komutları](development/debug-instructions-windows.md) +* [Simge Sunucusu(Symbol Server) Hata Ayıklama Kurulumu](development/setting-up-symbol-server.md) diff --git a/docs-translations/tr-TR/styleguide.md b/docs-translations/tr-TR/styleguide.md new file mode 100644 index 00000000000..d264600f0d5 --- /dev/null +++ b/docs-translations/tr-TR/styleguide.md @@ -0,0 +1,95 @@ +# Electron Dokümantasyonu Stil Rehberi + +Size uygun bölümü bulun: [Electron Dokümantasyonunu okumak](#reading-electron-documentation) +ya da [Electron Dokümantasyonunu yazmak](#writing-electron-documentation). + +## Electron Dokümantasyonunu Yazmak + +Electron Dokümantasyonunu geliştirmek için aşağıdaki yöntemleri takip edin. + +- Her sayfada en fazla bir tane `h1` etiketi olmalıdır. +- Kod bloklarında `cmd` yerine `bash` kullanın.(syntax highlighter için). +- `h1` Başlığı nesne ismiyle eşleşmeli (ör. `browser-window` → + `BrowserWindow`). + - Hyphen separated filenames, however, are fine. +- No headers following headers, add at least a one-sentence description. +- Methods headers are wrapped in `code` ticks. +- Event headers are wrapped in single 'quotation' marks. +- No nesting lists more than 2 levels (unfortunately because of markdown + renderer). +- Add section titles: Events, Class Methods and Instance Methods. +- Use 'will' over 'would' when describing outcomes. +- Events and methods are `h3` headers. +- Optional arguments written as `function (required[, optional])`. +- Optional arguments are denoted when called out in list. +- 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' + +### Dokümantasyon Çevirisi + +Electron Dokümantasyonunun çevirileri `docs-translations` klasörü içerisindedir. + +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/electron/electron#documentation-translations). + +## Electron Dokümantasyonunu Okumak + +Electron Dokümantasyon sözdizimini(syntax) anlayabileceğiniz bir kaç ipucu: + +### Metodlar + +[Method](https://developer.mozilla.org/en-US/docs/Glossary/Method) dokümantasyonunun bir örneği: + +--- + +`methodName(required[, optional]))` + +* `require` String (**required**) +* `optional` Integer + +--- + +The method name is followed by the arguments it takes. Optional arguments are +notated by brackets surrounding the optional argument as well as the comma +required if this optional argument follows another argument. + +Below the method is more detailed information on each of the arguments. The type +of argument is notated by either the common types: +[`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), +[`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), +[`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), +[`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) +or a custom type like Electron's [`webContent`](api/web-content.md). + +### Events + +[event](https://developer.mozilla.org/en-US/docs/Web/API/Event) Dokümantasyonunun bir örneği: + +--- + +Event: 'wake-up' + +Returns: + +* `time` String + +--- + +The event is a string that is used after a `.on` listener method. If it returns +a value it and its type is noted below. If you were to listen and respond to +this event it might look something like this: + +```javascript +Alarm.on('wake-up', function(time) { + console.log(time) +}) +``` From 64db17dde73272c066ad82fc23d2878b2078799f Mon Sep 17 00:00:00 2001 From: arifcakiroglu Date: Tue, 26 Apr 2016 01:03:17 +0300 Subject: [PATCH 0605/1265] Added Turkish Docs link to README-ko --- README-ko.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README-ko.md b/README-ko.md index a3dd38124fa..706a5556df9 100644 --- a/README-ko.md +++ b/README-ko.md @@ -56,6 +56,7 @@ npm install electron-prebuilt --save-dev - [스페인어](https://github.com/electron/electron/tree/master/docs-translations/es) - [중국어 간체](https://github.com/electron/electron/tree/master/docs-translations/zh-CN) - [중국어 번체](https://github.com/electron/electron/tree/master/docs-translations/zh-TW) +- [터키의](https://github.com/electron/electron/tree/master/docs-translations/tr-TR) - [우크라이나어](https://github.com/electron/electron/tree/master/docs-translations/uk-UA) - [러시아어](https://github.com/electron/electron/tree/master/docs-translations/ru-RU) - [프랑스어](https://github.com/electron/electron/tree/master/docs-translations/fr-FR) From a0c14eed046f9a4c4813be28da4512ccdc49687a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 10:24:43 +0900 Subject: [PATCH 0606/1265] Revise the using-pepper-flash-plugin.md --- docs/tutorial/using-pepper-flash-plugin.md | 28 ++++++++++++---------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/tutorial/using-pepper-flash-plugin.md b/docs/tutorial/using-pepper-flash-plugin.md index cdb4d04ad08..de7c7001cf3 100644 --- a/docs/tutorial/using-pepper-flash-plugin.md +++ b/docs/tutorial/using-pepper-flash-plugin.md @@ -1,6 +1,6 @@ # Using Pepper Flash Plugin -Electron now supports the Pepper Flash plugin. To use the Pepper Flash plugin in +Electron supports the Pepper Flash plugin. To use the Pepper Flash plugin in Electron, you should manually specify the location of the Pepper Flash plugin and then enable it in your application. @@ -11,14 +11,11 @@ navigating to `chrome://plugins` in the Chrome browser. Its location and version are useful for Electron's Pepper Flash support. You can also copy it to another location. -_**Attention:** On windows, Pepper Flash plugin is win32 and it won't work with Electron x64 version. -
Get win32 version from [Electron Releases](https://github.com/electron/electron/releases)_ - ## Add Electron Switch You can directly add `--ppapi-flash-path` and `ppapi-flash-version` to the Electron command line or by using the `app.commandLine.appendSwitch` method -before the app ready event. Also, add the `plugins` switch of `browser-window`. +before the app ready event. Also, turn on `plugins` option of `BrowserWindow`. For example: ```javascript @@ -33,11 +30,10 @@ app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169'); app.on('ready', function() { mainWindow = new BrowserWindow({ - 'width': 800, - 'height': 600, - // web-preferences is deprecated. Use webPreferences instead. - 'webPreferences': { - 'plugins': true + width: 800, + height: 600, + webPreferences: { + plugins: true } }); mainWindow.loadURL('file://' + __dirname + '/index.html'); @@ -45,8 +41,6 @@ app.on('ready', function() { }); ``` -_**Attention:** You can check if Flash dll was loaded by running `navigator.plugins` on the Console (although you can't know if the plugin's path is correct)_ - ## Enable Flash Plugin in a `` Tag Add `plugins` attribute to `` tag. @@ -54,3 +48,13 @@ Add `plugins` attribute to `` tag. ```html ``` + +## Troubleshooting + +You can check if Pepper Flash plugin was loaded by inspecting +`navigator.plugins` in the console of devtools (although you can't know if the +plugin's path is correct). + +The architecture of Pepper Flash plugin has to match Electron's one. On Windows, +a common error is to use 32bit version of Flash plugin against 64bit version of +Electron. From 315cd9d2c89c6ad68f50e070a1110a5b28ea88a0 Mon Sep 17 00:00:00 2001 From: Samuel Attard Date: Tue, 26 Apr 2016 01:35:34 +1000 Subject: [PATCH 0607/1265] Emit an error if `quitAndInstall` is called without an update being available --- atom/browser/auto_updater_mac.mm | 21 +++++++++++++++---- .../api/auto-updater/auto-updater-win.js | 5 +++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/atom/browser/auto_updater_mac.mm b/atom/browser/auto_updater_mac.mm index a55cdd28126..5f9814fd347 100644 --- a/atom/browser/auto_updater_mac.mm +++ b/atom/browser/auto_updater_mac.mm @@ -22,6 +22,12 @@ SQRLUpdater* g_updater = nil; } // namespace +namespace { + +bool g_update_available = false; + +} + // static void AutoUpdater::SetFeedURL(const std::string& feed) { if (g_updater == nil) { @@ -69,6 +75,7 @@ void AutoUpdater::CheckForUpdates() { take:1] subscribeNext:^(SQRLDownloadedUpdate *downloadedUpdate) { if (downloadedUpdate) { + g_update_available = true; SQRLUpdate* update = downloadedUpdate.update; // There is a new update that has been downloaded. delegate->OnUpdateDownloaded( @@ -77,6 +84,7 @@ void AutoUpdater::CheckForUpdates() { base::Time::FromDoubleT(update.releaseDate.timeIntervalSince1970), base::SysNSStringToUTF8(update.updateURL.absoluteString)); } else { + g_update_available = false; // When the completed event is sent with no update, then we know there // is no update available. delegate->OnUpdateNotAvailable(); @@ -89,11 +97,16 @@ void AutoUpdater::CheckForUpdates() { } void AutoUpdater::QuitAndInstall() { - [[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) { - Delegate* delegate = AutoUpdater::GetDelegate(); + if (g_update_available) { + [[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) { + Delegate* delegate = AutoUpdater::GetDelegate(); + if (delegate) + delegate->OnError(base::SysNSStringToUTF8(error.localizedDescription)); + }]; + } else { if (delegate) - delegate->OnError(base::SysNSStringToUTF8(error.localizedDescription)); - }]; + delegate->OnError("No update available, can't quit and install"); + } } } // namespace auto_updater diff --git a/lib/browser/api/auto-updater/auto-updater-win.js b/lib/browser/api/auto-updater/auto-updater-win.js index 896b9ffce9d..5b1127027e9 100644 --- a/lib/browser/api/auto-updater/auto-updater-win.js +++ b/lib/browser/api/auto-updater/auto-updater-win.js @@ -12,6 +12,9 @@ function AutoUpdater () { util.inherits(AutoUpdater, EventEmitter) AutoUpdater.prototype.quitAndInstall = function () { + if (!this.updateAvailable) { + return this.emitError('No update available, can\'t quit and install') + } squirrelUpdate.processStart() return app.quit() } @@ -33,8 +36,10 @@ AutoUpdater.prototype.checkForUpdates = function () { return this.emitError(error) } if (update == null) { + this.updateAvailable = false return this.emit('update-not-available') } + this.updateAvailable = true this.emit('update-available') squirrelUpdate.update(this.updateURL, (error) => { var date, releaseNotes, version From f081c77422fff1eddc6901a73519e6426686facf Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 11:15:36 +0900 Subject: [PATCH 0608/1265] Fix compilation error --- atom/browser/auto_updater_mac.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/auto_updater_mac.mm b/atom/browser/auto_updater_mac.mm index 5f9814fd347..9af920f5929 100644 --- a/atom/browser/auto_updater_mac.mm +++ b/atom/browser/auto_updater_mac.mm @@ -97,9 +97,9 @@ void AutoUpdater::CheckForUpdates() { } void AutoUpdater::QuitAndInstall() { + Delegate* delegate = AutoUpdater::GetDelegate(); if (g_update_available) { [[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) { - Delegate* delegate = AutoUpdater::GetDelegate(); if (delegate) delegate->OnError(base::SysNSStringToUTF8(error.localizedDescription)); }]; From 06cf0406fe8ddcef3a500a689952c77fdfb9c9a8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 16:10:27 +0900 Subject: [PATCH 0609/1265] Dereference remote objects with native code Previously we rely on the v8util.setDestructor to dereference the remote objects in JavaScript, however as documented in V8, it is forbidden to call V8 APIs in object's destructor (e.g. the weak callback), and doing so would result in crashs. This commit removes the JavaScript setDestructor method, and avoids doing the dereference work with V8. --- atom/common/api/atom_api_v8_util.cc | 13 ++-- atom/common/api/object_life_monitor.cc | 29 +++----- atom/common/api/object_life_monitor.h | 16 ++--- atom/common/api/remote_callback_freer.cc | 70 +++++++++++++++++++ atom/common/api/remote_callback_freer.h | 44 ++++++++++++ atom/common/api/remote_object_freer.cc | 63 +++++++++++++++++ atom/common/api/remote_object_freer.h | 32 +++++++++ .../content_converter.cc | 13 ++++ .../content_converter.h | 2 + filenames.gypi | 4 ++ lib/browser/rpc-server.js | 43 +++++++----- lib/renderer/api/remote.js | 4 +- 12 files changed, 272 insertions(+), 61 deletions(-) create mode 100644 atom/common/api/remote_callback_freer.cc create mode 100644 atom/common/api/remote_callback_freer.h create mode 100644 atom/common/api/remote_object_freer.cc create mode 100644 atom/common/api/remote_object_freer.h diff --git a/atom/common/api/atom_api_v8_util.cc b/atom/common/api/atom_api_v8_util.cc index 0ebd939398f..109f9f0f36c 100644 --- a/atom/common/api/atom_api_v8_util.cc +++ b/atom/common/api/atom_api_v8_util.cc @@ -4,7 +4,9 @@ #include -#include "atom/common/api/object_life_monitor.h" +#include "atom/common/api/remote_callback_freer.h" +#include "atom/common/api/remote_object_freer.h" +#include "atom/common/native_mate_converters/content_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #include "v8/include/v8-profiler.h" @@ -51,12 +53,6 @@ int32_t GetObjectHash(v8::Local object) { return object->GetIdentityHash(); } -void SetDestructor(v8::Isolate* isolate, - v8::Local object, - v8::Local callback) { - atom::ObjectLifeMonitor::BindTo(isolate, object, callback); -} - void TakeHeapSnapshot(v8::Isolate* isolate) { isolate->GetHeapProfiler()->TakeHeapSnapshot(); } @@ -68,8 +64,9 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("setHiddenValue", &SetHiddenValue); dict.SetMethod("deleteHiddenValue", &DeleteHiddenValue); dict.SetMethod("getObjectHash", &GetObjectHash); - dict.SetMethod("setDestructor", &SetDestructor); dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot); + dict.SetMethod("setRemoteCallbackFreer", &atom::RemoteCallbackFreer::BindTo); + dict.SetMethod("setRemoteObjectFreer", &atom::RemoteObjectFreer::BindTo); } } // namespace diff --git a/atom/common/api/object_life_monitor.cc b/atom/common/api/object_life_monitor.cc index 916ad8a5177..ffcc0d71842 100644 --- a/atom/common/api/object_life_monitor.cc +++ b/atom/common/api/object_life_monitor.cc @@ -10,30 +10,28 @@ namespace atom { -// static -void ObjectLifeMonitor::BindTo(v8::Isolate* isolate, - v8::Local target, - v8::Local destructor) { - new ObjectLifeMonitor(isolate, target, destructor); -} - ObjectLifeMonitor::ObjectLifeMonitor(v8::Isolate* isolate, - v8::Local target, - v8::Local destructor) + v8::Local target) : isolate_(isolate), context_(isolate, isolate->GetCurrentContext()), target_(isolate, target), - destructor_(isolate, destructor), weak_ptr_factory_(this) { target_.SetWeak(this, OnObjectGC, v8::WeakCallbackType::kParameter); } +ObjectLifeMonitor::~ObjectLifeMonitor() { + if (target_.IsEmpty()) + return; + target_.ClearWeak(); + target_.Reset(); +} + // static void ObjectLifeMonitor::OnObjectGC( const v8::WeakCallbackInfo& data) { ObjectLifeMonitor* self = data.GetParameter(); self->target_.Reset(); - self->RunCallback(); + self->RunDestructor(); data.SetSecondPassCallback(Free); } @@ -43,13 +41,4 @@ void ObjectLifeMonitor::Free( delete data.GetParameter(); } -void ObjectLifeMonitor::RunCallback() { - v8::HandleScope handle_scope(isolate_); - v8::Local context = v8::Local::New( - isolate_, context_); - v8::Context::Scope context_scope(context); - v8::Local::New(isolate_, destructor_)->Call( - context->Global(), 0, nullptr); -} - } // namespace atom diff --git a/atom/common/api/object_life_monitor.h b/atom/common/api/object_life_monitor.h index 82d923fcedb..59d5fdb5cff 100644 --- a/atom/common/api/object_life_monitor.h +++ b/atom/common/api/object_life_monitor.h @@ -12,25 +12,19 @@ namespace atom { class ObjectLifeMonitor { - public: - static void BindTo(v8::Isolate* isolate, - v8::Local target, - v8::Local destructor); + protected: + ObjectLifeMonitor(v8::Isolate* isolate, v8::Local target); + virtual ~ObjectLifeMonitor(); + + virtual void RunDestructor() = 0; private: - ObjectLifeMonitor(v8::Isolate* isolate, - v8::Local target, - v8::Local destructor); - static void OnObjectGC(const v8::WeakCallbackInfo& data); static void Free(const v8::WeakCallbackInfo& data); - void RunCallback(); - v8::Isolate* isolate_; v8::Global context_; v8::Global target_; - v8::Global destructor_; base::WeakPtrFactory weak_ptr_factory_; diff --git a/atom/common/api/remote_callback_freer.cc b/atom/common/api/remote_callback_freer.cc new file mode 100644 index 00000000000..24d2897ae75 --- /dev/null +++ b/atom/common/api/remote_callback_freer.cc @@ -0,0 +1,70 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/common/api/remote_callback_freer.h" + +#include "atom/common/api/api_messages.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/web_contents.h" + +namespace atom { + +// static +void RemoteCallbackFreer::BindTo(v8::Isolate* isolate, + v8::Local target, + int object_id, + content::WebContents* web_contents) { + new RemoteCallbackFreer(isolate, target, object_id, web_contents); +} + +RemoteCallbackFreer::RemoteCallbackFreer(v8::Isolate* isolate, + v8::Local target, + int object_id, + content::WebContents* web_contents) + : ObjectLifeMonitor(isolate, target), + content::WebContentsObserver(web_contents), + web_contents_(web_contents), + renderer_process_id_(GetRendererProcessID()), + object_id_(object_id) { +} + +RemoteCallbackFreer::~RemoteCallbackFreer() { +} + +void RemoteCallbackFreer::RunDestructor() { + if (!web_contents_) + return; + + if (renderer_process_id_ == GetRendererProcessID()) { + base::string16 channel = + base::ASCIIToUTF16("ELECTRON_RENDERER_RELEASE_CALLBACK"); + base::ListValue args; + args.AppendInteger(object_id_); + Send(new AtomViewMsg_Message(routing_id(), channel, args)); + } + web_contents_ = nullptr; +} + +void RemoteCallbackFreer::WebContentsDestroyed() { + if (!web_contents_) + return; + + web_contents_ = nullptr; + delete this; +} + +int RemoteCallbackFreer::GetRendererProcessID() { + if (!web_contents_) + return -1; + + auto process = web_contents()->GetRenderProcessHost(); + if (!process) + return -1; + + return process->GetID(); +} + +} // namespace atom diff --git a/atom/common/api/remote_callback_freer.h b/atom/common/api/remote_callback_freer.h new file mode 100644 index 00000000000..5c160c2d8ec --- /dev/null +++ b/atom/common/api/remote_callback_freer.h @@ -0,0 +1,44 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_ +#define ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_ +#include "atom/common/api/object_life_monitor.h" +#include "content/public/browser/web_contents_observer.h" + +namespace atom { + +class RemoteCallbackFreer : public ObjectLifeMonitor, + public content::WebContentsObserver { + public: + static void BindTo(v8::Isolate* isolate, + v8::Local target, + int object_id, + content::WebContents* web_conents); + + protected: + RemoteCallbackFreer(v8::Isolate* isolate, + v8::Local target, + int object_id, + content::WebContents* web_conents); + ~RemoteCallbackFreer() override; + + void RunDestructor() override; + + // content::WebContentsObserver: + void WebContentsDestroyed() override; + + private: + int GetRendererProcessID(); + + content::WebContents* web_contents_; + int renderer_process_id_; + int object_id_; + + DISALLOW_COPY_AND_ASSIGN(RemoteCallbackFreer); +}; + +} // namespace atom + +#endif // ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_ diff --git a/atom/common/api/remote_object_freer.cc b/atom/common/api/remote_object_freer.cc new file mode 100644 index 00000000000..1762f1d1e06 --- /dev/null +++ b/atom/common/api/remote_object_freer.cc @@ -0,0 +1,63 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/common/api/remote_object_freer.h" + +#include "atom/common/api/api_messages.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "content/public/renderer/render_view.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "third_party/WebKit/public/web/WebView.h" + +using blink::WebLocalFrame; +using blink::WebView; + +namespace atom { + +namespace { + +content::RenderView* GetCurrentRenderView() { + WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); + if (!frame) + return nullptr; + + WebView* view = frame->view(); + if (!view) + return nullptr; // can happen during closing. + + return content::RenderView::FromWebView(view); +} + +} // namespace + +// static +void RemoteObjectFreer::BindTo( + v8::Isolate* isolate, v8::Local target, int object_id) { + new RemoteObjectFreer(isolate, target, object_id); +} + +RemoteObjectFreer::RemoteObjectFreer( + v8::Isolate* isolate, v8::Local target, int object_id) + : ObjectLifeMonitor(isolate, target), + object_id_(object_id) { +} + +RemoteObjectFreer::~RemoteObjectFreer() { +} + +void RemoteObjectFreer::RunDestructor() { + content::RenderView* render_view = GetCurrentRenderView(); + if (!render_view) + return; + + base::string16 channel = base::ASCIIToUTF16("ipc-message"); + base::ListValue args; + args.AppendString("ELECTRON_BROWSER_DEREFERENCE"); + args.AppendInteger(object_id_); + render_view->Send( + new AtomViewHostMsg_Message(render_view->GetRoutingID(), channel, args)); +} + +} // namespace atom diff --git a/atom/common/api/remote_object_freer.h b/atom/common/api/remote_object_freer.h new file mode 100644 index 00000000000..c2b5d8b7d30 --- /dev/null +++ b/atom/common/api/remote_object_freer.h @@ -0,0 +1,32 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_ +#define ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_ + +#include "atom/common/api/object_life_monitor.h" + +namespace atom { + +class RemoteObjectFreer : public ObjectLifeMonitor { + public: + static void BindTo( + v8::Isolate* isolate, v8::Local target, int object_id); + + protected: + RemoteObjectFreer( + v8::Isolate* isolate, v8::Local target, int object_id); + ~RemoteObjectFreer() override; + + void RunDestructor() override; + + private: + int object_id_; + + DISALLOW_COPY_AND_ASSIGN(RemoteObjectFreer); +}; + +} // namespace atom + +#endif // ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_ diff --git a/atom/common/native_mate_converters/content_converter.cc b/atom/common/native_mate_converters/content_converter.cc index 7e7cd9bd1ff..154dcf88ce3 100644 --- a/atom/common/native_mate_converters/content_converter.cc +++ b/atom/common/native_mate_converters/content_converter.cc @@ -180,4 +180,17 @@ v8::Local Converter::ToV8( return atom::api::WebContents::CreateFrom(isolate, val).ToV8(); } +// static +bool Converter::FromV8( + v8::Isolate* isolate, + v8::Local val, + content::WebContents** out) { + atom::api::WebContents* web_contents = nullptr; + if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents) + return false; + + *out = web_contents->web_contents(); + return true; +} + } // namespace mate diff --git a/atom/common/native_mate_converters/content_converter.h b/atom/common/native_mate_converters/content_converter.h index b1a42b6897c..f2e7211ce5d 100644 --- a/atom/common/native_mate_converters/content_converter.h +++ b/atom/common/native_mate_converters/content_converter.h @@ -57,6 +57,8 @@ template<> struct Converter { static v8::Local ToV8(v8::Isolate* isolate, content::WebContents* val); + static bool FromV8(v8::Isolate* isolate, v8::Local val, + content::WebContents** out); }; } // namespace mate diff --git a/filenames.gypi b/filenames.gypi index c3eca34528d..1c213949756 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -303,6 +303,10 @@ 'atom/common/api/locker.h', 'atom/common/api/object_life_monitor.cc', 'atom/common/api/object_life_monitor.h', + 'atom/common/api/remote_callback_freer.cc', + 'atom/common/api/remote_callback_freer.h', + 'atom/common/api/remote_object_freer.cc', + 'atom/common/api/remote_object_freer.h', 'atom/common/asar/archive.cc', 'atom/common/asar/archive.h', 'atom/common/asar/asar_util.cc', diff --git a/lib/browser/rpc-server.js b/lib/browser/rpc-server.js index ca193b4115e..1dff5fdb8ad 100644 --- a/lib/browser/rpc-server.js +++ b/lib/browser/rpc-server.js @@ -12,8 +12,19 @@ const FUNCTION_PROPERTIES = [ ] // The remote functions in renderer processes. -// (webContentsId) => {id: Function} -let rendererFunctions = {} +// id => Function +let rendererFunctions = new IDWeakMap() + +// Merge two IDs together. +let mergeIds = function (webContentsId, metaId) { + const PADDING_BITS = 20 + if ((webContentsId << PADDING_BITS) < 0) { + throw new Error(`webContents ID is too large: ${webContentsId}`) + } else if (metaId > (1 << PADDING_BITS)) { + throw new Error(`Object ID is too large: ${metaId}`) + } + return (webContentsId << PADDING_BITS) + metaId +} // Return the description of object's members: let getObjectMembers = function (object) { @@ -165,32 +176,26 @@ var unwrapArgs = function (sender, args) { return returnValue } case 'function': { + // Merge webContentsId and meta.id, since meta.id can be the same in + // different webContents. + const webContentsId = sender.getId() + const objectId = mergeIds(webContentsId, meta.id) + // Cache the callbacks in renderer. - let webContentsId = sender.getId() - let callbacks = rendererFunctions[webContentsId] - if (!callbacks) { - callbacks = rendererFunctions[webContentsId] = new IDWeakMap() - sender.once('render-view-deleted', function (event, id) { - callbacks.clear() - delete rendererFunctions[id] - }) + if (rendererFunctions.has(objectId)) { + return rendererFunctions.get(objectId) } - if (callbacks.has(meta.id)) return callbacks.get(meta.id) - let callIntoRenderer = function (...args) { - if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) { + if (!sender.isDestroyed() && webContentsId === sender.getId()) { sender.send('ELECTRON_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args)) } else { throw new Error(`Attempting to call a function in a renderer window that has been closed or released. Function provided here: ${meta.location}.`) } } - v8Util.setDestructor(callIntoRenderer, function () { - if ((webContentsId in rendererFunctions) && !sender.isDestroyed()) { - sender.send('ELECTRON_RENDERER_RELEASE_CALLBACK', meta.id) - } - }) - callbacks.set(meta.id, callIntoRenderer) + + v8Util.setRemoteCallbackFreer(callIntoRenderer, meta.id, sender) + rendererFunctions.set(objectId, callIntoRenderer) return callIntoRenderer } default: diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index d15ebd717ec..6631ea22575 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -210,9 +210,7 @@ let metaToValue = function (meta) { // Track delegate object's life time, and tell the browser to clean up // when the object is GCed. - v8Util.setDestructor(ret, function () { - ipcRenderer.send('ELECTRON_BROWSER_DEREFERENCE', meta.id) - }) + v8Util.setRemoteObjectFreer(ret, meta.id) // Remember object's id. v8Util.setHiddenValue(ret, 'atomId', meta.id) From d9778413e170b70ba52a30eb675dfb8363bf407d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 16:30:26 +0900 Subject: [PATCH 0610/1265] Should also destory RemoteCallbackFreer when page is reloaded --- atom/common/api/remote_callback_freer.cc | 2 +- atom/common/api/remote_callback_freer.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/atom/common/api/remote_callback_freer.cc b/atom/common/api/remote_callback_freer.cc index 24d2897ae75..917128baf9e 100644 --- a/atom/common/api/remote_callback_freer.cc +++ b/atom/common/api/remote_callback_freer.cc @@ -48,7 +48,7 @@ void RemoteCallbackFreer::RunDestructor() { web_contents_ = nullptr; } -void RemoteCallbackFreer::WebContentsDestroyed() { +void RemoteCallbackFreer::RenderViewDeleted(content::RenderViewHost*) { if (!web_contents_) return; diff --git a/atom/common/api/remote_callback_freer.h b/atom/common/api/remote_callback_freer.h index 5c160c2d8ec..43a4a215a4d 100644 --- a/atom/common/api/remote_callback_freer.h +++ b/atom/common/api/remote_callback_freer.h @@ -27,7 +27,7 @@ class RemoteCallbackFreer : public ObjectLifeMonitor, void RunDestructor() override; // content::WebContentsObserver: - void WebContentsDestroyed() override; + void RenderViewDeleted(content::RenderViewHost*) override; private: int GetRendererProcessID(); From 4f21a50d235db3b2cc32b4135a0bc20f20951b83 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 16:31:56 +0900 Subject: [PATCH 0611/1265] Remove duplicated converter for content::WebContents --- atom/browser/api/atom_api_web_view_manager.cc | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/atom/browser/api/atom_api_web_view_manager.cc b/atom/browser/api/atom_api_web_view_manager.cc index e57c5ffb6bb..f06c1105526 100644 --- a/atom/browser/api/atom_api_web_view_manager.cc +++ b/atom/browser/api/atom_api_web_view_manager.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#include "atom/browser/api/atom_api_web_contents.h" #include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_manager.h" +#include "atom/common/native_mate_converters/content_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/node_includes.h" #include "content/public/browser/browser_context.h" @@ -12,22 +12,6 @@ using atom::WebContentsPreferences; -namespace mate { - -template<> -struct Converter { - static bool FromV8(v8::Isolate* isolate, v8::Local val, - content::WebContents** out) { - atom::api::WebContents* contents; - if (!Converter::FromV8(isolate, val, &contents)) - return false; - *out = contents->web_contents(); - return true; - } -}; - -} // namespace mate - namespace { atom::WebViewManager* GetWebViewManager(content::WebContents* web_contents) { From 76a954077d7ed12592c0a8dc62093212dfddfac8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 26 Apr 2016 16:37:46 +0900 Subject: [PATCH 0612/1265] Simplify RemoteCallbackFreer --- atom/common/api/remote_callback_freer.cc | 35 ++++-------------------- atom/common/api/remote_callback_freer.h | 4 --- 2 files changed, 6 insertions(+), 33 deletions(-) diff --git a/atom/common/api/remote_callback_freer.cc b/atom/common/api/remote_callback_freer.cc index 917128baf9e..7bc377efc5e 100644 --- a/atom/common/api/remote_callback_freer.cc +++ b/atom/common/api/remote_callback_freer.cc @@ -7,8 +7,6 @@ #include "atom/common/api/api_messages.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/web_contents.h" namespace atom { @@ -26,8 +24,6 @@ RemoteCallbackFreer::RemoteCallbackFreer(v8::Isolate* isolate, content::WebContents* web_contents) : ObjectLifeMonitor(isolate, target), content::WebContentsObserver(web_contents), - web_contents_(web_contents), - renderer_process_id_(GetRendererProcessID()), object_id_(object_id) { } @@ -35,36 +31,17 @@ RemoteCallbackFreer::~RemoteCallbackFreer() { } void RemoteCallbackFreer::RunDestructor() { - if (!web_contents_) - return; + base::string16 channel = + base::ASCIIToUTF16("ELECTRON_RENDERER_RELEASE_CALLBACK"); + base::ListValue args; + args.AppendInteger(object_id_); + Send(new AtomViewMsg_Message(routing_id(), channel, args)); - if (renderer_process_id_ == GetRendererProcessID()) { - base::string16 channel = - base::ASCIIToUTF16("ELECTRON_RENDERER_RELEASE_CALLBACK"); - base::ListValue args; - args.AppendInteger(object_id_); - Send(new AtomViewMsg_Message(routing_id(), channel, args)); - } - web_contents_ = nullptr; + Observe(nullptr); } void RemoteCallbackFreer::RenderViewDeleted(content::RenderViewHost*) { - if (!web_contents_) - return; - - web_contents_ = nullptr; delete this; } -int RemoteCallbackFreer::GetRendererProcessID() { - if (!web_contents_) - return -1; - - auto process = web_contents()->GetRenderProcessHost(); - if (!process) - return -1; - - return process->GetID(); -} - } // namespace atom diff --git a/atom/common/api/remote_callback_freer.h b/atom/common/api/remote_callback_freer.h index 43a4a215a4d..8fe80c8d477 100644 --- a/atom/common/api/remote_callback_freer.h +++ b/atom/common/api/remote_callback_freer.h @@ -30,10 +30,6 @@ class RemoteCallbackFreer : public ObjectLifeMonitor, void RenderViewDeleted(content::RenderViewHost*) override; private: - int GetRendererProcessID(); - - content::WebContents* web_contents_; - int renderer_process_id_; int object_id_; DISALLOW_COPY_AND_ASSIGN(RemoteCallbackFreer); From 21af03d71ad4dad9bd4a15996884b7a7b7869129 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Mon, 25 Apr 2016 23:23:16 -0400 Subject: [PATCH 0613/1265] :apple: Fix converting from windows virtual keycode back to mac keycode --- atom/browser/ui/accelerator_util_mac.mm | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/atom/browser/ui/accelerator_util_mac.mm b/atom/browser/ui/accelerator_util_mac.mm index be631b02124..d3395884c97 100644 --- a/atom/browser/ui/accelerator_util_mac.mm +++ b/atom/browser/ui/accelerator_util_mac.mm @@ -13,12 +13,6 @@ namespace accelerator_util { void SetPlatformAccelerator(ui::Accelerator* accelerator) { unichar character; unichar characterIgnoringModifiers; - ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(), - 0, - &character, - &characterIgnoringModifiers); - NSString* characters = - [[[NSString alloc] initWithCharacters:&character length:1] autorelease]; NSUInteger modifiers = (accelerator->IsCtrlDown() ? NSControlKeyMask : 0) | @@ -26,6 +20,18 @@ void SetPlatformAccelerator(ui::Accelerator* accelerator) { (accelerator->IsAltDown() ? NSAlternateKeyMask : 0) | (accelerator->IsShiftDown() ? NSShiftKeyMask : 0); + ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(), + modifiers, + &character, + &characterIgnoringModifiers); + + if (character != characterIgnoringModifiers) { + modifiers ^= NSShiftKeyMask; + } + + NSString* characters = + [[[NSString alloc] initWithCharacters:&character length:1] autorelease]; + scoped_ptr platform_accelerator( new ui::PlatformAcceleratorCocoa(characters, modifiers)); accelerator->set_platform_accelerator(std::move(platform_accelerator)); From b1c0e7e2ab5fa3c7b680ec626ad1a14575ac3db6 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 10:28:04 -0700 Subject: [PATCH 0614/1265] web-frame -> webFrame --- docs/api/web-frame.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index b2d8aa0f41e..4b7d04b6f0f 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -12,7 +12,7 @@ webFrame.setZoomFactor(2); ## Methods -The `web-frame` module has the following methods: +The `webFrame` module has the following methods: ### `webFrame.setZoomFactor(factor)` From 4080442f8006c5e839adf132b25aa5aa1e5da309 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 10:28:20 -0700 Subject: [PATCH 0615/1265] content-tracing -> contentTracing --- docs/api/content-tracing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/content-tracing.md b/docs/api/content-tracing.md index a9414d34876..e347790b63f 100644 --- a/docs/api/content-tracing.md +++ b/docs/api/content-tracing.md @@ -28,7 +28,7 @@ contentTracing.startRecording(options, function() { ## Methods -The `content-tracing` module has the following methods: +The `contentTracing` module has the following methods: ### `contentTracing.getCategories(callback)` From f3c3042debd0ff59ebb435cf9d4d6311d1e12bb0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 27 Apr 2016 19:55:01 +0900 Subject: [PATCH 0616/1265] Do not run clean in cibuild --- script/cibuild | 4 ---- 1 file changed, 4 deletions(-) diff --git a/script/cibuild b/script/cibuild index fda5817b6b8..59437837aa1 100755 --- a/script/cibuild +++ b/script/cibuild @@ -53,8 +53,6 @@ def main(): if PLATFORM == 'linux': os.environ['DISPLAY'] = ':99.0' - run_script('clean.py') - # CI's npm is not reliable. npm = 'npm.cmd' if PLATFORM == 'win32' else 'npm' execute([npm, 'install', 'npm@2.12.1']) @@ -81,8 +79,6 @@ def main(): if PLATFORM != 'win32' and target_arch == 'x64': run_script('test.py', ['--ci']) - run_script('clean.py') - def run_script(script, args=[]): sys.stderr.write('\nRunning ' + script +'\n') From 4435cdc576e27c5f6fa4701232e95f2024655319 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 27 Apr 2016 21:46:44 +0900 Subject: [PATCH 0617/1265] Create user_data_dir before creating singleton lock --- chromium_src/chrome/browser/process_singleton_posix.cc | 3 +++ chromium_src/chrome/browser/process_singleton_win.cc | 3 +++ 2 files changed, 6 insertions(+) diff --git a/chromium_src/chrome/browser/process_singleton_posix.cc b/chromium_src/chrome/browser/process_singleton_posix.cc index c583db0162a..5c26d7b6157 100644 --- a/chromium_src/chrome/browser/process_singleton_posix.cc +++ b/chromium_src/chrome/browser/process_singleton_posix.cc @@ -717,6 +717,9 @@ ProcessSingleton::ProcessSingleton( const NotificationCallback& notification_callback) : notification_callback_(notification_callback), current_pid_(base::GetCurrentProcId()) { + // The user_data_dir may have not been created yet. + base::CreateDirectoryAndGetError(user_data_dir, nullptr); + socket_path_ = user_data_dir.Append(kSingletonSocketFilename); lock_path_ = user_data_dir.Append(kSingletonLockFilename); cookie_path_ = user_data_dir.Append(kSingletonCookieFilename); diff --git a/chromium_src/chrome/browser/process_singleton_win.cc b/chromium_src/chrome/browser/process_singleton_win.cc index fd4c22e7405..b488ad45767 100644 --- a/chromium_src/chrome/browser/process_singleton_win.cc +++ b/chromium_src/chrome/browser/process_singleton_win.cc @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/process/process.h" #include "base/process/process_info.h" #include "base/strings/string_number_conversions.h" @@ -190,6 +191,8 @@ ProcessSingleton::ProcessSingleton( user_data_dir_(user_data_dir), should_kill_remote_process_callback_( base::Bind(&TerminateAppWithError)) { + // The user_data_dir may have not been created yet. + base::CreateDirectoryAndGetError(user_data_dir, nullptr); } ProcessSingleton::~ProcessSingleton() { From 46208b5b3efa881c66b646ccaf116667fbdd83eb Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 27 Apr 2016 20:00:31 +0530 Subject: [PATCH 0618/1265] session: dont attach download dialog to deleted webContents window --- atom/browser/api/atom_api_session.cc | 2 +- atom/browser/atom_download_manager_delegate.cc | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index ec4e2aebe4c..45281c4112b 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -315,7 +315,7 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, bool prevent_default = Emit( "will-download", DownloadItem::Create(isolate(), item), - api::WebContents::CreateFrom(isolate(), web_contents)); + web_contents); if (prevent_default) { item->Cancel(true); item->Remove(); diff --git a/atom/browser/atom_download_manager_delegate.cc b/atom/browser/atom_download_manager_delegate.cc index 16c0cf708b8..295747a33c4 100644 --- a/atom/browser/atom_download_manager_delegate.cc +++ b/atom/browser/atom_download_manager_delegate.cc @@ -70,7 +70,9 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated( return; NativeWindow* window = nullptr; - auto relay = NativeWindowRelay::FromWebContents(item->GetWebContents()); + content::WebContents* web_contents = item->GetWebContents(); + auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) + : nullptr; if (relay) window = relay->window.get(); From bfae925b0ffc4cb58656f5ade92e744fb0a5a248 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Wed, 27 Apr 2016 22:49:07 +0800 Subject: [PATCH 0619/1265] Translate `testing-on-headless-ci.md` to Chinese --- .../zh-CN/tutorial/testing-on-headless-ci.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs-translations/zh-CN/tutorial/testing-on-headless-ci.md diff --git a/docs-translations/zh-CN/tutorial/testing-on-headless-ci.md b/docs-translations/zh-CN/tutorial/testing-on-headless-ci.md new file mode 100644 index 00000000000..7da98b0a1a6 --- /dev/null +++ b/docs-translations/zh-CN/tutorial/testing-on-headless-ci.md @@ -0,0 +1,51 @@ +# Testing Electron with headless CI Systems (Travis CI, Jenkins) + +Electron基于Chromium,所以需要一个显示驱动使其运转。如果Chromium无法找到一个显示驱动, +ELectron 会启动失败,因此无论你如何去运行它,Electron不会执行你的任何测试。在Travis, Circle, +Jenkins 或者类似的系统上测试基于Electron的应用时,需要进行一些配置。本质上,我们需要使用一个 +虚拟的显示驱动。 + +## Configuring the Virtual Display Server + +首先安装[Xvfb](https://en.wikipedia.org/wiki/Xvfb)。 +这是一个虚拟的帧缓冲,实现了X11显示服务协议,所有的图形操作都在内存中表现,而不需要显示在 +任何屏幕输出设备上。这正是我们所需要的。 + +然后创建一个虚拟的xvfb屏幕并且导出一个指向他的名为`DISPLAY`的环境变量。Electron中的Chromium +会自动的去寻找`$DISPLAY`,所以你的应用不需要再去进行配置。这一步可以通过Paul Betts's的 +[xvfb-maybe](https://github.com/paulcbetts/xvfb-maybe)实现自动化:如果系统需要,在`xvfb-maybe`前加上你的测试命令 +然后这个小工具会自动的设置xvfb。在Windows或者Mac OS X系统下,它不会执行任何东西。 + +``` +## On Windows or OS X, this just invokes electron-mocha +## On Linux, if we are in a headless environment, this will be equivalent +## to xvfb-run electron-mocha ./test/*.js +xvfb-maybe electron-mocha ./test/*.js +``` + +### Travis CI + +在 Travis 上, 你的 `.travis.yml` 应该和下面的代码相似: + +``` +addons: + apt: + packages: + - xvfb + +install: + - export DISPLAY=':99.0' + - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & +``` + +### Jenkins + +Jenkins下, 有一个可用的[Xvfb插件](https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin). + +### Circle CI + +Circle CI 是非常棒的而且有xvfb,`$DISPLAY`也[已经搭建,所以不需要再进行设置](https://circleci.com/docs/environment#browsers)。 + +### AppVeyor + +AppVeyor运行于Windows上,支持 Selenium, Chromium, Electron 以及一些类似的工具,开箱即用,无需配置。 From 6dbd2ce243a6f01772bceed345239741ef0fbe01 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 27 Apr 2016 20:29:39 +0530 Subject: [PATCH 0620/1265] use DownloadItem to determine download initiator --- atom/browser/api/atom_api_session.cc | 7 ++----- atom/browser/api/save_page_handler.cc | 5 ----- atom/browser/api/save_page_handler.h | 2 -- 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 45281c4112b..39c435b723e 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -9,9 +9,7 @@ #include "atom/browser/api/atom_api_cookies.h" #include "atom/browser/api/atom_api_download_item.h" -#include "atom/browser/api/atom_api_web_contents.h" #include "atom/browser/api/atom_api_web_request.h" -#include "atom/browser/api/save_page_handler.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_permission_manager.h" @@ -306,8 +304,7 @@ Session::~Session() { void Session::OnDownloadCreated(content::DownloadManager* manager, content::DownloadItem* item) { - auto web_contents = item->GetWebContents(); - if (SavePageHandler::IsSavePageTypes(item->GetMimeType())) + if (item->IsSavePackageDownload()) return; v8::Locker locker(isolate()); @@ -315,7 +312,7 @@ void Session::OnDownloadCreated(content::DownloadManager* manager, bool prevent_default = Emit( "will-download", DownloadItem::Create(isolate(), item), - web_contents); + item->GetWebContents()); if (prevent_default) { item->Cancel(true); item->Remove(); diff --git a/atom/browser/api/save_page_handler.cc b/atom/browser/api/save_page_handler.cc index 1e5bc094cf6..e07ec3ac0ab 100644 --- a/atom/browser/api/save_page_handler.cc +++ b/atom/browser/api/save_page_handler.cc @@ -73,11 +73,6 @@ void SavePageHandler::Destroy(content::DownloadItem* item) { delete this; } -// static -bool SavePageHandler::IsSavePageTypes(const std::string& type) { - return type == "multipart/related" || type == "text/html"; -} - } // namespace api } // namespace atom diff --git a/atom/browser/api/save_page_handler.h b/atom/browser/api/save_page_handler.h index dd1692a8bad..951a9414e03 100644 --- a/atom/browser/api/save_page_handler.h +++ b/atom/browser/api/save_page_handler.h @@ -37,8 +37,6 @@ class SavePageHandler : public content::DownloadManager::Observer, bool Handle(const base::FilePath& full_path, const content::SavePageType& save_type); - static bool IsSavePageTypes(const std::string& type); - private: void Destroy(content::DownloadItem* item); From df2141d9e69da138b491122839780260e8548a80 Mon Sep 17 00:00:00 2001 From: Rita Zhang Date: Sun, 24 Apr 2016 22:17:01 -0700 Subject: [PATCH 0621/1265] :zap: Add API: IsDefaultProtocolClient --- atom/browser/api/atom_api_app.cc | 2 ++ atom/browser/browser.h | 3 +++ atom/browser/browser_linux.cc | 4 +++ atom/browser/browser_mac.mm | 24 +++++++++++++++++ atom/browser/browser_win.cc | 44 ++++++++++++++++++++++++++++++++ docs/api/app.md | 14 ++++++++++ 6 files changed, 91 insertions(+) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index ce20ce96ded..304e53a5554 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -451,6 +451,8 @@ void App::BuildPrototype( base::Bind(&Browser::ClearRecentDocuments, browser)) .SetMethod("setAppUserModelId", base::Bind(&Browser::SetAppUserModelID, browser)) + .SetMethod("isDefaultProtocolClient", + base::Bind(&Browser::IsDefaultProtocolClient, browser)) .SetMethod("setAsDefaultProtocolClient", base::Bind(&Browser::SetAsDefaultProtocolClient, browser)) .SetMethod("removeAsDefaultProtocolClient", diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 0f1dbe99311..8329b14bc2c 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -82,6 +82,9 @@ class Browser : public WindowListObserver { // Set as default handler for a protocol. bool SetAsDefaultProtocolClient(const std::string& protocol); + // Query the current state of default handler for a protocol. + bool IsDefaultProtocolClient(const std::string& protocol); + #if defined(OS_MACOSX) // Hide the application. void Hide(); diff --git a/atom/browser/browser_linux.cc b/atom/browser/browser_linux.cc index 6c7d4abaf64..d994bb4109b 100644 --- a/atom/browser/browser_linux.cc +++ b/atom/browser/browser_linux.cc @@ -42,6 +42,10 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return false; } +bool Browser::IsDefaultProtocolClient(const std::string& protocol) { + return false; +} + std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 11fd3aa6d35..c10369a2e7a 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -60,6 +60,30 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return return_code == noErr; } +bool Browser::IsDefaultProtocolClient(const std::string& protocol) { + if (protocol.empty()) + return false; + + NSString* identifier = [base::mac::MainBundle() bundleIdentifier]; + if (!identifier) + return false; + + NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()]; + + CFStringRef bundle = + LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)); + NSString* bundleId = static_cast( + base::mac::CFTypeRefToNSObjectAutorelease(bundle)); + if (!bundleId) + return false; + + // Ensure the comparison is case-insensitive + // as LS does not persist the case of the bundle id. + NSComparisonResult result = + [bundleId caseInsensitiveCompare:identifier]; + return result == NSOrderedSame; +} + void Browser::SetAppUserModelID(const base::string16& name) { } diff --git a/atom/browser/browser_win.cc b/atom/browser/browser_win.cc index 9531406f8cd..7b1402ba2d2 100644 --- a/atom/browser/browser_win.cc +++ b/atom/browser/browser_win.cc @@ -225,6 +225,50 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return true; } +bool Browser::IsDefaultProtocolClient(const std::string& protocol) { + if (protocol.empty()) + return false; + + base::FilePath path; + if (!PathService::Get(base::FILE_EXE, &path)) { + LOG(ERROR) << "Error getting app exe path"; + return false; + } + + // Main Registry Key + HKEY root = HKEY_CURRENT_USER; + std::string keyPathStr = "Software\\Classes\\" + protocol; + std::wstring keyPath = std::wstring(keyPathStr.begin(), keyPathStr.end()); + + // Command Key + std::string cmdPathStr = keyPathStr + "\\shell\\open\\command"; + std::wstring cmdPath = std::wstring(cmdPathStr.begin(), cmdPathStr.end()); + + base::win::RegKey key; + base::win::RegKey commandKey; + if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) + // Key doesn't exist, we can confirm that it is not set + return false; + + if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) + // Key doesn't exist, we can confirm that it is not set + return false; + + std::wstring keyVal; + if (FAILED(commandKey.ReadValue(L"", &keyVal))) + // Default value not set, we can confirm that it is not set + return false; + + std::wstring exePath(path.value()); + std::wstring exe = L"\"" + exePath + L"\" \"%1\""; + if (keyVal == exe) { + // Default value is the same as current file path + return true; + } else { + return false; + } +} + PCWSTR Browser::GetAppUserModelID() { if (app_user_model_id_.empty()) { SetAppUserModelID(base::ReplaceStringPlaceholders( diff --git a/docs/api/app.md b/docs/api/app.md index 0aca703ba51..1f682933d23 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -384,6 +384,18 @@ This method checks if the current executable as the default handler for a protoc **Note:** On OS X, removing the app will automatically remove the app as the default protocol handler. +### `app.isDefaultProtocolClient(protocol)` _OS X_ _Windows_ + +* `protocol` String - The name of your protocol, without `://`. + +This method checks if the current executable is the default handler for a protocol +(aka URI scheme). If so, it will return true. Otherwise, it will return false. + +**Note:** On OS X, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the OS X machine. +Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. + +The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally. + ### `app.setUserTasks(tasks)` _Windows_ * `tasks` Array - Array of `Task` objects @@ -556,3 +568,5 @@ Sets the `image` associated with this dock icon. [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 +[LSCopyDefaultHandlerForURLScheme]: +https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme From 4e6b148eaa93034fb003e9060ef7fc149cf721bb Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 28 Apr 2016 01:54:08 +0530 Subject: [PATCH 0622/1265] webContents: fix executejavascript when called before page load --- lib/browser/api/web-contents.js | 6 ++++-- spec/api-browser-window-spec.js | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index dfacf6a02cf..823351ebe11 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -117,9 +117,11 @@ let wrapWebContents = function (webContents) { hasUserGesture = false } if (this.getURL() && !this.isLoadingMainFrame()) { - return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture) + asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture) } else { - return this.once('did-finish-load', asyncWebFrameMethods.bind(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)) + this.once('did-finish-load', () => { + asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture) + }) } } diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index 1110269e5de..c364b916c3a 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -870,6 +870,14 @@ describe('browser-window module', function () { }) w.loadURL(server.url) }) + + it('executes after page load', function (done) { + w.webContents.executeJavaScript(code, function(result) { + assert.equal(result, expected) + done() + }) + w.loadURL(server.url) + }) }) describe('deprecated options', function () { From d64e3784f4df22cde31c3cc924e02548581c685f Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Thu, 28 Apr 2016 02:02:14 +0530 Subject: [PATCH 0623/1265] renderer: fix desktop capture api not responding different subsequest calls --- atom/browser/api/atom_api_desktop_capturer.cc | 1 - spec/api-desktop-capturer-spec.js | 12 ++++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_desktop_capturer.cc b/atom/browser/api/atom_api_desktop_capturer.cc index cc978a40b39..9200a89224c 100644 --- a/atom/browser/api/atom_api_desktop_capturer.cc +++ b/atom/browser/api/atom_api_desktop_capturer.cc @@ -89,7 +89,6 @@ void DesktopCapturer::OnSourceThumbnailChanged(int index) { bool DesktopCapturer::OnRefreshFinished() { Emit("finished", media_list_->GetSources()); - media_list_.reset(); return false; } diff --git a/spec/api-desktop-capturer-spec.js b/spec/api-desktop-capturer-spec.js index 9e85a48fbcc..68ab2463087 100644 --- a/spec/api-desktop-capturer-spec.js +++ b/spec/api-desktop-capturer-spec.js @@ -24,4 +24,16 @@ describe('desktopCapturer', function () { desktopCapturer.getSources({types: ['window', 'screen']}, callback) desktopCapturer.getSources({types: ['window', 'screen']}, callback) }) + + it('responds to subsequest calls of different options', function (done) { + var callCount = 0 + var callback = function (error, sources) { + callCount++ + assert.equal(error, null) + if (callCount === 2) done() + } + + desktopCapturer.getSources({types: ['window']}, callback) + desktopCapturer.getSources({types: ['screen']}, callback) + }) }) From 1bac04c69d051ece3c6d04f598ecc02f7583cd03 Mon Sep 17 00:00:00 2001 From: StoneStoneStone Date: Thu, 28 Apr 2016 22:30:14 +0800 Subject: [PATCH 0624/1265] Update desktop-environment-integration.md --- .../desktop-environment-integration.md | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/docs-translations/zh-CN/tutorial/desktop-environment-integration.md b/docs-translations/zh-CN/tutorial/desktop-environment-integration.md index f069065cd65..3f946da34e1 100644 --- a/docs-translations/zh-CN/tutorial/desktop-environment-integration.md +++ b/docs-translations/zh-CN/tutorial/desktop-environment-integration.md @@ -3,6 +3,47 @@ 本章将会说明怎样使用 Electron APIs 把你的应用和桌面环境集成到一块。 +## Notifications (Windows, Linux, OS X) + +这三个操作系统都为用户提供了发送通知的方法。Electron让开发人员通过 +[HTML5 Notification API](https://notifications.spec.whatwg.org/) +便利的去发送通知,用操作系统自带的通知APIs去显示。 + +**Note:** 因为这是一个HTML5API,所以只在渲染进程中起作用 + +```javascript +var myNotification = new Notification('Title', { + body: 'Lorem Ipsum Dolor Sit Amet' +}); + +myNotification.onclick = function () { + console.log('Notification clicked') +} +``` + +尽管代码和用户体验在不同的操作系统中基本相同,但还是有一些差异。 + +### Windows + +* 在Windows 10上, 通知"可以工作". +* 在Windows 8.1和Windows 8系统下,你需要将你的应用通过一个[Application User +Model ID][app-user-model-id]安装到开始屏幕上。需要注意的是,这不是将你的应用固定到开始屏幕。 +* 在Windows 7以及更低的版本中,通知不被支持。不过你可以使用[Tray API][tray-balloon]发送一个"气泡通知"。 + +此外,通知支持的最大字符长队为250。Windows团队建议通知应该保持在200个字符以下。 + +### Linux + +通知使用`libnotify`发送,它能在任何支持[Desktop Notifications +Specification][notification-spec]的桌面环境中显示,包括 Cinnamon, Enlightenment, Unity, +GNOME, KDE。 + +### OS X + +在OS X系统中,通知是直接转发的,你应该了解[Apple's Human Interface guidelines regarding notifications](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/OSXHIGuidelines/NotificationCenter.html)。 + +注意通知被限制在256个字节以内,如果超出,则会被截断。 + ## 最近文档 (Windows & OS X) Windows 和 OS X 提供获取最近文档列表的便捷方式,那就是打开跳转列表或者鱼眼菜单。 @@ -165,3 +206,17 @@ window.setDocumentEdited(true); [16]: https://cloud.githubusercontent.com/assets/639601/5082061/670a949a-6f14-11e4-987a-9aaa04b23c1d.png [17]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md [18]: https://github.com/electron/electron/blob/master/docs-translations/zh-CN/api/browser-window.md + +[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath-os-x-windows +[clearrecentdocuments]: ../api/app.md#appclearrecentdocuments-os-x-windows +[setusertaskstasks]: ../api/app.md#appsetusertaskstasks-windows +[setprogressbar]: ../api/browser-window.md#winsetprogressbarprogress +[setoverlayicon]: ../api/browser-window.md#winsetoverlayiconoverlay-description-windows-7 +[setrepresentedfilename]: ../api/browser-window.md#winsetrepresentedfilenamefilename-os-x +[setdocumentedited]: ../api/browser-window.md#winsetdocumenteditededited-os-x +[app-registration]: http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx +[unity-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher +[setthumbarbuttons]: ../api/browser-window.md#winsetthumbarbuttonsbuttons-windows-7 +[tray-balloon]: ../api/tray.md#traydisplayballoonoptions-windows +[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx +[notification-spec]: https://developer.gnome.org/notification-spec/ From 340b7220f126e8f9d590a76b34604a085c833cab Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Thu, 28 Apr 2016 17:46:41 +0200 Subject: [PATCH 0625/1265] Fix #3075 by not caching the displays (id is not persistent on Windows) --- atom/browser/api/atom_api_screen.cc | 14 +------------- atom/browser/api/atom_api_screen.h | 1 - 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/atom/browser/api/atom_api_screen.cc b/atom/browser/api/atom_api_screen.cc index 61b722d7a44..9d845e390e3 100644 --- a/atom/browser/api/atom_api_screen.cc +++ b/atom/browser/api/atom_api_screen.cc @@ -49,7 +49,6 @@ std::vector MetricsToArray(uint32_t metrics) { Screen::Screen(v8::Isolate* isolate, gfx::Screen* screen) : screen_(screen) { - displays_ = screen_->GetAllDisplays(); screen_->AddObserver(this); Init(isolate); } @@ -67,7 +66,7 @@ gfx::Display Screen::GetPrimaryDisplay() { } std::vector Screen::GetAllDisplays() { - return displays_; + return screen_->GetAllDisplays(); } gfx::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { @@ -79,26 +78,15 @@ gfx::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { } void Screen::OnDisplayAdded(const gfx::Display& new_display) { - displays_.push_back(new_display); Emit("display-added", new_display); } void Screen::OnDisplayRemoved(const gfx::Display& old_display) { - auto iter = FindById(&displays_, old_display.id()); - if (iter == displays_.end()) - return; - - displays_.erase(iter); Emit("display-removed", old_display); } void Screen::OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) { - auto iter = FindById(&displays_, display.id()); - if (iter == displays_.end()) - return; - - *iter = display; Emit("display-metrics-changed", display, MetricsToArray(changed_metrics)); } diff --git a/atom/browser/api/atom_api_screen.h b/atom/browser/api/atom_api_screen.h index 14fc8ce30e7..c17b6128852 100644 --- a/atom/browser/api/atom_api_screen.h +++ b/atom/browser/api/atom_api_screen.h @@ -47,7 +47,6 @@ class Screen : public mate::EventEmitter, private: gfx::Screen* screen_; - std::vector displays_; DISALLOW_COPY_AND_ASSIGN(Screen); }; From 09b036f07b15af5c2cf1d1681699e93161c8155a Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 09:16:59 -0700 Subject: [PATCH 0626/1265] Update header colors --- default_app/index.html | 58 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 11 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index 5c8440cfdad..3fab74a3108 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -3,8 +3,8 @@ Electron From 7e9d7900706b36e72b394c38b72f48ab20659bfa Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 09:28:50 -0700 Subject: [PATCH 0628/1265] Tweak font weight on holder div --- default_app/index.html | 3 +++ 1 file changed, 3 insertions(+) diff --git a/default_app/index.html b/default_app/index.html index c11a4e37147..2748c01dcbe 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -6,6 +6,8 @@ color: #205161; background-color: #fff; font-family: Roboto, -apple-system, BlinkMacSystemFont, "Helvetica Neue", "Segoe UI", "Oxygen", "Ubuntu", "Cantarell", "Open Sans", sans-serif; + font-style: normal; + font-variant: normal; padding: 0; margin: 0; } @@ -82,6 +84,7 @@ color: #466a72; border-radius: 3px; font-size: 30px; + font-weight: 300; line-height: 275px; text-align: center; -webkit-user-select: none; From c6edab0950a3db6fb2a62685d3458a9293046d16 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 09:30:37 -0700 Subject: [PATCH 0629/1265] Tweak link style --- default_app/index.html | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index 2748c01dcbe..5c266c40dd7 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -46,13 +46,10 @@ vertical-align: middle !important; } - a { - color: #39AEC6; - text-decoration: none; - } - + a, a:hover { - text-decoration: underline; + color: #2ab0cb; + text-decoration: none; } pre, code { From dd337640f5afca9730fccc0c2e0c9ac4aee8867e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 09:30:55 -0700 Subject: [PATCH 0630/1265] :art: --- default_app/index.html | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index 5c266c40dd7..61f7e01c0ee 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -115,12 +115,12 @@
From 068909dc03b281d55618c12036de1221e27cbfbe Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 10:06:46 -0700 Subject: [PATCH 0631/1265] Tweak header text color --- default_app/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index 61f7e01c0ee..f1a1142aa84 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -19,7 +19,7 @@ .header { background-color: #2f3241; border-bottom: 1px solid #1a1b23; - color: #74b1be; + color: #9feaf9; padding: 15px 30px; margin: 0; } @@ -39,7 +39,7 @@ .svg-stroke, .svg-fill { - stroke: #74b1be; + stroke: #9feaf9; } .vertical-middle { From 6979ea7fda87c8145de087c0027653cc53634c72 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 26 Apr 2016 10:07:05 -0700 Subject: [PATCH 0632/1265] Use default cursor on holder area --- default_app/index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/default_app/index.html b/default_app/index.html index f1a1142aa84..aa1ed4e869c 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -84,6 +84,7 @@ font-weight: 300; line-height: 275px; text-align: center; + cursor: default; -webkit-user-select: none; } From 3e4ecd6d6eb1dfdef6319b98b63fb70c57ec7670 Mon Sep 17 00:00:00 2001 From: simurai Date: Wed, 27 Apr 2016 10:42:03 +0900 Subject: [PATCH 0633/1265] Fix logo So the inner dot is filled --- default_app/index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index aa1ed4e869c..f9387cfff7a 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -37,10 +37,12 @@ margin-right: 0.4em; } - .svg-stroke, - .svg-fill { + .svg-stroke { stroke: #9feaf9; } + .svg-fill { + fill: #9feaf9; + } .vertical-middle { vertical-align: middle !important; From 5995e3f40031ddcbfb879e7992faff4c12ee5e18 Mon Sep 17 00:00:00 2001 From: simurai Date: Wed, 27 Apr 2016 10:50:21 +0900 Subject: [PATCH 0634/1265] Make drag&drop text wrap-able --- default_app/index.html | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/default_app/index.html b/default_app/index.html index f9387cfff7a..27cc69fbd4f 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -76,7 +76,11 @@ } #holder { + display: flex; + align-items: center; + justify-content: center; margin: 0 auto; + padding: 10px; height: 275px; border: 1px solid #e0e5e6; background-color: #f6f8f8; @@ -84,7 +88,6 @@ border-radius: 3px; font-size: 30px; font-weight: 300; - line-height: 275px; text-align: center; cursor: default; -webkit-user-select: none; From 80bece56406745a9cdab8f2342c9204ded3a4500 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 27 Apr 2016 15:37:03 -0700 Subject: [PATCH 0635/1265] Add links to nav bar --- default_app/index.html | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index 27cc69fbd4f..ffd99e380bf 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -24,11 +24,23 @@ margin: 0; } - .header-version { + .header a { + padding-left: 15px; + color: #9feaf9; + font-weight: 300; + } + + .header-nav { float: right; margin-top: 12px; } + .header-version { + font-size: 1em; + padding-left: 10px; + font-weight: 300; + } + .header-icon { width: 48px; height: 48px; @@ -134,8 +146,12 @@ -
- Version + + +
From b0dc7ff841bac49f484767e6bac8c78f1fdf135d Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 27 Apr 2016 15:41:36 -0700 Subject: [PATCH 0636/1265] Remove header link hover color --- default_app/index.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/default_app/index.html b/default_app/index.html index ffd99e380bf..c10d67a089a 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -24,7 +24,8 @@ margin: 0; } - .header a { + .header a, + .header a:hover { padding-left: 15px; color: #9feaf9; font-weight: 300; From f7d4ff90eac6c934f280599ce6e73f1b26cd27ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arif=20=C3=87ak=C4=B1ro=C4=9Flu?= Date: Fri, 29 Apr 2016 02:28:46 +0300 Subject: [PATCH 0637/1265] added accelerator.md to api folders and translated (#5316) * added accelerator.md to api folders and translated :tada: * added file-object.md to api folder and translated * added all folders to /tr-TR for broken links * removed untouched documentation file * broken link fix --- docs-translations/tr-TR/README.md | 108 ++++++++++----------- docs-translations/tr-TR/api/accelerator.md | 49 ++++++++++ docs-translations/tr-TR/api/file-object.md | 29 ++++++ docs-translations/tr-TR/styleguide.md | 2 +- 4 files changed, 133 insertions(+), 55 deletions(-) create mode 100644 docs-translations/tr-TR/api/accelerator.md create mode 100644 docs-translations/tr-TR/api/file-object.md diff --git a/docs-translations/tr-TR/README.md b/docs-translations/tr-TR/README.md index 1d79da1d667..b055e63f5af 100644 --- a/docs-translations/tr-TR/README.md +++ b/docs-translations/tr-TR/README.md @@ -5,82 +5,82 @@ Eğer öyleyse, atom.io üzerinden [mevcut sürümler](http://electron.atom.io/d ## SSS(Sıkça Sorulan Sorular) Bir problem(issue) bildirmeden önce sıkça sorulan sorulara göz atın: -* [Electron SSS](faq/electron-faq.md) +* [Electron SSS](https://github.com/electron/electron/tree/master/docs/faq/electron-faq.md) ## Klavuzlar -* [Desteklenen Platformlar ](tutorial/supported-platforms.md) -* [Uygulama Dağıtımı](tutorial/application-distribution.md) -* [Mac Uygulama Mağazası Başvuru Klavuzu](tutorial/mac-app-store-submission-guide.md) -* [Uygulama Paketleme](tutorial/application-packaging.md) -* [Native Node Modüllerini Kullanma](tutorial/using-native-node-modules.md) -* [Ana Süreç(Main Process) Hata ayıklama](tutorial/debugging-main-process.md) -* [Selenium ve WebDriver kullanımı](tutorial/using-selenium-and-webdriver.md) -* [DevTools Eklentisi](tutorial/devtools-extension.md) -* [Pepper Flash Kullanımı](tutorial/using-pepper-flash-plugin.md) -* [Widevine CDM Kullanımı](tutorial/using-widevine-cdm-plugin.md) -* [CI Sistem Testleri (Travis, Jenkins)](tutorial/testing-on-headless-ci.md) +* [Desteklenen Platformlar ](https://github.com/electron/electron/tree/master/docs/tutorial/supported-platforms.md) +* [Uygulama Dağıtımı](https://github.com/electron/electron/tree/master/docs/tutorial/application-distribution.md) +* [Mac Uygulama Mağazası Başvuru Klavuzu](https://github.com/electron/electron/tree/master/docs/tutorial/mac-app-store-submission-guide.md) +* [Uygulama Paketleme](https://github.com/electron/electron/tree/master/docs/tutorial/application-packaging.md) +* [Native Node Modüllerini Kullanma](https://github.com/electron/electron/tree/master/docs/tutorial/using-native-node-modules.md) +* [Ana Süreç(Main Process) Hata ayıklama](https://github.com/electron/electron/tree/master/docs/tutorial/debugging-main-process.md) +* [Selenium ve WebDriver kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-selenium-and-webdriver.md) +* [DevTools Eklentisi](https://github.com/electron/electron/tree/master/docs/tutorial/devtools-extension.md) +* [Pepper Flash Kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-pepper-flash-plugin.md) +* [Widevine CDM Kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-widevine-cdm-plugin.md) +* [CI Sistem Testleri (Travis, Jenkins)](https://github.com/electron/electron/tree/master/docs/tutorial/testing-on-headless-ci.md) ## Eğitimler -* [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](https://github.com/electron/electron/tree/master/docs/tutorial/quick-start.md) +* [Desktop Environment Integration](https://github.com/electron/electron/tree/master/docs/tutorial/desktop-environment-integration.md) +* [Online/Offline Event Detection](https://github.com/electron/electron/tree/master/docs/tutorial/online-offline-events.md) ## API Kaynakları -* [Synopsis](api/synopsis.md) -* [Process Object](api/process.md) -* [Desteklenen Chrome Komut Satırı Anahtarları](api/chrome-command-line-switches.md) -* [Environment Değişkenleri](api/environment-variables.md) +* [Synopsis](https://github.com/electron/electron/tree/master/docs/api/synopsis.md) +* [Process Object](https://github.com/electron/electron/tree/master/docs/api/process.md) +* [Desteklenen Chrome Komut Satırı Anahtarları](https://github.com/electron/electron/tree/master/docs/api/chrome-command-line-switches.md) +* [Environment Değişkenleri](https://github.com/electron/electron/tree/master/docs/api/environment-variables.md) ### Özel DOM Elementleri: * [`File` Nesnesi](api/file-object.md) -* [`` Etiketi](api/web-view-tag.md) -* [`window.open` Fonksiyonu](api/window-open.md) +* [`` Etiketi](https://github.com/electron/electron/tree/master/docs/api/web-view-tag.md) +* [`window.open` Fonksiyonu](https://github.com/electron/electron/tree/master/docs/api/window-open.md) ### Ana Süreç(Main Process) Modülleri: -* [app](api/app.md) -* [autoUpdater](api/auto-updater.md) -* [BrowserWindow](api/browser-window.md) -* [contentTracing](api/content-tracing.md) -* [dialog](api/dialog.md) -* [globalShortcut](api/global-shortcut.md) -* [ipcMain](api/ipc-main.md) -* [Menu](api/menu.md) -* [MenuItem](api/menu-item.md) -* [powerMonitor](api/power-monitor.md) -* [powerSaveBlocker](api/power-save-blocker.md) -* [protocol](api/protocol.md) -* [session](api/session.md) -* [webContents](api/web-contents.md) -* [Tray](api/tray.md) +* [app](https://github.com/electron/electron/tree/master/docs/api/app.md) +* [autoUpdater](https://github.com/electron/electron/tree/master/docs/api/auto-updater.md) +* [BrowserWindow](https://github.com/electron/electron/tree/master/docs/api/browser-window.md) +* [contentTracing](https://github.com/electron/electron/tree/master/docs/api/content-tracing.md) +* [dialog](https://github.com/electron/electron/tree/master/docs/api/dialog.md) +* [globalShortcut](https://github.com/electron/electron/tree/master/docs/api/global-shortcut.md) +* [ipcMain](https://github.com/electron/electron/tree/master/docs/api/ipc-main.md) +* [Menu](https://github.com/electron/electron/tree/master/docs/api/menu.md) +* [MenuItem](https://github.com/electron/electron/tree/master/docs/api/menu-item.md) +* [powerMonitor](https://github.com/electron/electron/tree/master/docs/api/power-monitor.md) +* [powerSaveBlocker](https://github.com/electron/electron/tree/master/docs/api/power-save-blocker.md) +* [protocol](https://github.com/electron/electron/tree/master/docs/api/protocol.md) +* [session](https://github.com/electron/electron/tree/master/docs/api/session.md) +* [webContents](https://github.com/electron/electron/tree/master/docs/api/web-contents.md) +* [Tray](https://github.com/electron/electron/tree/master/docs/api/tray.md) ### Renderer Process Modülelri (Web Page): -* [desktopCapturer](api/desktop-capturer.md) -* [ipcRenderer](api/ipc-renderer.md) -* [remote](api/remote.md) -* [webFrame](api/web-frame.md) +* [desktopCapturer](https://github.com/electron/electron/tree/master/docs/api/desktop-capturer.md) +* [ipcRenderer](https://github.com/electron/electron/tree/master/docs/api/ipc-renderer.md) +* [remote](https://github.com/electron/electron/tree/master/docs/api/remote.md) +* [webFrame](https://github.com/electron/electron/tree/master/docs/api/web-frame.md) ### Her İki Süreç İçin Geçerli Modüller: -* [clipboard](api/clipboard.md) -* [crashReporter](api/crash-reporter.md) -* [nativeImage](api/native-image.md) -* [screen](api/screen.md) -* [shell](api/shell.md) +* [clipboard](https://github.com/electron/electron/tree/master/docs/api/clipboard.md) +* [crashReporter](https://github.com/electron/electron/tree/master/docs/api/crash-reporter.md) +* [nativeImage](https://github.com/electron/electron/tree/master/docs/api/native-image.md) +* [screen](https://github.com/electron/electron/tree/master/docs/api/screen.md) +* [shell](https://github.com/electron/electron/tree/master/docs/api/shell.md) ## Geliştirme -* [Kodlama Stili](development/coding-style.md) -* [Kaynak Kod Dizin Yapısı](development/source-code-directory-structure.md) -* [NW.js(node-webkit adıyla bilinen) İle Arasındaki Teknik Farklılıklar](development/atom-shell-vs-node-webkit.md) -* [Build Sisyem Genel Bakış](development/build-system-overview.md) -* [(OS X) Build Komutları](development/build-instructions-osx.md) -* [(Windows) Build Komutları](development/build-instructions-windows.md) -* [(Linux) Build Komutları](development/build-instructions-linux.md) -* [(Windows) Hata Ayıklama Komutları](development/debug-instructions-windows.md) -* [Simge Sunucusu(Symbol Server) Hata Ayıklama Kurulumu](development/setting-up-symbol-server.md) +* [Kodlama Stili](https://github.com/electron/electron/tree/master/docs/development/coding-style.md) +* [Kaynak Kod Dizin Yapısı](https://github.com/electron/electron/tree/master/docs/development/source-code-directory-structure.md) +* [NW.js(node-webkit adıyla bilinen) İle Arasındaki Teknik Farklılıklar](https://github.com/electron/electron/tree/master/docs/development/atom-shell-vs-node-webkit.md) +* [Build Sisyem Genel Bakış](https://github.com/electron/electron/tree/master/docs/development/build-system-overview.md) +* [(OS X) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-osx.md) +* [(Windows) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-windows.md) +* [(Linux) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-linux.md) +* [(Windows) Hata Ayıklama Komutları](https://github.com/electron/electron/tree/master/docs/development/debug-instructions-windows.md) +* [Simge Sunucusu(Symbol Server) Hata Ayıklama Kurulumu](https://github.com/electron/electron/tree/master/docs/development/setting-up-symbol-server.md) diff --git a/docs-translations/tr-TR/api/accelerator.md b/docs-translations/tr-TR/api/accelerator.md new file mode 100644 index 00000000000..9105e5c6e46 --- /dev/null +++ b/docs-translations/tr-TR/api/accelerator.md @@ -0,0 +1,49 @@ +# Hızlandırıcı + +> Kısayol Tanımlama. + +Hızlandırıcılar `+` karakteriyle birden fazla niteleyici ile kombinlenebilir. + +Örnek: + +* `CommandOrControl+A` +* `CommandOrControl+Shift+Z` + +## Platform bilgileri + +Linux ve Windows'ta `Command` tuşu herhangi bir etki göstermez. Bunun yerine +`CommandOrControl` niteleyicisini kullanın. Bu işlem OS X'te `Command`, +Linux ve Windows'ta `Control` tuşunun işlevini sağlar. `Alt` ise tüm platformlarda mevcuttur. + +`Super` tuşu Windows ve Linux'te `Windows` tuşuna, OS X'te ise `Cmd` tuşuna eşleştirilmiştir. + +## Mevcut düzenleyiciler + +* `Command` (ya da kısa tanım için `Cmd`) +* `Control` (ya da kısa tanım için `Ctrl`) +* `CommandOrControl` (ya da kısa tanım için `CmdOrCtrl`) +* `Alt` +* `Option` +* `AltGr` +* `Shift` +* `Super` + +## Mevcut tuş kodları + +* `0`dan `9`a +* `A`dan `Z`ye +* `F1`dan `F24`e +* Noktalama işaretleri `~`, `!`, `@`, `#`, `$`, vb. +* `Plus` +* `Space` +* `Backspace` +* `Delete` +* `Insert` +* `Return` (ya da `Enter`) +* `Up`, `Down`, `Left` ve `Right` +* `Home` ve `End` +* `PageUp` ve `PageDown` +* `Escape` (ya da kısa tanım için `Esc`) +* `VolumeUp`, `VolumeDown` ve `VolumeMute` +* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` ve `MediaPlayPause` +* `PrintScreen` diff --git a/docs-translations/tr-TR/api/file-object.md b/docs-translations/tr-TR/api/file-object.md new file mode 100644 index 00000000000..a99bdb329c5 --- /dev/null +++ b/docs-translations/tr-TR/api/file-object.md @@ -0,0 +1,29 @@ +# `File` nesnesi + +> Dosya ve dosya sistemlerinde HTML5 `File` nesnesini native olarak çalışır. + +DOM Dosya arayüzü HTML5 dosya API'sini kullanarak kullanıcılara doğrudan native dosyalar üzerinde çalışmasına olanak sağlar. Electron'da `File` arayüzü için `path` özelliğini eklemiştir. + +`dragged-onto-the-app`'dan tam dosya yolu alma örneği: + +```html +
+ Dosyalarınızı buraya sürükleyin +
+ + +``` diff --git a/docs-translations/tr-TR/styleguide.md b/docs-translations/tr-TR/styleguide.md index d264600f0d5..5e8f7524072 100644 --- a/docs-translations/tr-TR/styleguide.md +++ b/docs-translations/tr-TR/styleguide.md @@ -68,7 +68,7 @@ of argument is notated by either the common types: [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) -or a custom type like Electron's [`webContent`](api/web-content.md). +or a custom type like Electron's [`webContent`](https://github.com/electron/electron/tree/master/docs/api/web-content.md). ### Events From 83af5de572993d98395385bac932008052bb5ba5 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 29 Apr 2016 10:32:33 +0900 Subject: [PATCH 0638/1265] :memo: Small fixes [ci skip] --- README-ko.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README-ko.md b/README-ko.md index 706a5556df9..4da9eb3f3f2 100644 --- a/README-ko.md +++ b/README-ko.md @@ -5,9 +5,9 @@ [![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron#info=devDependencies) [![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/) -### [Electron](https://github.com/electron/electron/) 한국어 참조문서 +### [Electron](https://github.com/electron/electron/) 한국어 참조 문서 -:zap: *프레임워크 이름이 Atom Shell에서 Electron으로 변경되었습니다* :zap: +:zap: *이전까지 Atom Shell로 불렸지만, Electron으로 변경되었습니다* :zap: Electron 프레임워크는 JavaScript, HTML 그리고 CSS를 사용하여 Cross-Platform 데스크톱 어플리케이션을 개발할 수 있도록 해주는 프레임워크입니다. @@ -56,7 +56,7 @@ npm install electron-prebuilt --save-dev - [스페인어](https://github.com/electron/electron/tree/master/docs-translations/es) - [중국어 간체](https://github.com/electron/electron/tree/master/docs-translations/zh-CN) - [중국어 번체](https://github.com/electron/electron/tree/master/docs-translations/zh-TW) -- [터키의](https://github.com/electron/electron/tree/master/docs-translations/tr-TR) +- [터키어](https://github.com/electron/electron/tree/master/docs-translations/tr-TR) - [우크라이나어](https://github.com/electron/electron/tree/master/docs-translations/uk-UA) - [러시아어](https://github.com/electron/electron/tree/master/docs-translations/ru-RU) - [프랑스어](https://github.com/electron/electron/tree/master/docs-translations/fr-FR) From 66853344c0fdf1c8bcea50bd58a95e4a94b63575 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 29 Apr 2016 20:20:52 +0900 Subject: [PATCH 0639/1265] Make sure the userData directory is created before ready event --- atom/browser/browser.cc | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index b3c7a59e08b..093209ef7c4 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -9,7 +9,10 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" +#include "base/files/file_util.h" #include "base/message_loop/message_loop.h" +#include "base/path_service.h" +#include "brightray/browser/brightray_paths.h" namespace atom { @@ -139,6 +142,11 @@ void Browser::WillFinishLaunching() { } void Browser::DidFinishLaunching() { + // Make sure the userData directory is created. + base::FilePath user_data; + if (PathService::Get(brightray::DIR_USER_DATA, &user_data)) + base::CreateDirectoryAndGetError(user_data, nullptr); + is_ready_ = true; FOR_EACH_OBSERVER(BrowserObserver, observers_, OnFinishLaunching()); } From edb73fb7346d5abc31cbff4d991f2cf89b86b62f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 29 Apr 2016 19:55:59 +0900 Subject: [PATCH 0640/1265] Bump v0.37.8 --- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- electron.gyp | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 8cfb6368891..9d04617b209 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 0.37.7 + 0.37.8 CFBundleShortVersionString - 0.37.7 + 0.37.8 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index bcd4a829369..9f74c14d446 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,37,7,0 - PRODUCTVERSION 0,37,7,0 + FILEVERSION 0,37,8,0 + PRODUCTVERSION 0,37,8,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "0.37.7" + VALUE "FileVersion", "0.37.8" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "0.37.7" + VALUE "ProductVersion", "0.37.8" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index dab2966bb99..4ce73bc0aee 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 0 #define ATOM_MINOR_VERSION 37 -#define ATOM_PATCH_VERSION 7 +#define ATOM_PATCH_VERSION 8 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/electron.gyp b/electron.gyp index e6134df117b..66ff2fd5baf 100644 --- a/electron.gyp +++ b/electron.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '0.37.7', + 'version%': '0.37.8', }, 'includes': [ 'filenames.gypi', diff --git a/package.json b/package.json index aa7ca37e5eb..7d40098f099 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "0.37.7", + "version": "0.37.8", "devDependencies": { "asar": "^0.11.0", "request": "*", From 2f71d6afe000fc61d2c9b5c56b42815ea3a3df86 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 29 Apr 2016 13:17:50 -0700 Subject: [PATCH 0641/1265] update quick-start code to match quick-start repo --- docs/tutorial/quick-start.md | 65 ++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 25 deletions(-) diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md index ddbda378244..3a1b7a2d8ac 100644 --- a/docs/tutorial/quick-start.md +++ b/docs/tutorial/quick-start.md @@ -80,45 +80,60 @@ The `main.js` should create windows and handle system events, a typical example being: ```javascript -'use strict'; - -const electron = require('electron'); -const app = electron.app; // Module to control application life. -const BrowserWindow = electron.BrowserWindow; // Module to create native browser window. +const electron = require('electron') +// Module to control application life. +const app = electron.app +// Module to create native browser window. +const BrowserWindow = electron.BrowserWindow // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. -var mainWindow = null; +let mainWindow -// Quit when all windows are closed. -app.on('window-all-closed', function() { - // On OS X it is common for applications and their menu bar - // to stay active until the user quits explicitly with Cmd + Q - if (process.platform != 'darwin') { - app.quit(); - } -}); - -// This method will be called when Electron has finished -// initialization and is ready to create browser windows. -app.on('ready', function() { +function createWindow () { // Create the browser window. - mainWindow = new BrowserWindow({width: 800, height: 600}); + mainWindow = new BrowserWindow({width: 800, height: 600}) // and load the index.html of the app. - mainWindow.loadURL('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html') // Open the DevTools. - mainWindow.webContents.openDevTools(); + mainWindow.webContents.openDevTools() // Emitted when the window is closed. - mainWindow.on('closed', function() { + mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. - mainWindow = null; - }); -}); + mainWindow = null + }) +} + +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +// Some APIs can only be used after this event occurs. +app.on('ready', createWindow) + +// Quit when all windows are closed. +app.on('window-all-closed', function () { + // On OS X it is common for applications and their menu bar + // to stay active until the user quits explicitly with Cmd + Q + if (process.platform !== 'darwin') { + app.quit() + } +}) + +app.on('activate', function () { + // On OS X it's common to re-create a window in the app when the + // dock icon is clicked and there are no other windows open. + if (mainWindow === null) { + createWindow() + } +}) + +// In this file you can include the rest of your app's specific main process +// code. You can also put them in separate files and require them here. + ``` Finally the `index.html` is the web page you want to show: From 95476a81ae0737683b4fb4496b28de4dfcd27e2d Mon Sep 17 00:00:00 2001 From: rhedshi Date: Fri, 29 Apr 2016 13:28:41 -0700 Subject: [PATCH 0642/1265] Update mac-app-store-submission-guide.md --- docs/tutorial/mac-app-store-submission-guide.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index 404dcb80efb..15b6142b57a 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -65,8 +65,8 @@ And then sign your app with the following script: # Name of your app. APP="YourApp" -# The path of you app to sign. -APP_PATH="/path/to/YouApp.app" +# The path of your app to sign. +APP_PATH="/path/to/YourApp.app" # The path to the location you want to put the signed package. RESULT_PATH="~/Desktop/$APP.pkg" # The name of certificates you requested. From 0c9c1229e3a87fdab80a0fbc991d2dd24cede763 Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 29 Apr 2016 13:32:00 -0700 Subject: [PATCH 0643/1265] describe electron-prebuilt and link to it --- docs/tutorial/quick-start.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md index ddbda378244..c2b759a0491 100644 --- a/docs/tutorial/quick-start.md +++ b/docs/tutorial/quick-start.md @@ -147,8 +147,11 @@ working as expected. ### electron-prebuilt -If you've installed `electron-prebuilt` globally with `npm`, then you will only -need to run the following in your app's source directory: +[`electron-prebuilt`](https://github.com/electron-userland/electron-prebuilt) is +an `npm` module that contains pre-compiled versions of Electron. + +If you've installed it globally with `npm`, then you will only need to run the +following in your app's source directory: ```bash electron . From 92606579d3af5b23b79161d889a795ac13d8fb77 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 17:32:25 -0700 Subject: [PATCH 0644/1265] Generalize this mate converter for reuse. --- atom/common/api/atom_api_crash_reporter.cc | 19 +--------- .../string_map_converter.cc | 37 +++++++++++++++++++ .../string_map_converter.h | 28 ++++++++++++++ filenames.gypi | 2 + 4 files changed, 68 insertions(+), 18 deletions(-) create mode 100644 atom/common/native_mate_converters/string_map_converter.cc create mode 100644 atom/common/native_mate_converters/string_map_converter.h diff --git a/atom/common/api/atom_api_crash_reporter.cc b/atom/common/api/atom_api_crash_reporter.cc index e1932ad7f5f..5db1461f88c 100644 --- a/atom/common/api/atom_api_crash_reporter.cc +++ b/atom/common/api/atom_api_crash_reporter.cc @@ -6,6 +6,7 @@ #include #include "atom/common/crash_reporter/crash_reporter.h" +#include "atom/common/native_mate_converters/string_map_converter.h" #include "base/bind.h" #include "native_mate/dictionary.h" @@ -15,24 +16,6 @@ using crash_reporter::CrashReporter; namespace mate { -template<> -struct Converter > { - static bool FromV8(v8::Isolate* isolate, - v8::Local val, - std::map* out) { - if (!val->IsObject()) - return false; - - v8::Local dict = val->ToObject(); - v8::Local keys = dict->GetOwnPropertyNames(); - for (uint32_t i = 0; i < keys->Length(); ++i) { - v8::Local key = keys->Get(i); - (*out)[V8ToString(key)] = V8ToString(dict->Get(key)); - } - return true; - } -}; - template<> struct Converter { static v8::Local ToV8(v8::Isolate* isolate, diff --git a/atom/common/native_mate_converters/string_map_converter.cc b/atom/common/native_mate_converters/string_map_converter.cc new file mode 100644 index 00000000000..dce3c387f0e --- /dev/null +++ b/atom/common/native_mate_converters/string_map_converter.cc @@ -0,0 +1,37 @@ +// Copyright (c) 2014 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/common/native_mate_converters/string_map_converter.h" + +namespace mate { + +bool Converter>::FromV8(v8::Isolate* isolate, + v8::Local val, + std::map* out) { + + if (!val->IsObject()) + return false; + + v8::Local dict = val->ToObject(); + v8::Local keys = dict->GetOwnPropertyNames(); + for (uint32_t i = 0; i < keys->Length(); ++i) { + v8::Local key = keys->Get(i); + (*out)[V8ToString(key)] = V8ToString(dict->Get(key)); + } + return true; +} + +v8::Local Converter>::ToV8(v8::Isolate* isolate, + const std::map& in) { + + mate::Dictionary dict(isolate, v8::Object::New(isolate)); + + for (auto const &pair : in) { + dict.Set(pair.first, pair.second); + } + + return dict.GetHandle(); +} + +} // namespace mate \ No newline at end of file diff --git a/atom/common/native_mate_converters/string_map_converter.h b/atom/common/native_mate_converters/string_map_converter.h new file mode 100644 index 00000000000..bdab0be2b8a --- /dev/null +++ b/atom/common/native_mate_converters/string_map_converter.h @@ -0,0 +1,28 @@ +// Copyright (c) 2014 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_COMMON_NATIVE_MATE_CONVERTERS_STRING_MAP_CONVERTER_H_ +#define ATOM_COMMON_NATIVE_MATE_CONVERTERS_STRING_MAP_CONVERTER_H_ + +#include +#include + +#include "native_mate/converter.h" +#include "native_mate/dictionary.h" + +namespace mate { + +template<> +struct Converter> { + static bool FromV8(v8::Isolate* isolate, + v8::Local val, + std::map* out); + + static v8::Local ToV8(v8::Isolate* isolate, + const std::map& in); +}; + +} // namespace mate + +#endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_STRING_MAP_CONVERTER_H_ \ No newline at end of file diff --git a/filenames.gypi b/filenames.gypi index 1c213949756..783b5cb33d0 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -361,6 +361,8 @@ 'atom/common/native_mate_converters/image_converter.h', 'atom/common/native_mate_converters/net_converter.cc', 'atom/common/native_mate_converters/net_converter.h', + 'atom/common/native_mate_converters/string_map_converter.cc', + 'atom/common/native_mate_converters/string_map_converter.h', 'atom/common/native_mate_converters/string16_converter.h', 'atom/common/native_mate_converters/v8_value_converter.cc', 'atom/common/native_mate_converters/v8_value_converter.h', From 6df4bb176dce4903e105690deb54627ad8c4d1d0 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 17:35:07 -0700 Subject: [PATCH 0645/1265] Implement app.setUserActivity(type, userInfo). --- atom/browser/api/atom_api_app.cc | 1 + atom/browser/browser.h | 4 ++++ atom/browser/browser_mac.mm | 17 +++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 304e53a5554..8e7d8c3034a 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -460,6 +460,7 @@ void App::BuildPrototype( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) + .SetMethod("setUserActivity", base::Bind(&Browser::SetUserActivity, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 8329b14bc2c..b0dd829ff4d 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -7,6 +7,7 @@ #include #include +#include #include "base/macros.h" #include "base/compiler_specific.h" @@ -92,6 +93,9 @@ class Browser : public WindowListObserver { // Show the application. void Show(); + // Creates an activity and sets it as the one currently in use. + void SetUserActivity(const std::string& type, const std::map& user_info); + // Bounce the dock icon. enum BounceType { BOUNCE_CRITICAL = 0, diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index c10369a2e7a..627ed65dccd 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -87,6 +87,23 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { void Browser::SetAppUserModelID(const base::string16& name) { } +void Browser::SetUserActivity(const std::string& type, const std::map& user_info) { + NSString* type_ns = [NSString stringWithUTF8String:type.c_str()]; + NSUserActivity *user_activity = [[NSUserActivity alloc] initWithActivityType:type_ns]; + + NSMutableArray* user_info_args = [[NSMutableArray alloc] init]; + for (auto const &pair : user_info) { + NSString* key_ns = [NSString stringWithUTF8String:pair.first.c_str()]; + NSString* value_ns = [NSString stringWithUTF8String:pair.second.c_str()]; + + [user_info_args addObject:key_ns]; + [user_info_args addObject:value_ns]; + } + + user_activity.userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:user_info_args, nil]; + [user_activity becomeCurrent]; +} + std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } From c20acb0361a4915e800d3e3281046f2199b383f9 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 17:36:04 -0700 Subject: [PATCH 0646/1265] Implement a "continue-activity" event on app for resuming from hand-off. --- atom/browser/api/atom_api_app.cc | 5 +++++ atom/browser/api/atom_api_app.h | 2 ++ atom/browser/browser.cc | 11 +++++++++++ atom/browser/browser.h | 3 +++ atom/browser/browser_observer.h | 6 ++++++ 5 files changed, 27 insertions(+) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 8e7d8c3034a..fb258e2f483 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -20,6 +20,7 @@ #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/value_converter.h" +#include "atom/common/native_mate_converters/string_map_converter.h" #include "atom/common/node_includes.h" #include "atom/common/options_switches.h" #include "base/command_line.h" @@ -249,6 +250,10 @@ void App::OnFinishLaunching() { Emit("ready"); } +void App::OnContinueUserActivity(bool* handled, const std::string& type, const std::map& user_info) { + *handled = Emit("continue-activity", type, user_info); +} + void App::OnLogin(LoginHandler* login_handler) { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index c99d5df7793..882f05376ca 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -6,6 +6,7 @@ #define ATOM_BROWSER_API_ATOM_API_APP_H_ #include +#include #include "atom/browser/api/event_emitter.h" #include "atom/browser/atom_browser_client.h" @@ -71,6 +72,7 @@ class App : public AtomBrowserClient::Delegate, void OnWillFinishLaunching() override; void OnFinishLaunching() override; void OnLogin(LoginHandler* login_handler) override; + void OnContinueUserActivity(bool* handled, const std::string& type, const std::map& user_info) override; // content::ContentBrowserClient: void AllowCertificateError( diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 093209ef7c4..94f3948c4a6 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -137,6 +137,17 @@ void Browser::Activate(bool has_visible_windows) { OnActivate(has_visible_windows)); } +#if defined(OS_MACOSX) +bool Browser::ContinueUserActivity(const std::string& type, const std::map& user_info) { + bool handled = false; + FOR_EACH_OBSERVER(BrowserObserver, + observers_, + OnContinueUserActivity(&handled, type, user_info)); + + return handled; +} +#endif + void Browser::WillFinishLaunching() { FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWillFinishLaunching()); } diff --git a/atom/browser/browser.h b/atom/browser/browser.h index b0dd829ff4d..4fb140e79e8 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -96,6 +96,9 @@ class Browser : public WindowListObserver { // Creates an activity and sets it as the one currently in use. void SetUserActivity(const std::string& type, const std::map& user_info); + // Resumes an activity via hand-off. + bool ContinueUserActivity(const std::string& type, const std::map& user_info); + // Bounce the dock icon. enum BounceType { BOUNCE_CRITICAL = 0, diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index f6d76bc13fb..11346f36875 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -6,6 +6,7 @@ #define ATOM_BROWSER_BROWSER_OBSERVER_H_ #include +#include namespace atom { @@ -45,6 +46,11 @@ class BrowserObserver { // The browser requests HTTP login. virtual void OnLogin(LoginHandler* login_handler) {} + // The browser wants to resume a user activity via handoff. (OS X only) + virtual void OnContinueUserActivity(bool* handled, + const std::string& type, + const std::map& user_info) {} + protected: virtual ~BrowserObserver() {} }; From 3a9a1d35d7356c45bb292d3c176520d8c25119d2 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 17:37:01 -0700 Subject: [PATCH 0647/1265] Add the AppDelegate override for restoring from hand-off, and fire the app event. --- atom/browser/mac/atom_application_delegate.mm | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index 7662162ab61..33aa47ce240 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -59,4 +59,24 @@ return flag; } +- (BOOL)application:(NSApplication *)sender +continueUserActivity:(NSUserActivity *)userActivity + restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { + std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); + + std::map user_info; + + NSArray* keys = [userActivity.userInfo allKeys]; + for (NSString* key in keys) + { + NSString* value = [userActivity.userInfo objectForKey:key]; + std::string key_str(base::SysNSStringToUTF8(key)); + std::string value_str(base::SysNSStringToUTF8(value)); + user_info[key_str] = value_str; + } + + atom::Browser* browser = atom::Browser::Get(); + return browser->ContinueUserActivity(activity_type, user_info) ? YES : NO; +} + @end From 9f99ba3b73cf2fab0cf9245b739f64f406a2b90e Mon Sep 17 00:00:00 2001 From: Zeke Sikelianos Date: Fri, 29 Apr 2016 18:35:02 -0700 Subject: [PATCH 0648/1265] update all references to old atom-log bracket notation --- docs-translations/es/api/process.md | 4 ++-- docs-translations/es/tutorial/quick-start.md | 2 +- docs-translations/jp/api/process.md | 4 ++-- docs-translations/ko-KR/api/process.md | 4 ++-- docs-translations/ko-KR/tutorial/quick-start.md | 2 +- docs-translations/pt-BR/api/process.md | 4 ++-- docs-translations/pt-BR/tutorial/quick-start.md | 2 +- docs-translations/zh-CN/api/process.md | 4 ++-- docs-translations/zh-CN/tutorial/quick-start.md | 2 +- docs-translations/zh-TW/api/process.md | 4 ++-- docs/api/process.md | 4 ++-- spec/api-crash-reporter-spec.js | 2 +- 12 files changed, 19 insertions(+), 19 deletions(-) diff --git a/docs-translations/es/api/process.md b/docs-translations/es/api/process.md index 9e95ba98854..e50a2c1aac6 100644 --- a/docs-translations/es/api/process.md +++ b/docs-translations/es/api/process.md @@ -5,8 +5,8 @@ al node convencional: * `process.type` String - El tipo del proceso puede ser `browser` (ej. proceso principal) o `renderer`. -* `process.versions['electron']` String - Versión de Electron. -* `process.versions['chrome']` String - Versión de Chromium. +* `process.versions.electron` String - Versión de Electron. +* `process.versions.chrome` String - Versión de Chromium. * `process.resourcesPath` String - Ruta al código fuente JavaScript. ## Events diff --git a/docs-translations/es/tutorial/quick-start.md b/docs-translations/es/tutorial/quick-start.md index a760fccad2c..9e65042c503 100644 --- a/docs-translations/es/tutorial/quick-start.md +++ b/docs-translations/es/tutorial/quick-start.md @@ -115,7 +115,7 @@ Finalmente el `index.html` es la página web que mostraremos:

Hello World!

We are using io.js - and Electron . + and Electron . ``` diff --git a/docs-translations/jp/api/process.md b/docs-translations/jp/api/process.md index ea15fc747a2..6ad3c32d76f 100644 --- a/docs-translations/jp/api/process.md +++ b/docs-translations/jp/api/process.md @@ -3,8 +3,8 @@ Electronの`process`オブジェクトは上流nodeの1つから次のような違いがあります。 * `process.type` String - プロセスの種類で、`browser` (例 メインプロセス)または `renderer`を設定できます。 -* `process.versions['electron']` String - Electronのバージョン -* `process.versions['chrome']` String - Chromiumのバージョン +* `process.versions.electron` String - Electronのバージョン +* `process.versions.chrome` String - Chromiumのバージョン * `process.resourcesPath` String - JavaScriptのソースコードのパスを設定します。 * `process.mas` Boolean - Mac app Store用のビルドで、値は`true`です。ほかのビルドの場合は`undefined`です。 diff --git a/docs-translations/ko-KR/api/process.md b/docs-translations/ko-KR/api/process.md index 3cdc10dd78c..a7377a629b2 100644 --- a/docs-translations/ko-KR/api/process.md +++ b/docs-translations/ko-KR/api/process.md @@ -4,8 +4,8 @@ Electron의 `process` 객체는 기존의 node와는 달리 약간의 차이점 * `process.type` String - 프로세스의 타입, `browser` (메인 프로세스) 또는 `renderer`가 됩니다. -* `process.versions['electron']` String - Electron의 버전. -* `process.versions['chrome']` String - Chromium의 버전. +* `process.versions.electron` String - Electron의 버전. +* `process.versions.chrome` String - Chromium의 버전. * `process.resourcesPath` String - JavaScript 소스 코드의 경로. * `process.mas` Boolean - Mac 앱 스토어용 빌드일 때 `true`로 지정됩니다. 다른 빌드일 땐 `undefined`로 지정됩니다. diff --git a/docs-translations/ko-KR/tutorial/quick-start.md b/docs-translations/ko-KR/tutorial/quick-start.md index eb95232a06f..f7eb700d037 100644 --- a/docs-translations/ko-KR/tutorial/quick-start.md +++ b/docs-translations/ko-KR/tutorial/quick-start.md @@ -129,7 +129,7 @@ app.on('ready', function() {

헬로 월드!

이 어플리케이션은 node , Chrome , - Electron 을 사용합니다. + Electron 을 사용합니다. ``` diff --git a/docs-translations/pt-BR/api/process.md b/docs-translations/pt-BR/api/process.md index 1c20e2df118..71502de80d6 100644 --- a/docs-translations/pt-BR/api/process.md +++ b/docs-translations/pt-BR/api/process.md @@ -3,8 +3,8 @@ O objeto `process` no Electron tem as seguintes diferenças do objeto no upstrea * `process.type` String - Tipo de processo, pode ser `browser` (processo principal) ou `renderer`. -* `process.versions['electron']` String - Versão do Electron. -* `process.versions['chrome']` String - Versão do Chromium. +* `process.versions.electron` String - Versão do Electron. +* `process.versions.chrome` String - Versão do Chromium. * `process.resourcesPath` String - Caminho para o código fonte JavaScript. * `process.mas` Boolean - Para build da Mac App Store, este valor é `true`, para outros builds é `undefined`. diff --git a/docs-translations/pt-BR/tutorial/quick-start.md b/docs-translations/pt-BR/tutorial/quick-start.md index 76b128df5d0..6a21123ecf6 100644 --- a/docs-translations/pt-BR/tutorial/quick-start.md +++ b/docs-translations/pt-BR/tutorial/quick-start.md @@ -130,7 +130,7 @@ Finalmente o `index.html` é a página web que você quer mostrar:

Hello World!

Nós estamos usando io.js - e Electron . + e Electron . ``` diff --git a/docs-translations/zh-CN/api/process.md b/docs-translations/zh-CN/api/process.md index 7e8173dfb3b..89a5e02a675 100644 --- a/docs-translations/zh-CN/api/process.md +++ b/docs-translations/zh-CN/api/process.md @@ -4,8 +4,8 @@ Electron 中的 `process` 对象 与 upstream node 中的有以下的不同点: * `process.type` String - 进程类型, 可以是 `browser` (i.e. main process) 或 `renderer`. -* `process.versions['electron']` String - Electron的版本. -* `process.versions['chrome']` String - Chromium的版本. +* `process.versions.electron` String - Electron的版本. +* `process.versions.chrome` String - Chromium的版本. * `process.resourcesPath` String - JavaScript源代码路径. * `process.mas` Boolean - 在Mac App Store 创建, 它的值为 `true`, 在其它的地方值为 `undefined`. diff --git a/docs-translations/zh-CN/tutorial/quick-start.md b/docs-translations/zh-CN/tutorial/quick-start.md index 8bdcc05cb02..d267d314605 100644 --- a/docs-translations/zh-CN/tutorial/quick-start.md +++ b/docs-translations/zh-CN/tutorial/quick-start.md @@ -89,7 +89,7 @@ app.on('ready', function() {

Hello World!

We are using io.js - and Electron . + and Electron . ``` diff --git a/docs-translations/zh-TW/api/process.md b/docs-translations/zh-TW/api/process.md index a4f45352b9c..ba3dd245f7a 100644 --- a/docs-translations/zh-TW/api/process.md +++ b/docs-translations/zh-TW/api/process.md @@ -3,8 +3,8 @@ 在 Electron 裡的 `process` 物件具有以下幾個與 upstream node 的不同點: * `process.type` String - Process 的型態,可以是 `browser` (i.e. 主行程) 或 `renderer`. -* `process.versions['electron']` String - Electron 的版本 -* `process.versions['chrome']` String - Chromium 的版本 +* `process.versions.electron` String - Electron 的版本 +* `process.versions.chrome` String - Chromium 的版本 * `process.resourcesPath` String - JavaScript 源碼的路徑 # 方法 (Methods) diff --git a/docs/api/process.md b/docs/api/process.md index 79bd9bd5572..1becdd46df0 100644 --- a/docs/api/process.md +++ b/docs/api/process.md @@ -7,8 +7,8 @@ upstream node: * `process.type` String - Process's type, can be `browser` (i.e. main process) or `renderer`. -* `process.versions['electron']` String - Version of Electron. -* `process.versions['chrome']` String - Version of Chromium. +* `process.versions.electron` String - Version of Electron. +* `process.versions.chrome` String - Version of Chromium. * `process.resourcesPath` String - Path to JavaScript source code. * `process.mas` Boolean - For Mac App Store build, this value is `true`, for other builds it is `undefined`. diff --git a/spec/api-crash-reporter-spec.js b/spec/api-crash-reporter-spec.js index 2e49fdc36c5..e5a3223eed8 100644 --- a/spec/api-crash-reporter-spec.js +++ b/spec/api-crash-reporter-spec.js @@ -44,7 +44,7 @@ describe('crash-reporter module', function () { if (called) return called = true assert.equal(fields['prod'], 'Electron') - assert.equal(fields['ver'], process.versions['electron']) + assert.equal(fields['ver'], process.versions.electron) assert.equal(fields['process_type'], 'renderer') assert.equal(fields['platform'], process.platform) assert.equal(fields['extra1'], 'extra1') From 88805ec7e27884e05538e7043c883bef594d4b3a Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 22:05:36 -0700 Subject: [PATCH 0649/1265] Make the Linter happy. --- atom/browser/api/atom_api_app.cc | 7 +++++-- atom/browser/api/atom_api_app.h | 4 +++- atom/browser/browser.cc | 10 ++++++---- atom/browser/browser.h | 8 +++++--- atom/browser/browser_observer.h | 4 ++-- .../native_mate_converters/string_map_converter.cc | 9 ++++----- .../native_mate_converters/string_map_converter.h | 4 ++-- 7 files changed, 27 insertions(+), 19 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index fb258e2f483..0e2a6e55626 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -250,7 +250,9 @@ void App::OnFinishLaunching() { Emit("ready"); } -void App::OnContinueUserActivity(bool* handled, const std::string& type, const std::map& user_info) { +void App::OnContinueUserActivity(bool* handled, + const std::string& type, + const std::map& user_info) { *handled = Emit("continue-activity", type, user_info); } @@ -465,7 +467,8 @@ void App::BuildPrototype( #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) - .SetMethod("setUserActivity", base::Bind(&Browser::SetUserActivity, browser)) + .SetMethod("setUserActivity", + base::Bind(&Browser::SetUserActivity, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 882f05376ca..3a13322cc08 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -72,7 +72,9 @@ class App : public AtomBrowserClient::Delegate, void OnWillFinishLaunching() override; void OnFinishLaunching() override; void OnLogin(LoginHandler* login_handler) override; - void OnContinueUserActivity(bool* handled, const std::string& type, const std::map& user_info) override; + void OnContinueUserActivity(bool* handled, + const std::string& type, + const std::map& user_info) override; // content::ContentBrowserClient: void AllowCertificateError( diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 94f3948c4a6..15980190030 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -138,12 +138,14 @@ void Browser::Activate(bool has_visible_windows) { } #if defined(OS_MACOSX) -bool Browser::ContinueUserActivity(const std::string& type, const std::map& user_info) { +bool Browser::ContinueUserActivity(const std::string& type, + const std::map& user_info) { bool handled = false; - FOR_EACH_OBSERVER(BrowserObserver, - observers_, + FOR_EACH_OBSERVER(BrowserObserver, + observers_, OnContinueUserActivity(&handled, type, user_info)); - + return handled; } #endif diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 4fb140e79e8..14f94a061e4 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -94,10 +94,12 @@ class Browser : public WindowListObserver { void Show(); // Creates an activity and sets it as the one currently in use. - void SetUserActivity(const std::string& type, const std::map& user_info); - + void SetUserActivity(const std::string& type, + const std::map& user_info); + // Resumes an activity via hand-off. - bool ContinueUserActivity(const std::string& type, const std::map& user_info); + bool ContinueUserActivity(const std::string& type, + const std::map& user_info); // Bounce the dock icon. enum BounceType { diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index 11346f36875..977f1a8dc12 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -48,8 +48,8 @@ class BrowserObserver { // The browser wants to resume a user activity via handoff. (OS X only) virtual void OnContinueUserActivity(bool* handled, - const std::string& type, - const std::map& user_info) {} + const std::string& type, + const std::map& user_info) {} protected: virtual ~BrowserObserver() {} diff --git a/atom/common/native_mate_converters/string_map_converter.cc b/atom/common/native_mate_converters/string_map_converter.cc index dce3c387f0e..475b052ba65 100644 --- a/atom/common/native_mate_converters/string_map_converter.cc +++ b/atom/common/native_mate_converters/string_map_converter.cc @@ -6,10 +6,9 @@ namespace mate { -bool Converter>::FromV8(v8::Isolate* isolate, +bool Converter>::FromV8(v8::Isolate* isolate, v8::Local val, std::map* out) { - if (!val->IsObject()) return false; @@ -22,9 +21,9 @@ bool Converter>::FromV8(v8::Isolate* isolate, return true; } -v8::Local Converter>::ToV8(v8::Isolate* isolate, +v8::Local Converter>::ToV8( + v8::Isolate* isolate, const std::map& in) { - mate::Dictionary dict(isolate, v8::Object::New(isolate)); for (auto const &pair : in) { @@ -34,4 +33,4 @@ v8::Local Converter>::ToV8(v8::Iso return dict.GetHandle(); } -} // namespace mate \ No newline at end of file +} // namespace mate diff --git a/atom/common/native_mate_converters/string_map_converter.h b/atom/common/native_mate_converters/string_map_converter.h index bdab0be2b8a..54e4297714c 100644 --- a/atom/common/native_mate_converters/string_map_converter.h +++ b/atom/common/native_mate_converters/string_map_converter.h @@ -20,9 +20,9 @@ struct Converter> { std::map* out); static v8::Local ToV8(v8::Isolate* isolate, - const std::map& in); + const std::map& in); }; } // namespace mate -#endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_STRING_MAP_CONVERTER_H_ \ No newline at end of file +#endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_STRING_MAP_CONVERTER_H_ From 195940292d2ba649e9ea840119fb5d84bdba4ce8 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 22:08:19 -0700 Subject: [PATCH 0650/1265] This is preventDefault by convention. --- atom/browser/api/atom_api_app.cc | 4 ++-- atom/browser/api/atom_api_app.h | 2 +- atom/browser/browser.cc | 6 +++--- atom/browser/browser_observer.h | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 0e2a6e55626..ec6cdce417c 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -250,10 +250,10 @@ void App::OnFinishLaunching() { Emit("ready"); } -void App::OnContinueUserActivity(bool* handled, +void App::OnContinueUserActivity(bool* prevent_default, const std::string& type, const std::map& user_info) { - *handled = Emit("continue-activity", type, user_info); + *prevent_default = Emit("continue-activity", type, user_info); } void App::OnLogin(LoginHandler* login_handler) { diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 3a13322cc08..321230d711e 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -72,7 +72,7 @@ class App : public AtomBrowserClient::Delegate, void OnWillFinishLaunching() override; void OnFinishLaunching() override; void OnLogin(LoginHandler* login_handler) override; - void OnContinueUserActivity(bool* handled, + void OnContinueUserActivity(bool* prevent_default, const std::string& type, const std::map& user_info) override; diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 15980190030..ee2a225246b 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -141,12 +141,12 @@ void Browser::Activate(bool has_visible_windows) { bool Browser::ContinueUserActivity(const std::string& type, const std::map& user_info) { - bool handled = false; + bool prevent_default = false; FOR_EACH_OBSERVER(BrowserObserver, observers_, - OnContinueUserActivity(&handled, type, user_info)); + OnContinueUserActivity(&prevent_default, type, user_info)); - return handled; + return prevent_default; } #endif diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index 977f1a8dc12..4ad001370c0 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -47,7 +47,7 @@ class BrowserObserver { virtual void OnLogin(LoginHandler* login_handler) {} // The browser wants to resume a user activity via handoff. (OS X only) - virtual void OnContinueUserActivity(bool* handled, + virtual void OnContinueUserActivity(bool* prevent_default, const std::string& type, const std::map& user_info) {} From cea1b49db06255745ab1329b78170220825ba473 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Fri, 29 Apr 2016 22:25:09 -0700 Subject: [PATCH 0651/1265] Add some documentation in app.md. --- docs/api/app.md | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index 1f682933d23..04f91b3a904 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -108,8 +108,20 @@ Returns: * `event` Event * `hasVisibleWindows` Boolean -Emitted when the application is activated, which usually happens when clicks on -the applications's dock icon. +Emitted when the application is activated, which usually happens when the user clicks on +the application's dock icon. + +### Event: 'continue-activity' _OS X_ + +Returns: + +* `event` Event +* `type` String - A string identifying the event. Maps to [`NSUserActivity.activityType`](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType). +* `userInfo` Object - Contains app-specific state stored by the activity on another device. + +Emitted during [handoff](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html) when an activity from a different device wants to be +resumed. You should call `event.preventDefault()` if you want to handle this +event. ### Event: 'browser-window-blur' @@ -386,12 +398,12 @@ default protocol handler. ### `app.isDefaultProtocolClient(protocol)` _OS X_ _Windows_ -* `protocol` String - The name of your protocol, without `://`. +* `protocol` String - The name of your protocol, without `://`. This method checks if the current executable is the default handler for a protocol -(aka URI scheme). If so, it will return true. Otherwise, it will return false. +(aka URI scheme). If so, it will return true. Otherwise, it will return false. -**Note:** On OS X, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the OS X machine. +**Note:** On OS X, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the OS X machine. Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally. @@ -482,6 +494,16 @@ app.on('ready', function() { }); ``` +### `app.setUserActivity(type, userInfo)` _OS X_ + +* `type` String - Uniquely identifies the activity. It's recommended to use a +reverse-DNS string. +* `userInfo` Object - Contains app-specific state stored by the activity on +another device. + +Creates an `NSUserActivity` and sets it as the current activity. The activity +is eligible for [handoff](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html) to another device afterward. + ### `app.setAppUserModelId(id)` _Windows_ * `id` String @@ -568,5 +590,5 @@ Sets the `image` associated with this dock icon. [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 -[LSCopyDefaultHandlerForURLScheme]: +[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme From 6756f8c7af799c4a99cc7c9f5d7faaff655fd4d0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 15:38:23 +0900 Subject: [PATCH 0652/1265] Make win32 CI machine run tests --- script/cibuild | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/script/cibuild b/script/cibuild index 59437837aa1..8d21e3a4024 100755 --- a/script/cibuild +++ b/script/cibuild @@ -39,6 +39,7 @@ def main(): if os.environ.has_key('TARGET_ARCH'): target_arch = os.environ['TARGET_ARCH'] + is_appveyor = (os.getenv('APPVEYOR') == 'True') is_travis = (os.getenv('TRAVIS') == 'true') if is_travis and PLATFORM == 'linux': print 'Setup travis CI' @@ -76,7 +77,7 @@ def main(): run_script('upload.py') else: run_script('build.py', ['-c', 'D']) - if PLATFORM != 'win32' and target_arch == 'x64': + if not is_appveyor and target_arch == 'x64': run_script('test.py', ['--ci']) From 8aa88067ca0cef906e7f7bda97239c09335b4fcf Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 17:05:52 +0900 Subject: [PATCH 0653/1265] Do not write to stdout in Electron when running on win32 CI machine This makes Electron crash on CI machine somehow. --- script/cibuild | 5 +++-- script/test.py | 5 +++++ spec/static/main.js | 21 ++++++++++++++------- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/script/cibuild b/script/cibuild index 8d21e3a4024..3a141eac099 100755 --- a/script/cibuild +++ b/script/cibuild @@ -39,7 +39,6 @@ def main(): if os.environ.has_key('TARGET_ARCH'): target_arch = os.environ['TARGET_ARCH'] - is_appveyor = (os.getenv('APPVEYOR') == 'True') is_travis = (os.getenv('TRAVIS') == 'true') if is_travis and PLATFORM == 'linux': print 'Setup travis CI' @@ -76,8 +75,10 @@ def main(): run_script('create-dist.py') run_script('upload.py') else: + if PLATFORM == 'win32': + os.environ['OUTPUT_TO_FILE'] = 'output.log' run_script('build.py', ['-c', 'D']) - if not is_appveyor and target_arch == 'x64': + if target_arch == 'x64': run_script('test.py', ['--ci']) diff --git a/script/test.py b/script/test.py index 28aeac9dc1f..2acf1f7154a 100755 --- a/script/test.py +++ b/script/test.py @@ -32,6 +32,11 @@ def main(): subprocess.check_call([atom_shell, 'spec'] + sys.argv[1:]) + if os.environ.has_key('OUTPUT_TO_FILE'): + output_to_file = os.environ['OUTPUT_TO_FILE'] + with open(output_to_file, 'r') as f: + print f.read() + if __name__ == '__main__': sys.exit(main()) diff --git a/spec/static/main.js b/spec/static/main.js index 84e9ba3da55..025ff394bc6 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -7,8 +7,10 @@ const ipcMain = electron.ipcMain const dialog = electron.dialog const BrowserWindow = electron.BrowserWindow +const fs = require('fs') const path = require('path') const url = require('url') +const util = require('util') var argv = require('yargs') .boolean('ci') @@ -35,13 +37,18 @@ ipcMain.on('message', function (event, arg) { event.sender.send('message', arg) }) -ipcMain.on('console.log', function (event, args) { - console.error.apply(console, args) -}) - -ipcMain.on('console.error', function (event, args) { - console.error.apply(console, args) -}) +// Write output to file if OUTPUT_TO_FILE is defined. +const outputToFile = process.env.OUTPUT_TO_FILE +const print = function (_, args) { + let output = util.format.apply(null, args) + if (outputToFile) { + fs.appendFileSync(outputToFile, output + '\n') + } else { + console.error(output) + } +} +ipcMain.on('console.log', print) +ipcMain.on('console.error', print) ipcMain.on('process.exit', function (event, code) { process.exit(code) From 3dcf69eab3d6deabd26f5c05c8f6e2cc409794af Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 17:17:23 +0900 Subject: [PATCH 0654/1265] Also run tests on 32bit Windows --- script/cibuild | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/cibuild b/script/cibuild index 3a141eac099..7d025b4e82c 100755 --- a/script/cibuild +++ b/script/cibuild @@ -78,7 +78,7 @@ def main(): if PLATFORM == 'win32': os.environ['OUTPUT_TO_FILE'] = 'output.log' run_script('build.py', ['-c', 'D']) - if target_arch == 'x64': + if PLATFORM == 'win32' or target_arch == 'x64': run_script('test.py', ['--ci']) From b68a25835fe68d7a8cab44ad47aabd5e005f7236 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 17:47:29 +0900 Subject: [PATCH 0655/1265] Make sure output is written when test fails --- script/test.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/script/test.py b/script/test.py index 2acf1f7154a..85061db5746 100755 --- a/script/test.py +++ b/script/test.py @@ -30,13 +30,19 @@ def main(): else: atom_shell = os.path.join(SOURCE_ROOT, 'out', config, PROJECT_NAME) - subprocess.check_call([atom_shell, 'spec'] + sys.argv[1:]) + returncode = 0 + try: + subprocess.check_call([atom_shell, 'spec'] + sys.argv[1:]) + except subprocess.CalledProcessError as e: + returncode = e.returncode if os.environ.has_key('OUTPUT_TO_FILE'): output_to_file = os.environ['OUTPUT_TO_FILE'] with open(output_to_file, 'r') as f: print f.read() + return returncode + if __name__ == '__main__': sys.exit(main()) From 2a55d935015e73baaae87dd341ad01ef13b54152 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 17:52:53 +0900 Subject: [PATCH 0656/1265] Remove the output file after testing --- script/test.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/script/test.py b/script/test.py index 85061db5746..5adfd4eed6c 100755 --- a/script/test.py +++ b/script/test.py @@ -4,7 +4,7 @@ import os import subprocess import sys -from lib.util import atom_gyp +from lib.util import atom_gyp, rm_rf SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) @@ -40,6 +40,8 @@ def main(): output_to_file = os.environ['OUTPUT_TO_FILE'] with open(output_to_file, 'r') as f: print f.read() + rm_rf(output_to_file) + return returncode From 214eb0430c823f5196cc5989a6189bd774caa142 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 18:21:18 +0900 Subject: [PATCH 0657/1265] Fix a few failing tests on Windows --- spec/api-browser-window-spec.js | 5 +++-- spec/chromium-spec.js | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/spec/api-browser-window-spec.js b/spec/api-browser-window-spec.js index c364b916c3a..e76821020bd 100644 --- a/spec/api-browser-window-spec.js +++ b/spec/api-browser-window-spec.js @@ -173,11 +173,12 @@ describe('browser-window module', function () { }) it('does not crash in did-fail-provisional-load handler', function (done) { + this.timeout(10000) w.webContents.once('did-fail-provisional-load', function () { - w.loadURL('http://localhost:11111') + w.loadURL('http://127.0.0.1:11111') done() }) - w.loadURL('http://localhost:11111') + w.loadURL('http://127.0.0.1:11111') }) }) diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 1d37d0fe051..706447c00dd 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -97,6 +97,9 @@ describe('chromium feature', function () { if (isCI && process.platform === 'linux') { return } + if (isCI && process.platform === 'win32') { + return + } it('can return labels of enumerated devices', function (done) { navigator.mediaDevices.enumerateDevices().then((devices) => { @@ -327,6 +330,10 @@ describe('chromium feature', function () { }) describe('webgl', function () { + if (isCI && process.platform === 'win32') { + return + } + it('can be get as context in canvas', function () { if (process.platform === 'linux') return From dae63ec4f19b86b2495efb2b154e52d4e7d6b353 Mon Sep 17 00:00:00 2001 From: TyanNN Date: Sat, 30 Apr 2016 13:54:19 +0300 Subject: [PATCH 0658/1265] Translated Quickstart to ru_RU --- .../ru-RU/tutorial/quick-start.md | 225 ++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 docs-translations/ru-RU/tutorial/quick-start.md diff --git a/docs-translations/ru-RU/tutorial/quick-start.md b/docs-translations/ru-RU/tutorial/quick-start.md new file mode 100644 index 00000000000..b18d17c41d4 --- /dev/null +++ b/docs-translations/ru-RU/tutorial/quick-start.md @@ -0,0 +1,225 @@ +# Быстрый старт + +Electron позволяет вам делать приложения для рабочего стола на чистом JavaScript, +предоставляя среду с богатым API. Можете представлять его как Node.js, который +ориентирован на рабочий стол, а не веб сервера. + +Это, однако, не значит, что Electron — лишь привязки к GUI билиотекам. На деле +Electron использует веб-страницы как интерфейс, так что вы можете считать его +небольшим Chroumium браузером, который контролируется с помощью JavaScript. + +### Главный процесс + +В Electron процесс, который запускает `main` из `package.json` называется +__главным процессом__. Скрипт, который работает в главном процессе может +показывать GUI, создавая веб-страницы. + +### Процесс-рендерер + +Так как Electron использует Chromium для показа веб-страниц, +мульти-процессовая архитектура показа страниц Chromium тоже используется. +Каждая веб-страницы в Electron работает в своём собственном процессе, +который называется __процесс-рендерер__. + +В обычных браузерах веб-страницы обычно запускаются в "песочнице" и им недоступны +реальные ресурсы компьютера. Пользователи Electron же могут использовать API +Node.js на страницах, что допускает более низкоуровневую работу с операционной системой. + +### Разница мужду главным процессом и процессом-рендерером + +Главный процесс создаёт веб-страницы используя `BrowserWindow`. Каждый экземпляр +`BrowserWindow` показывает веб-страницу через свой собственный процесс-рендерер. +Если экземпляр `BrowserWindow` уничтожается, то и соответствующий процесс-рендерер тоже +завершается. + +Главный процесс управляет всеми веб-страницами и соответствующими им процессами-редерерами. +Каждый процесс-рендерер изолирован и управляет только своей веб-страницей. + +На веб-страницах не позволяется вызывать нативные API, которые управляют GUI, +потому что это очень опасно и может легко вызвать утечку ресурсов. Если вы хотите +выполнить действия с GUI на странице, процесс-рендерер этой страницы должен +"попросить" главный процесс сделать эти действия. + +В Electron есть несолько способов общения между процессам. Например, модули +[`ipcRenderer`](../api/ipc-renderer.md) и [`ipcMain`](../api/ipc-main.md) используются +для отправки сообщений, а [remote](../api/remote.md) - для коммуникации в RPC стиле. +В ЧАВО также есть пункт о том, [как разделять информацию между страницами][share-data] + +## Первое приложение на Electron + +Как правило, приложение Electron структурировано следующим образом:: + +```text +your-app/ +├── package.json +├── main.js +└── index.html +``` + +Формат `package.json` точно такой же, как у модулей Node и сприпт, объявленый +как `main`, будет выполняться при запуске вашего приложения, работая в +главном процессе. Например, ваш `package.json` может выглядеть вот так: + +```json +{ + "name" : "your-app", + "version" : "0.1.0", + "main" : "main.js" +} +``` + +__Заметка__: Если поле `main` отсутствует в `package.json`, Electron попробует +загрузить `index.js`. + + +`main.js` должен создавать окно и управлять системными событиями, +типичный пример: + +```javascript +const electron = require('electron') +// Модуль, контролирующий основное: сам Electron. +const app = electron.app +// Модуль, создающий окно приложения. +const BrowserWindow = electron.BrowserWindow + +// Удерживайте глобальное обращение к объекту окна, если вы так не сделаете, то +// окно само закроется после того, как объект будет собран сборщиком мусора. +let mainWindow + +function createWindow () { + // Создаём окно браузера. + mainWindow = new BrowserWindow({width: 800, height: 600}) + + // и загружаем index.html приложения. + mainWindow.loadURL('file://' + __dirname + '/index.html') + + // Открываем DevTools. + mainWindow.webContents.openDevTools() + + // Будет выполнено, когда пользователь закроет окно + mainWindow.on('closed', function () { + //Убрать обращение на объект окна, обычно стоит хранить окна в массиве, + //если ваше приложение поддерживает несколько, сейчас стоит удалить + //соответствующий элемент. + mainWindow = null + }) +} + +//Этот метод будет вызван, когда Electron закончит инициализацию +//и будет готов создавать окна браузера. +//Некоторые API возможно использовать только послн того, как +//это произойдёт. +app.on('ready', createWindow) + +// Выйти, если все окна закрыты +app.on('window-all-closed', function () { + //На OS X приложение и его строка меню обычно остаются активными, + //пока пользователь не завершит их с помощью Cmd + Q. + if (process.platform !== 'darwin') { + app.quit() + } +}) + +app.on('activate', function () { + //На OS X приложение обычно пересоздаёт окно, когда + //пользователь кликает на его иконку в доке, если не открыто + //других окон. + if (mainWindow === null) { + createWindow() + } +}) + +//В этот файл вы можете включить остальной код вашего главного процесса. +//Вы также можете разложить его по отдельным файлам и подключить с помощью require. + +``` + +Наконец, `index.html`, страница, которую вы хотите показать: + +```html + + + + + Hello World! + + +

Привет, мир!

+ Мы используем Node , + Chrome , + и Electron . + + +``` + +## Запуск вашего приложения + +Когда вы создали `main.js`, `index.html` и `package.json` вас скорее всего захочется +запустить ваше приложение, чтобы проверить, что оно работает так, как надо. + +### electron-prebuilt + +[`electron-prebuilt`](https://github.com/electron-userland/electron-prebuilt) — `npm` модуль, +который содержит прекомпилированную версию Electron. + +Если вы установили Electron глобально через `npm`, то вам нужно будет всего лишь +запустить сдедующее в папке вашего проекта: + +```bash +electron . +``` + +Если вы установили Electron локально, то выполните это: + +```bash +./node_modules/.bin/electron . +``` + +### Исполняемые файлы Electron, скачанные вручную + +Если вы скачали Electron вручную, то вы можете использовать +исполняемые файлы прямо в папке вашего проекта. + +#### Windows + +```bash +$ .\electron\electron.exe your-app\ +``` + +#### Linux + +```bash +$ ./electron/electron your-app/ +``` + +#### OS X + +```bash +$ ./Electron.app/Contents/MacOS/Electron your-app/ +``` + +`Electron.app` — часть реализного пакета Electron, вы можете скачать его +[тут](https://github.com/electron/electron/releases). + +### Запустить как дистрибутив + +Когда вы закончили написание вашего приложения, вы можете создать +дистрибутив, следуя инструкциям [отсюда](./application-distribution.md) и +затем запустить полученное приложение. + +### Попробуйте этот пример + +Скопируйте и запустите этот обучающий код, ичпользуя репозиторий [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) + +**Заметка**: Для запуска требуется [Git](https://git-scm.com) и [Node.js](https://nodejs.org/en/download/) (который включает в себя [npm](https://npmjs.org)). + +```bash +# Склонируйте репозиторий +$ git clone https://github.com/electron/electron-quick-start +# Перейдите в папку репозитория +$ cd electron-quick-start +# Установите зависимости и запустите +$ npm install && npm start +``` + +[share-data]: ../faq/electron-faq.md#how-to-share-data-between-web-pages From 33370b18b3f468a3eb501e45c35626cdb031a81d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 20:41:45 +0900 Subject: [PATCH 0659/1265] Run tests for branches on appveyor --- appveyor.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 0fa0c0d9bdd..a3fd5192558 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -14,10 +14,6 @@ install: - cmd: SET PATH=C:\python27;%PATH% - cmd: python script/cibuild -branches: - only: - - master - # disable build and test pahses build: off test: off From f65f8918c95ed2b83651309d48a91bb9b60f211d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 20:51:09 +0900 Subject: [PATCH 0660/1265] Fix specs on Windows when running without desktop session --- spec/api-desktop-capturer-spec.js | 6 ++++++ spec/chromium-spec.js | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/spec/api-desktop-capturer-spec.js b/spec/api-desktop-capturer-spec.js index 68ab2463087..35b7248ed5e 100644 --- a/spec/api-desktop-capturer-spec.js +++ b/spec/api-desktop-capturer-spec.js @@ -1,7 +1,13 @@ const assert = require('assert') const desktopCapturer = require('electron').desktopCapturer +const isCI = require('electron').remote.getGlobal('isCi') + describe('desktopCapturer', function () { + if (isCI && process.platform === 'win32') { + return + } + it('should return a non-empty array of sources', function (done) { desktopCapturer.getSources({ types: ['window', 'screen'] diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js index 706447c00dd..577f020128a 100644 --- a/spec/chromium-spec.js +++ b/spec/chromium-spec.js @@ -62,6 +62,10 @@ describe('chromium feature', function () { w.loadURL(url) }) + if (isCI && process.platform === 'win32') { + return + } + it('is set correctly when window is inactive', function (done) { w = new BrowserWindow({ show: false From d91cd424fec788bb1e5ee490e265964fd4022b63 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 21:21:11 +0900 Subject: [PATCH 0661/1265] Revert "Run tests for branches on appveyor" This reverts commit 33370b18b3f468a3eb501e45c35626cdb031a81d. This commit was wrongly pushed. --- appveyor.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index a3fd5192558..0fa0c0d9bdd 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -14,6 +14,10 @@ install: - cmd: SET PATH=C:\python27;%PATH% - cmd: python script/cibuild +branches: + only: + - master + # disable build and test pahses build: off test: off From 47f7f7b02e5c8f064fc7af4bf68a320040a6a77b Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Sat, 30 Apr 2016 21:43:33 +0900 Subject: [PATCH 0662/1265] Revert "Don't upload PDB files in CI" This reverts commit 7ab8134613577b9092f5e8e81f1c883174bee222. --- script/upload.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/script/upload.py b/script/upload.py index fd795172a67..80d9e5e9e09 100755 --- a/script/upload.py +++ b/script/upload.py @@ -101,6 +101,10 @@ def main(): upload_atom_shell(github, release, os.path.join(DIST_DIR, mksnapshot)) if PLATFORM == 'win32' and not tag_exists: + # Upload PDBs to Windows symbol server. + execute([sys.executable, + os.path.join(SOURCE_ROOT, 'script', 'upload-windows-pdb.py')]) + # Upload node headers. execute([sys.executable, os.path.join(SOURCE_ROOT, 'script', 'upload-node-headers.py'), From bde412dd69a8a70cad6dac81d968af21650a1b4f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 1 May 2016 01:11:21 +0900 Subject: [PATCH 0663/1265] :memo: Fix typos [ci skip] --- docs-translations/ko-KR/api/frameless-window.md | 2 +- docs-translations/ko-KR/api/native-image.md | 2 +- docs-translations/ko-KR/api/protocol.md | 4 ++-- docs-translations/ko-KR/api/session.md | 4 ++-- docs-translations/ko-KR/api/web-contents.md | 2 +- docs-translations/ko-KR/api/web-view-tag.md | 16 ++++++++-------- .../development/setting-up-symbol-server.md | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs-translations/ko-KR/api/frameless-window.md b/docs-translations/ko-KR/api/frameless-window.md index 7bcdeb4a60b..747c7ed7881 100644 --- a/docs-translations/ko-KR/api/frameless-window.md +++ b/docs-translations/ko-KR/api/frameless-window.md @@ -42,7 +42,7 @@ var win = new BrowserWindow({ transparent: true, frame: false }); [이슈](https://github.com/electron/electron/issues/1335)를 참고하세요. * 투명한 창은 크기를 조절할 수 없습니다. `resizable` 속성을 `true`로 할 경우 몇몇 플랫폼에선 크래시가 일어납니다. -* `blur` 필터는 웹 페이지에서만 적용됩니다. 윈도우 아래 컨텐츠에는 블러 효과를 적용할 +* `blur` 필터는 웹 페이지에서만 적용됩니다. 윈도우 아래 콘텐츠에는 블러 효과를 적용할 방법이 없습니다. (예시: 유저의 시스템에 열린 다른 어플리케이션) * Windows에선 DWM(데스크톱 창 관리자)가 비활성화되어 있을 경우 투명한 창이 작동하지 않습니다. diff --git a/docs-translations/ko-KR/api/native-image.md b/docs-translations/ko-KR/api/native-image.md index 2ef35668cae..3447215715d 100644 --- a/docs-translations/ko-KR/api/native-image.md +++ b/docs-translations/ko-KR/api/native-image.md @@ -66,7 +66,7 @@ var appIcon = new Tray('/Users/somebody/images/icon.png'); ## 템플릿 이미지 템플릿 이미지는 검은색과 명확한 색상(알파 채널)으로 이루어져 있습니다. 템플릿 이미지는 -단독 이미지로 사용되지 않고 다른 컨텐츠와 혼합되어 최종 외관 만드는데 사용됩니다. +단독 이미지로 사용되지 않고 다른 콘텐츠와 혼합되어 최종 외관 만드는데 사용됩니다. 가장 일반적으로 템플릿 이미지는 밝고 어두운 테마 색상으로 변경할 수 있는 메뉴 바 아이콘 등에 사용되고 있습니다. diff --git a/docs-translations/ko-KR/api/protocol.md b/docs-translations/ko-KR/api/protocol.md index 2b42226e2ff..7ac23a59189 100644 --- a/docs-translations/ko-KR/api/protocol.md +++ b/docs-translations/ko-KR/api/protocol.md @@ -134,8 +134,8 @@ HTTP 요청을 응답으로 전송할 `scheme`의 프로토콜을 등록합니 POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다. * `uploadData` object - * `contentType` String - 컨텐츠의 MIME 타입. - * `data` String - 전송할 컨텐츠. + * `contentType` String - 콘텐츠의 MIME 타입. + * `data` String - 전송할 콘텐츠. ### `protocol.unregisterProtocol(scheme[, completion])` diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index 76a3fc9ea83..d6a782e3a45 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -322,7 +322,7 @@ session.fromPartition(partition).setPermissionRequestHandler(function(webContent #### `ses.webRequest` -`webRequest` API는 생명주기의 다양한 단계에 맞춰 요청 컨텐츠를 가로채거나 변경할 수 +`webRequest` API는 생명주기의 다양한 단계에 맞춰 요청 콘텐츠를 가로채거나 변경할 수 있도록 합니다. 각 API는 `filter`와 `listener`를 선택적으로 받을 수 있습니다. `listener`는 API의 @@ -367,7 +367,7 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, `uploadData`는 `data` 객체의 배열입니다: * `data` Object - * `bytes` Buffer - 전송될 컨텐츠. + * `bytes` Buffer - 전송될 콘텐츠. * `file` String - 업로드될 파일의 경로. `callback`은 `response` 객체와 함께 호출되어야 합니다: diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 48798f79b6c..550351c58d2 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -501,7 +501,7 @@ CSS 코드를 현재 웹 페이지에 삽입합니다. ### `webContents.findInPage(text[, options])` -* `text` String - 찾을 컨텐츠, 반드시 공백이 아니여야 합니다. +* `text` String - 찾을 콘텐츠, 반드시 공백이 아니여야 합니다. * `options` Object (optional) * `forward` Boolean - 앞에서부터 검색할지 뒤에서부터 검색할지 여부입니다. 기본값은 `true`입니다. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index b04398e8e5d..d90362fb3a7 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -1,18 +1,18 @@ # `` 태그 -`guest` 컨텐츠(웹 페이지)를 Electron 앱 페이지에 삽입하기 위해 `webview` 태그를 -사용할 수 있습니다. 게스트 컨텐츠는 `webview` 컨테이너에 담겨 대상 페이지에 삽입되고 -해당 페이지에선 게스트 컨텐츠의 배치 및 렌더링 과정을 조작할 수 있습니다. +`guest` 콘텐츠(웹 페이지)를 Electron 앱 페이지에 삽입하기 위해 `webview` 태그를 +사용할 수 있습니다. 게스트 콘텐츠는 `webview` 컨테이너에 담겨 대상 페이지에 삽입되고 +해당 페이지에선 게스트 콘텐츠의 배치 및 렌더링 과정을 조작할 수 있습니다. `iframe`과는 달리 `webview`는 어플리케이션과 분리된 프로세스에서 작동합니다. -이는 웹 페이지와 같은 권한을 가지지 않고 앱과 임베디드(게스트) 컨텐츠간의 모든 -상호작용이 비동기로 작동한다는 것을 의미합니다. 따라서 임베디드 컨텐츠로부터 +이는 웹 페이지와 같은 권한을 가지지 않고 앱과 임베디드(게스트) 콘텐츠간의 모든 +상호작용이 비동기로 작동한다는 것을 의미합니다. 따라서 임베디드 콘텐츠로부터 어플리케이션을 안전하게 유지할 수 있습니다. ## 예제 웹 페이지를 어플리케이션에 삽입하려면 `webview` 태그를 사용해 원하는 타겟 페이지에 -추가하면 됩니다. (게스트 컨텐츠가 앱 페이지에 추가 됩니다) 간단한 예로 `webview` +추가하면 됩니다. (게스트 콘텐츠가 앱 페이지에 추가 됩니다) 간단한 예로 `webview` 태그의 `src` 속성에 페이지를 지정하고 css 스타일을 이용해서 컨테이너의 외관을 설정할 수 있습니다: @@ -20,7 +20,7 @@ ``` -게스트 컨텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 +게스트 콘텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 응답을 받을 수 있습니다. 다음 예제를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 이벤트를 확인하고 두번째 리스너는 페이지의 로딩이 끝난시점을 확인합니다. 그리고 페이지를 로드하는 동안 "loading..." 메시지를 표시합니다. @@ -404,7 +404,7 @@ Service worker에 대한 개발자 도구를 엽니다. ### `webContents.findInPage(text[, options])` -* `text` String - 찾을 컨텐츠, 반드시 공백이 아니여야 합니다. +* `text` String - 찾을 콘텐츠, 반드시 공백이 아니여야 합니다. * `options` Object (optional) * `forward` Boolean - 앞에서부터 검색할지 뒤에서부터 검색할지 여부입니다. 기본값은 `true`입니다. diff --git a/docs-translations/ko-KR/development/setting-up-symbol-server.md b/docs-translations/ko-KR/development/setting-up-symbol-server.md index abfda6851bf..60523f2035b 100644 --- a/docs-translations/ko-KR/development/setting-up-symbol-server.md +++ b/docs-translations/ko-KR/development/setting-up-symbol-server.md @@ -9,7 +9,7 @@ 참고로 릴리즈된 Electron 빌드는 자체적으로 많은 최적화가 되어 있는 관계로 경우에 따라 디버깅이 쉽지 않을 수 있습니다. Inlining, tail call 등 컴파일러 최적화에 의해 디버거가 -모든 변수의 컨텐츠를 보여줄 수 없는 경우도 있고 실행 경로가 이상하게 보여지는 경우도 +모든 변수의 콘텐츠를 보여줄 수 없는 경우도 있고 실행 경로가 이상하게 보여지는 경우도 있습니다. 유일한 해결 방법은 최적화되지 않은 로컬 빌드를 하는 것입니다. 공식적인 Electron의 심볼 서버의 URL은 From f426c9c9515cb2a87cb2a33e1e21b592da81fa90 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 1 May 2016 01:12:54 +0900 Subject: [PATCH 0664/1265] :memo: Improve grammar [ci skip] --- docs-translations/ko-KR/api/crash-reporter.md | 2 +- docs-translations/ko-KR/api/dialog.md | 2 +- docs-translations/ko-KR/api/file-object.md | 2 +- docs-translations/ko-KR/api/ipc-main.md | 2 +- docs-translations/ko-KR/api/ipc-renderer.md | 2 +- docs-translations/ko-KR/api/menu-item.md | 2 +- docs-translations/ko-KR/api/menu.md | 8 ++++---- docs-translations/ko-KR/api/native-image.md | 4 ++-- docs-translations/ko-KR/api/power-monitor.md | 2 +- .../ko-KR/api/power-save-blocker.md | 2 +- docs-translations/ko-KR/api/protocol.md | 4 ++-- docs-translations/ko-KR/api/remote.md | 6 +++--- docs-translations/ko-KR/api/shell.md | 2 +- docs-translations/ko-KR/api/web-contents.md | 2 +- docs-translations/ko-KR/api/web-view-tag.md | 18 +++++++++--------- .../development/setting-up-symbol-server.md | 2 +- docs-translations/ko-KR/styleguide.md | 4 ++-- .../ko-KR/tutorial/application-packaging.md | 2 +- .../ko-KR/tutorial/devtools-extension.md | 2 +- .../ko-KR/tutorial/online-offline-events.md | 4 ++-- .../ko-KR/tutorial/quick-start.md | 8 ++++---- .../tutorial/using-native-node-modules.md | 4 ++-- .../tutorial/using-selenium-and-webdriver.md | 2 +- 23 files changed, 44 insertions(+), 44 deletions(-) diff --git a/docs-translations/ko-KR/api/crash-reporter.md b/docs-translations/ko-KR/api/crash-reporter.md index 2269742bcbf..e6174f3e1ef 100644 --- a/docs-translations/ko-KR/api/crash-reporter.md +++ b/docs-translations/ko-KR/api/crash-reporter.md @@ -3,7 +3,7 @@ `crash-reporter` 모듈은 어플리케이션의 크래시 정보를 자동으로 원격 서버에 업로드하는데 사용합니다. -다음 예제는 윈격 서버에 어플리케이션 크래시 정보를 자동으로 보고하는 예제입니다: +다음 예시는 윈격 서버에 어플리케이션 크래시 정보를 자동으로 보고하는 예시입니다: ```javascript const crashReporter = require('electron').crashReporter; diff --git a/docs-translations/ko-KR/api/dialog.md b/docs-translations/ko-KR/api/dialog.md index cbb1afc71ae..8bf144077be 100644 --- a/docs-translations/ko-KR/api/dialog.md +++ b/docs-translations/ko-KR/api/dialog.md @@ -4,7 +4,7 @@ 수 있는 모듈입니다. 이 모듈을 사용하면 웹 어플리케이션에서 일반 네이티브 어플리케이션과 비슷한 사용자 경험을 제공할 수 있습니다. -다음 예제는 파일과 디렉터리를 다중으로 선택하는 대화 상자를 표시하는 예제입니다: +다음 예시는 파일과 디렉터리를 다중으로 선택하는 대화 상자를 표시하는 예시입니다: ```javascript var win = ...; // 대화 상자를 사용할 BrowserWindow 객체 diff --git a/docs-translations/ko-KR/api/file-object.md b/docs-translations/ko-KR/api/file-object.md index a2a19a530d4..eb7bd9a135b 100644 --- a/docs-translations/ko-KR/api/file-object.md +++ b/docs-translations/ko-KR/api/file-object.md @@ -4,7 +4,7 @@ DOM의 File 인터페이스는 네이티브 파일을 추상화 합니다. 유 이용하여 작업할 때 선택된 파일의 경로를 알 수 있도록 Electron은 파일의 실제 경로를 담은 `path` 속성을 File 인터페이스에 추가하였습니다. -다음 예제는 앱으로 드래그 앤 드롭한 파일의 실제 경로를 가져옵니다: +다음 예시는 앱으로 드래그 앤 드롭한 파일의 실제 경로를 가져옵니다: ```html
diff --git a/docs-translations/ko-KR/api/ipc-main.md b/docs-translations/ko-KR/api/ipc-main.md index dcbaa139673..cc44d48c4c9 100644 --- a/docs-translations/ko-KR/api/ipc-main.md +++ b/docs-translations/ko-KR/api/ipc-main.md @@ -14,7 +14,7 @@ * 메시지에 동기로 응답할 땐 반드시 `event.returnValue`를 설정해야 합니다. * 메시지를 비동기로 응답할 땐 `event.sender.send(...)` 메서드를 사용할 수 있습니다. -다음 예제는 렌더러 프로세스와 메인 프로세스간에 메시지를 전달하고 받는 예제입니다: +다음 예시는 렌더러 프로세스와 메인 프로세스간에 메시지를 전달하고 받는 예시입니다: ```javascript // 메인 프로세스 diff --git a/docs-translations/ko-KR/api/ipc-renderer.md b/docs-translations/ko-KR/api/ipc-renderer.md index f46809a52d2..a25900453a7 100644 --- a/docs-translations/ko-KR/api/ipc-renderer.md +++ b/docs-translations/ko-KR/api/ipc-renderer.md @@ -4,7 +4,7 @@ 인스턴스입니다. 렌더러 프로세스에서 메인 프로세스로 동기/비동기 메시지를 주고 받는 방법을 제공합니다. 또한 메인 프로세스로부터 받은 메시지에 응답할 수도 있습니다. -[ipcMain](ipc-main.md)에서 코드 예제를 확인할 수 있습니다. +[ipcMain](ipc-main.md)에서 코드 예시를 확인할 수 있습니다. ## 메시지 리스닝 diff --git a/docs-translations/ko-KR/api/menu-item.md b/docs-translations/ko-KR/api/menu-item.md index 3ee5a2ff507..c34a53402ca 100644 --- a/docs-translations/ko-KR/api/menu-item.md +++ b/docs-translations/ko-KR/api/menu-item.md @@ -3,7 +3,7 @@ `menu-item` 모듈은 어플리케이션 또는 컨텍스트 [`menu`](menu.md)에 항목 아이템을 추가할 수 있도록 관련 클래스를 제공합니다. -[`menu`](menu.md)에서 예제를 확인할 수 있습니다. +[`menu`](menu.md)에서 예시를 확인할 수 있습니다. ## Class: MenuItem diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index c0de2ec2ab0..3c55d70c4b7 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -6,8 +6,8 @@ 각 메뉴는 여러 개의 [메뉴 아이템](menu-item.md)으로 구성되고 서브 메뉴를 가질 수도 있습니다. -다음 예제는 웹 페이지 내에서 [remote](remote.md) 모듈을 활용하여 동적으로 메뉴를 -생성하는 예제입니다. 그리고 유저가 페이지에서 오른쪽 클릭을 할 때마다 마우스 위치에 +다음 예시는 웹 페이지 내에서 [remote](remote.md) 모듈을 활용하여 동적으로 메뉴를 +생성하는 예시입니다. 그리고 유저가 페이지에서 오른쪽 클릭을 할 때마다 마우스 위치에 팝업 형태로 메뉴를 표시합니다: ```html @@ -29,7 +29,7 @@ window.addEventListener('contextmenu', function (e) { ``` -또 하나의 예를 들자면 다음 예제는 렌더러 프로세스에서 template API를 사용하여 +또 하나의 예를 들자면 다음 예시는 렌더러 프로세스에서 template API를 사용하여 어플리케이션 메뉴를 만듭니다: ```javascript @@ -331,7 +331,7 @@ OS X에선 지정한 어플리케이션 메뉴에 상관없이 메뉴의 첫번 이동하고 싶은 특정 그룹의 아이템들이 있을 경우 해당 그룹의 맨 첫번째 메뉴 아이템의 위치만을 지정하면 됩니다. -### 예제 +### 예시 메뉴 템플릿: diff --git a/docs-translations/ko-KR/api/native-image.md b/docs-translations/ko-KR/api/native-image.md index 3447215715d..bc55e4913b1 100644 --- a/docs-translations/ko-KR/api/native-image.md +++ b/docs-translations/ko-KR/api/native-image.md @@ -11,7 +11,7 @@ var appIcon = new Tray('/Users/somebody/images/icon.png'); var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'}); ``` -이 예제는 클립보드로부터 가져온 `nativeImage`로 트레이 메뉴를 생성합니다: +이 예시는 클립보드로부터 가져온 `nativeImage`로 트레이 메뉴를 생성합니다: ```javascript var image = clipboard.readImage(); @@ -73,7 +73,7 @@ var appIcon = new Tray('/Users/somebody/images/icon.png'); **참고:** 템플릿 이미지는 OS X 운영체제만 지원합니다. -템플릿 이미지를 지정하려면 다음 예제와 같이 파일명에 `Template` 문자열을 추가해야 +템플릿 이미지를 지정하려면 다음 예시와 같이 파일명에 `Template` 문자열을 추가해야 합니다: * `xxxTemplate.png` diff --git a/docs-translations/ko-KR/api/power-monitor.md b/docs-translations/ko-KR/api/power-monitor.md index 63d5959fe20..9f543cd1921 100644 --- a/docs-translations/ko-KR/api/power-monitor.md +++ b/docs-translations/ko-KR/api/power-monitor.md @@ -5,7 +5,7 @@ 됩니다) 메인 프로세스의 `app` 모듈에서 `ready` 이벤트를 호출하기 전까지 사용할 수 없습니다. -예제: +예시: ```javascript var app = require('app'); diff --git a/docs-translations/ko-KR/api/power-save-blocker.md b/docs-translations/ko-KR/api/power-save-blocker.md index 560b3fc9cef..4754f0e88bd 100644 --- a/docs-translations/ko-KR/api/power-save-blocker.md +++ b/docs-translations/ko-KR/api/power-save-blocker.md @@ -3,7 +3,7 @@ `powerSaveBlocker` 모듈은 시스템이 저전력(슬립) 모드로 진입하는 것을 막고 앱 시스템과 화면이 항상 활성화 상태를 유지할 수 있도록 하는 몇가지 유틸리티를 제공하는 모듈입니다. -예제: +예시: ```javascript const powerSaveBlocker = require('electron').powerSaveBlocker; diff --git a/docs-translations/ko-KR/api/protocol.md b/docs-translations/ko-KR/api/protocol.md index 7ac23a59189..5df6db37e60 100644 --- a/docs-translations/ko-KR/api/protocol.md +++ b/docs-translations/ko-KR/api/protocol.md @@ -3,7 +3,7 @@ `protocol` 모듈은 이미 있는 프로토콜의 동작을 가로채거나 새로운 프로토콜을 만들 수 있는 기능을 제공합니다. -다음 예제는 `file://` 프로토콜과 비슷한 일을 하는 커스텀 프로토콜을 설정합니다: +다음 예시는 `file://` 프로토콜과 비슷한 일을 하는 커스텀 프로토콜을 설정합니다: ```javascript const electron = require('electron'); @@ -87,7 +87,7 @@ The `uploadData` is an array of `data` objects: 속성을 포함하는 객체와 함께 호출되어야 한다는 점을 제외하면 `registerFileProtocol`과 사용법이 같습니다. -예제: +예시: ```javascript protocol.registerBufferProtocol('atom', function(request, callback) { diff --git a/docs-translations/ko-KR/api/remote.md b/docs-translations/ko-KR/api/remote.md index 3265a795a07..8c3583a159f 100644 --- a/docs-translations/ko-KR/api/remote.md +++ b/docs-translations/ko-KR/api/remote.md @@ -9,7 +9,7 @@ Electron의 메인 프로세스에선 GUI와 관련 있는(`dialog`, `menu`등) inter-process 통신을 하지 않고도 간단한 API를 통해 직접 메인 프로세스의 모듈과 메서드를 사용할 수 있습니다. 이 개념은 Java의 [RMI][rmi]와 비슷합니다. -다음 예제는 렌더러 프로세스에서 브라우저 창을 만드는 예제입니다: +다음 예시는 렌더러 프로세스에서 브라우저 창을 만드는 예시입니다: ```javascript const remote = require('electron').remote; @@ -29,7 +29,7 @@ win.loadURL('https://github.com'); 메서드를 호출하거나, 객체에 접근하거나, 생성자로 객체를 생성하는 등의 작업은 실질적으로 동기형 inter-process 메시지를 보냅니다. -위의 예제에서 사용한 두 `BrowserWindow`와 `win`은 remote 객체입니다. 그리고 +위의 예시에서 사용한 두 `BrowserWindow`와 `win`은 remote 객체입니다. 그리고 `new BrowserWindow`이 생성하는 `BrowserWindow` 객체는 렌더러 프로세스에서 생성되지 않습니다. 대신에 이 `BrowserWindow` 객체는 메인 프로세스에서 생성되며 렌더러 프로세스에 `win` 객체와 같이 이에 대응하는 remote 객체를 반환합니다. @@ -94,7 +94,7 @@ console.log(withRendererCb, withLocalCb) // [true, true, true], [2, 3, 4] 않습니다. 함수 참조는 메인 프로세스에서 GC가 일어나기 전까지 계속 프로세스에 남아있게 됩니다. -다음 코드를 보면 느낌이 올 것입니다. 이 예제는 remote 객체에 `close` 이벤트 콜백을 +다음 코드를 보면 느낌이 올 것입니다. 이 예시는 remote 객체에 `close` 이벤트 콜백을 설치합니다: ```javascript diff --git a/docs-translations/ko-KR/api/shell.md b/docs-translations/ko-KR/api/shell.md index 6e9b0f25d5a..552584f170b 100644 --- a/docs-translations/ko-KR/api/shell.md +++ b/docs-translations/ko-KR/api/shell.md @@ -2,7 +2,7 @@ `shell` 모듈은 데스크톱 환경 통합에 관련한 유틸리티를 제공하는 모듈입니다. -다음 예제는 설정된 URL을 유저의 기본 브라우저로 엽니다: +다음 예시는 설정된 URL을 유저의 기본 브라우저로 엽니다: ```javascript const shell = require('electron').shell; diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 550351c58d2..466ce9759bd 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -3,7 +3,7 @@ `webContents`는 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)를 상속받았습니다. 웹 페이지의 렌더링과 관리를 책임지며 [`BrowserWindow`](browser-window.md)의 속성입니다. 다음은 `webContents` 객체에 -접근하는 예제입니다: +접근하는 예시입니다: ```javascript const BrowserWindow = require('electron').BrowserWindow; diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index d90362fb3a7..743fcc5e325 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -9,7 +9,7 @@ 상호작용이 비동기로 작동한다는 것을 의미합니다. 따라서 임베디드 콘텐츠로부터 어플리케이션을 안전하게 유지할 수 있습니다. -## 예제 +## 예시 웹 페이지를 어플리케이션에 삽입하려면 `webview` 태그를 사용해 원하는 타겟 페이지에 추가하면 됩니다. (게스트 콘텐츠가 앱 페이지에 추가 됩니다) 간단한 예로 `webview` @@ -21,7 +21,7 @@ ``` 게스트 콘텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 -응답을 받을 수 있습니다. 다음 예제를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 +응답을 받을 수 있습니다. 다음 예시를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 이벤트를 확인하고 두번째 리스너는 페이지의 로딩이 끝난시점을 확인합니다. 그리고 페이지를 로드하는 동안 "loading..." 메시지를 표시합니다. @@ -200,7 +200,7 @@ API를 사용할 수 있습니다. 이를 지정하면 내부에서 로우레벨 **참고:** 태그 객체의 메서드는 페이지 로드가 끝난 뒤에만 사용할 수 있습니다. -**예제** +**예시** ```javascript webview.addEventListener("dom-ready", function() { @@ -451,7 +451,7 @@ Webview 페이지를 PDF 형식으로 인쇄합니다. 임의의 인자를 보낼 수도 있습니다. 렌더러 프로세스는 `ipcRenderer` 모듈의 `channel` 이벤트로 이 메시지를 받아 처리할 수 있습니다. -예제는 [webContents.send](web-contents.md#webcontentssendchannel-args)를 참고하세요. +예시는 [webContents.send](web-contents.md#webcontentssendchannel-args)를 참고하세요. ### `.sendInputEvent(event)` @@ -582,8 +582,8 @@ Returns: `console.log` API에 의해 로깅될 때 발생하는 이벤트입니다. -다음 예제는 모든 로그 메시지를 로그 레벨이나 다른 속성에 관련 없이 호스트 페이지의 -콘솔에 다시 로깅하는 예제입니다. +다음 예시는 모든 로그 메시지를 로그 레벨이나 다른 속성에 관련 없이 호스트 페이지의 +콘솔에 다시 로깅하는 예시입니다. ```javascript webview.addEventListener('console-message', function(e) { @@ -626,7 +626,7 @@ Returns: 페이지가 새로운 브라우저 창을 생성할 때 발생하는 이벤트입니다. -다음 예제 코드는 새 URL을 시스템의 기본 브라우저로 여는 코드입니다. +다음 예시 코드는 새 URL을 시스템의 기본 브라우저로 여는 코드입니다. ```javascript webview.addEventListener('new-window', function(e) { @@ -681,8 +681,8 @@ Returns: 페이지가 자체적으로 닫힐 때 발생하는 이벤트입니다. -다음 예제 코드는 페이지가 자체적으로 닫힐 때 `webview`를 `about:blank` 페이지로 -이동시키는 예제입니다. +다음 예시 코드는 페이지가 자체적으로 닫힐 때 `webview`를 `about:blank` 페이지로 +이동시키는 예시입니다. ```javascript webview.addEventListener('close', function() { diff --git a/docs-translations/ko-KR/development/setting-up-symbol-server.md b/docs-translations/ko-KR/development/setting-up-symbol-server.md index 60523f2035b..6a214c5b843 100644 --- a/docs-translations/ko-KR/development/setting-up-symbol-server.md +++ b/docs-translations/ko-KR/development/setting-up-symbol-server.md @@ -14,7 +14,7 @@ 공식적인 Electron의 심볼 서버의 URL은 http://54.249.141.255:8086/atom-shell/symbols 입니다. 일단 이 URL에 직접적으로 -접근할 수는 없습니다: 디버깅 툴에 심볼의 경로를 추가해야 합니다. 아래의 예제를 참고하면 +접근할 수는 없습니다: 디버깅 툴에 심볼의 경로를 추가해야 합니다. 아래의 예시를 참고하면 로컬 캐시 디렉터리는 서버로부터 중복되지 않게 PDB를 가져오는데 사용됩니다. `c:\code\symbols` 캐시 디렉터리를 사용중인 OS에 맞춰 적당한 경로로 변경하세요. diff --git a/docs-translations/ko-KR/styleguide.md b/docs-translations/ko-KR/styleguide.md index ec57970e513..3896f3d21d1 100644 --- a/docs-translations/ko-KR/styleguide.md +++ b/docs-translations/ko-KR/styleguide.md @@ -51,7 +51,7 @@ Electron 문서 구조를 이해하는 데 참고할 수 있는 유용한 도움 ### Methods [Method](https://developer.mozilla.org/ko/docs/Glossary/Method) 문서의 -예제입니다: +예시입니다: --- @@ -75,7 +75,7 @@ Electron 문서 구조를 이해하는 데 참고할 수 있는 유용한 도움 ### Events -[Event](https://developer.mozilla.org/ko/docs/Web/API/Event) 문서의 예제입니다: +[Event](https://developer.mozilla.org/ko/docs/Web/API/Event) 문서의 예시입니다: --- diff --git a/docs-translations/ko-KR/tutorial/application-packaging.md b/docs-translations/ko-KR/tutorial/application-packaging.md index a33e2eef96c..bc56d824617 100644 --- a/docs-translations/ko-KR/tutorial/application-packaging.md +++ b/docs-translations/ko-KR/tutorial/application-packaging.md @@ -168,7 +168,7 @@ Node API에는 `child_process.exec`, `child_process.spawn` 그리고 바이러스로 진단 할 수도 있습니다. 이 문제를 해결하려면 `--unpack` 옵션을 통해 파일을 압축이 풀려진 상태로 유지해야 합니다. -다음의 예제는 node 네이티브 모듈의 공유 라이브러리를 압축이 풀려진 상태로 유지합니다: +다음의 예시는 node 네이티브 모듈의 공유 라이브러리를 압축이 풀려진 상태로 유지합니다: ```bash $ asar pack app app.asar --unpack *.node diff --git a/docs-translations/ko-KR/tutorial/devtools-extension.md b/docs-translations/ko-KR/tutorial/devtools-extension.md index b45f88892d8..07281620ec7 100644 --- a/docs-translations/ko-KR/tutorial/devtools-extension.md +++ b/docs-translations/ko-KR/tutorial/devtools-extension.md @@ -10,7 +10,7 @@ **주의: 현재 React DevTools은 작동하지 않습니다. https://github.com/electron/electron/issues/915 이슈를 참고하세요!** -다음 예제는 [React DevTools Extension](https://github.com/facebook/react-devtools)을 +다음 예시는 [React DevTools Extension](https://github.com/facebook/react-devtools)을 사용합니다. 먼저 소스코드를 다운로드 받습니다: diff --git a/docs-translations/ko-KR/tutorial/online-offline-events.md b/docs-translations/ko-KR/tutorial/online-offline-events.md index 5b91fc61bd5..698544e83b6 100644 --- a/docs-translations/ko-KR/tutorial/online-offline-events.md +++ b/docs-translations/ko-KR/tutorial/online-offline-events.md @@ -1,6 +1,6 @@ # 온라인/오프라인 이벤트 감지 -온라인/오프라인 이벤트는 다음 예제와 같이 렌더러 프로세스에서 표준 HTML5 API를 이용하여 +온라인/오프라인 이벤트는 다음 예시와 같이 렌더러 프로세스에서 표준 HTML5 API를 이용하여 구현할 수 있습니다. _main.js_ @@ -41,7 +41,7 @@ _online-status.html_ 있습니다. 메인 프로세스는 `navigator` 객체를 가지고 있지 않기 때문에 이 이벤트를 직접 사용할 수는 없습니다. -대신 다음 예제와 같이 Electron의 inter-process communication(ipc) 유틸리티를 +대신 다음 예시와 같이 Electron의 inter-process communication(ipc) 유틸리티를 사용하면 이벤트를 메인 프로세스로 전달할 수 있습니다. _main.js_ diff --git a/docs-translations/ko-KR/tutorial/quick-start.md b/docs-translations/ko-KR/tutorial/quick-start.md index eb95232a06f..bdd151f1535 100644 --- a/docs-translations/ko-KR/tutorial/quick-start.md +++ b/docs-translations/ko-KR/tutorial/quick-start.md @@ -71,7 +71,7 @@ your-app/ __알림__: 만약 `main` 필드가 `package.json`에 설정되어 있지 않으면 Electron은 자동으로 같은 디렉터리의 `index.js`를 로드합니다. -반드시 `main.js`에서 창을 만들고 시스템 이벤트를 처리해야 합니다. 대표적인 예제로 +반드시 `main.js`에서 창을 만들고 시스템 이벤트를 처리해야 합니다. 대표적인 예시로 다음과 같이 작성할 수 있습니다: ```javascript @@ -116,7 +116,7 @@ app.on('ready', function() { }); ``` -마지막으로, 사용자에게 보여줄 `index.html` 웹 페이지의 예제입니다: +마지막으로, 사용자에게 보여줄 `index.html` 웹 페이지의 예시입니다: ```html @@ -196,9 +196,9 @@ $ ./Electron.app/Contents/MacOS/Electron your-app/ ### 미리 작성된 앱 실행하기 [`atom/electron-quick-start`](https://github.com/electron/electron-quick-start) -저장소를 클론하면 이 문서에서 작성한 예제 앱을 바로 실행해 볼 수 있습니다. +저장소를 클론하면 이 문서에서 작성한 예시 앱을 바로 실행해 볼 수 있습니다. -**참고**: 이 예제를 실행시키려면 [Git](https://git-scm.com)과 +**참고**: 이 예시를 실행시키려면 [Git](https://git-scm.com)과 [Node.js](https://nodejs.org/en/download/)가 필요합니다. (CLI에서 실행 가능한 [npm](https://npmjs.org)이 있어야 합니다) diff --git a/docs-translations/ko-KR/tutorial/using-native-node-modules.md b/docs-translations/ko-KR/tutorial/using-native-node-modules.md index e153b265b63..156319aaec4 100644 --- a/docs-translations/ko-KR/tutorial/using-native-node-modules.md +++ b/docs-translations/ko-KR/tutorial/using-native-node-modules.md @@ -12,7 +12,7 @@ node.js의 버전을 확인할 필요가 있습니다. Electron에서 사용하 [releases](https://github.com/electron/electron/releases)에서 확인할 수 있으며 `process.version`을 출력하여 버전을 확인할 수도 있습니다. ([시작하기](./quick-start.md)의 -예제를 참고하세요) +예시를 참고하세요) 혹시 직접 만든 네이티브 모듈이 있다면 [NAN](https://github.com/nodejs/nan/) 모듈을 사용하는 것을 고려해보는 것이 좋습니다. 이 모듈은 다중 버전의 node.js를 지원하기 쉽게 @@ -28,7 +28,7 @@ Electron도 이 모듈을 통해 포팅된 네이티브 모듈을 사용할 수 [`electron-rebuild`](https://github.com/paulcbetts/electron-rebuild) 패키지를 사용하면 빠르고 간단하게 네이티브 모듈을 다시 빌드할 수 있습니다. -다음 예제는 `electron-rebuild`를 통해 자동으로 모듈의 헤더를 다운로드하고 네이티브 +다음 예시는 `electron-rebuild`를 통해 자동으로 모듈의 헤더를 다운로드하고 네이티브 모듈을 빌드합니다: ```sh diff --git a/docs-translations/ko-KR/tutorial/using-selenium-and-webdriver.md b/docs-translations/ko-KR/tutorial/using-selenium-and-webdriver.md index 6cc5472bb12..e16f7be944e 100644 --- a/docs-translations/ko-KR/tutorial/using-selenium-and-webdriver.md +++ b/docs-translations/ko-KR/tutorial/using-selenium-and-webdriver.md @@ -13,7 +13,7 @@ Electron에서 `chromedriver`를 사옹하려면 드라이버에서 Electron을 ## WebDriverJs 설정하기 [WebDriverJs](https://code.google.com/p/selenium/wiki/WebDriverJs)는 WebDriver를 -사용하여 테스트 할 수 있도록 도와주는 node 패키지입니다. 다음 예제를 참고하세요. +사용하여 테스트 할 수 있도록 도와주는 node 패키지입니다. 다음 예시를 참고하세요. ### 1. 크롬 드라이버 시작 From 6fda14ce886fd5dfaa24f2f90dfabfcbf16f74eb Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 1 May 2016 01:53:21 +0900 Subject: [PATCH 0665/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/accelerator.md | 7 +++--- docs-translations/ko-KR/api/app.md | 12 ++++------ docs-translations/ko-KR/api/auto-updater.md | 9 +++++--- docs-translations/ko-KR/api/browser-window.md | 22 +++++++++---------- .../ko-KR/api/chrome-command-line-switches.md | 9 ++++---- docs-translations/ko-KR/api/clipboard.md | 11 +++++----- .../ko-KR/api/content-tracing.md | 11 +++++----- docs-translations/ko-KR/api/crash-reporter.md | 3 +-- .../ko-KR/api/desktop-capturer.md | 4 ++-- docs-translations/ko-KR/api/dialog.md | 8 +++---- docs-translations/ko-KR/api/download-item.md | 2 ++ .../ko-KR/api/environment-variables.md | 2 ++ docs-translations/ko-KR/api/file-object.md | 8 ++++--- .../ko-KR/api/frameless-window.md | 2 ++ .../ko-KR/api/global-shortcut.md | 6 +++-- docs-translations/ko-KR/api/ipc-main.md | 2 ++ docs-translations/ko-KR/api/ipc-renderer.md | 2 ++ docs-translations/ko-KR/api/menu-item.md | 3 +-- docs-translations/ko-KR/api/menu.md | 7 +++--- docs-translations/ko-KR/api/native-image.md | 2 ++ docs-translations/ko-KR/api/power-monitor.md | 8 +++---- .../ko-KR/api/power-save-blocker.md | 3 +-- docs-translations/ko-KR/api/process.md | 6 +++++ docs-translations/ko-KR/api/protocol.md | 3 +-- docs-translations/ko-KR/api/remote.md | 2 ++ docs-translations/ko-KR/api/screen.md | 13 ++++++----- docs-translations/ko-KR/api/session.md | 2 ++ docs-translations/ko-KR/api/shell.md | 2 ++ docs-translations/ko-KR/api/synopsis.md | 2 ++ docs-translations/ko-KR/api/tray.md | 3 +-- docs-translations/ko-KR/api/web-contents.md | 2 ++ docs-translations/ko-KR/api/web-frame.md | 13 +++++------ docs-translations/ko-KR/api/web-view-tag.md | 2 ++ docs-translations/ko-KR/api/window-open.md | 2 ++ .../mac-app-store-submission-guide.md | 2 +- .../tutorial/using-pepper-flash-plugin.md | 4 ++-- 36 files changed, 116 insertions(+), 85 deletions(-) diff --git a/docs-translations/ko-KR/api/accelerator.md b/docs-translations/ko-KR/api/accelerator.md index a0eb55e8702..58d4b41d972 100644 --- a/docs-translations/ko-KR/api/accelerator.md +++ b/docs-translations/ko-KR/api/accelerator.md @@ -1,9 +1,10 @@ # Accelerator -Accelerator는 키보드 단축키를 표현하는 문자열입니다, 여러 혼합키와 키코드를 `+` 문자를 -이용하여 결합할 수 있습니다. +> 키보드 단축키를 정의합니다. -예제: +Accelerator는 `+` 문자를 통해 여러 혼합키와 키코드를 결합할 수 있습니다. + +예시: * `CommandOrControl+A` * `CommandOrControl+Shift+Z` diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index ff6b4640ad2..86f4c7da923 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -1,8 +1,8 @@ # app -`app` 모듈은 어플리케이션의 생명주기 제어를 책임집니다. +> 어플리케이션의 이벤트 생명주기를 제어합니다. -밑의 예제는 마지막 윈도우가 종료되었을 때, 어플리케이션을 종료시키는 예제입니다: +밑의 예시는 마지막 윈도우가 종료되었을 때, 어플리케이션을 종료시키는 예시입니다: ```javascript const app = require('electron').app; @@ -236,10 +236,6 @@ app.on('login', function(event, webContents, request, authInfo, callback) { GPU가 작동하던 중 크래시가 일어났을 때 발생하는 이벤트입니다. -### Event: 'platform-theme-changed' _OS X_ - -시스템의 다크 모드 테마가 토글되면 발생하는 이벤트입니다. - ## Methods `app` 객체는 다음과 같은 메서드를 가지고 있습니다: @@ -455,8 +451,8 @@ OS X에선 사용자가 Finder에서 어플리케이션의 두 번째 인스턴 메커니즘이 무시되며 그대로 중복 실행됩니다. 따라서 OS X에서도 이 메서드를 통해 확실히 중복 실행을 방지하는 것이 좋습니다. -다음 예제는 두 번째 인스턴스가 생성되었을 때 중복된 인스턴스를 종료하고 주 어플리케이션 -인스턴스의 윈도우를 활성화 시키는 예제입니다: +다음 예시는 두 번째 인스턴스가 생성되었을 때 중복된 인스턴스를 종료하고 주 어플리케이션 +인스턴스의 윈도우를 활성화 시키는 예시입니다: ```javascript var myWindow = null; diff --git a/docs-translations/ko-KR/api/auto-updater.md b/docs-translations/ko-KR/api/auto-updater.md index e699108a649..a551459171d 100644 --- a/docs-translations/ko-KR/api/auto-updater.md +++ b/docs-translations/ko-KR/api/auto-updater.md @@ -1,9 +1,12 @@ # autoUpdater -이 모듈은 `Squirrel` 자동 업데이트 프레임워크의 인터페이스를 제공합니다. +> 어플리케이션이 자동으로 업데이트를 진행할 수 있도록 기능을 활성화합니다. -다음 프로젝트 중 하나를 택하여 사용하면, 어플리케이션을 배포하기 위한 멀티 플랫폼 -릴리즈 서버를 손쉽게 구축할 수 있습니다: +`autoUpdater` 모듈은 [Squirrel](https://github.com/Squirrel) 프레임워크에 대한 +인터페이스를 제공합니다. + +다음 프로젝트 중 하나를 선택하여, 어플리케이션을 배포하기 위한 멀티-플랫폼 릴리즈 +서버를 손쉽게 구축할 수 있습니다: - [electron-release-server][electron-release-server]: *완벽하게 모든 기능을 지원하는 electron 어플리케이션을 위한 자가 호스트 릴리즈 서버입니다. auto-updater와 diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index 9ba61bea57f..76257c8463b 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -1,8 +1,8 @@ # BrowserWindow -`BrowserWindow` 클래스는 브라우저 창(윈도우)을 만드는 역할을 담당합니다. +> 브라우저 윈도우를 생성하고 제어합니다. -다음 예제는 윈도우를 생성합니다: +다음 예시는 윈도우를 생성합니다: ```javascript // 메인 프로세스에서 @@ -72,7 +72,7 @@ win.show(); * `show` Boolean - 윈도우가 생성되면 보여줄지 여부. 기본값은 `true`입니다. * `frame` Boolean - `false`로 지정하면 창을 [Frameless Window](frameless-window.md) 형태로 생성합니다. 기본값은 `true`입니다. -* `acceptFirstMouse` Boolean - 윈도우가 비활성화 상태일 때 내부 컨텐츠 클릭 시 +* `acceptFirstMouse` Boolean - 윈도우가 비활성화 상태일 때 내부 콘텐츠 클릭 시 활성화 되는 동시에 단일 mouse-down 이벤트를 발생시킬지 여부. 기본값은 `false`입니다. * `disableAutoHideCursor` Boolean - 타이핑중 자동으로 커서를 숨길지 여부. 기본값은 `false`입니다. @@ -112,7 +112,7 @@ win.show(); 값을 사용할 수 있습니다: * `default` 또는 미지정: 표준 Mac 회색 불투명 스타일을 사용합니다. -* `hidden`: 타이틀 바를 숨기고 컨텐츠 전체를 윈도우 크기에 맞춥니다. +* `hidden`: 타이틀 바를 숨기고 콘텐츠 전체를 윈도우 크기에 맞춥니다. 타이틀 바는 없어지지만 표준 창 컨트롤 ("신호등 버튼")은 왼쪽 상단에 유지됩니다. * `hidden-inset`: `hidden` 타이틀 바 속성과 함께 신호등 버튼이 윈도우 모서리로부터 약간 더 안쪽으로 들어가도록합니다. @@ -125,7 +125,7 @@ win.show(); node API에 접근할 수 있습니다. 이 속성의 스크립트 경로는 절대 경로로 지정해야 합니다. node 통합이 비활성화되어있을 경우, preload 스크립트는 node의 global 심볼들을 다시 global 스코프로 다시 포함 시킬 수 있습니다. - [여기](process.md#event-loaded)의 예제를 참고하세요. + [여기](process.md#event-loaded)의 예시를 참고하세요. * `session` [Session](session.md#class-session) - 페이지에서 사용할 세션을 지정합니다. Session 객체를 직접적으로 전달하는 대신, 파티션 문자열을 받는 `partition` 옵션을 사용할 수도 있습니다. `session`과 `partition`이 같이 @@ -198,11 +198,11 @@ Returns: * `event` Event 윈도우가 닫히기 시작할 때 발생하는 이벤트입니다. -이 이벤트는 DOM의 `beforeunload` 와 `unload` 이벤트가 호출되기 전에 발생합니다. +이 이벤트는 DOM의 `beforeunload` 와 `unload` 이벤트 전에 발생합니다. `event.preventDefault()`를 호출하여 윈도우 종료를 취소할 수 있습니다. 보통 창을 닫아야 할지 결정하기 위해 `beforeunload` 이벤트를 사용하려고 할 것입니다. -이 이벤트는 윈도우 컨텐츠를 새로고칠 때도 발생합니다. +이 이벤트는 윈도우 콘텐츠를 새로고칠 때도 발생합니다. Electron에선 빈 문자열 또는 `false`를 전달할 경우 윈도우 종료를 취소합니다. 예시는 다음과 같습니다: @@ -481,21 +481,21 @@ var win = new BrowserWindow({ width: 800, height: 600 }); ### `win.setAspectRatio(aspectRatio[, extraSize])` _OS X_ -* `aspectRatio` 유지하려 하는 컨텐츠 뷰 일부의 종횡비 +* `aspectRatio` 유지하려 하는 콘텐츠 뷰 일부의 종횡비 * `extraSize` Object (optional) - 종횡비를 유지하는 동안 포함되지 않을 엑스트라 크기. * `width` Integer * `height` Integer 이 메서드는 윈도우의 종횡비를 유지하는 기능을 수행합니다. 엑스트라 크기는 개발자가 픽셀로 특정한 공간이 있을 때 종횡비 계산에서 제외됩니다. 이 API는 윈도우의 크기와 -컨텐츠 사이즈의 차이를 이미 고려하고 있습니다. +콘텐츠 사이즈의 차이를 이미 고려하고 있습니다. 일반 윈도우에서 작동하는 HD 비디오 플레이어와 관련된 컨트롤을 고려합니다. 만약 15 픽셀의 컨트롤이 왼쪽 가장자리에 있고 25 픽셀의 컨트롤이 오른쪽 가장자리에 있으며 50 픽셀의 컨트롤이 플레이어 밑에 있을 때 플레이어 자체가 16:9 종횡비(HD의 표준 종횡비는 @1920x1080)를 유지하기 위해선 이 함수를 16/9, [ 40, 50 ] 인수와 함께 -호출해야 합니다. 두번째 인수 엑스트라 크기는 존재하는 크기만 관여하고 컨텐츠 뷰 내의 -크기는 관여하지 않습니다. 그저 전체 컨텐츠 뷰 내에 있는 모든 엑스트라 너비, 높이 영역이 +호출해야 합니다. 두번째 인수 엑스트라 크기는 존재하는 크기만 관여하고 콘텐츠 뷰 내의 +크기는 관여하지 않습니다. 그저 전체 콘텐츠 뷰 내에 있는 모든 엑스트라 너비, 높이 영역이 합해집니다. ### `win.setBounds(options[, animate])` diff --git a/docs-translations/ko-KR/api/chrome-command-line-switches.md b/docs-translations/ko-KR/api/chrome-command-line-switches.md index babddd32755..7f1f4ced616 100644 --- a/docs-translations/ko-KR/api/chrome-command-line-switches.md +++ b/docs-translations/ko-KR/api/chrome-command-line-switches.md @@ -1,9 +1,10 @@ # 크롬 명령줄 스위치 지원 -크롬 명령줄(Command-Line) 스위치는 크롬 브라우저에서 제공되는 추가 옵션이며 -Electron에서도 지원합니다. [app][app]의 [ready][ready]이벤트가 작동하기 전에 -[app.commandLine.appendSwitch][append-switch] API를 사용하면 어플리케이션 내부에서 -스위치를 추가할 수 있습니다: +> Electron에서 지원하는 커맨드 명령줄 스위치입니다. + +어플리케이션 메인 스크립트의 [app][app] 모듈에서 [ready][ready] 이벤트가 실행되기 +전에 [app.commandLine.appendSwitch][append-switch]를 호출하면, 어플리케이션의 +명령줄 옵션을 추가로 지정할 수 있습니다: ```javascript const app = require('electron').app; diff --git a/docs-translations/ko-KR/api/clipboard.md b/docs-translations/ko-KR/api/clipboard.md index df6475ad611..83775dfa78b 100644 --- a/docs-translations/ko-KR/api/clipboard.md +++ b/docs-translations/ko-KR/api/clipboard.md @@ -1,7 +1,6 @@ # clipboard -`clipboard` 모듈은 복사/붙여넣기 작업을 수행하는 방법을 제공합니다. 다음 예제는 -클립보드에 문자열을 씁니다: +> 시스템 클립보드에 복사와 붙여넣기를 수행합니다. ```javascript const clipboard = require('electron').clipboard; @@ -27,7 +26,7 @@ console.log(clipboard.readText('selection')); * `type` String (optional) -클립보드 컨텐츠를 `plain text`로 반환합니다. +클립보드 콘텐츠를 `plain text`로 반환합니다. ### `clipboard.writeText(text[, type])` @@ -40,7 +39,7 @@ console.log(clipboard.readText('selection')); * `type` String (optional) -클립보드 컨텐츠를 `markup`으로 반환합니다. +클립보드 콘텐츠를 `markup`으로 반환합니다. ### `clipboard.writeHtml(markup[, type])` @@ -66,7 +65,7 @@ console.log(clipboard.readText('selection')); * `type` String (optional) -클립보드로부터 RTF 형식으로 컨텐츠를 읽어옵니다. +클립보드로부터 RTF 형식으로 콘텐츠를 읽어옵니다. ### `clipboard.writeRtf(text[, type])` @@ -79,7 +78,7 @@ console.log(clipboard.readText('selection')); * `type` String (optional) -클립보드에 저장된 모든 컨텐츠를 삭제합니다. +클립보드에 저장된 모든 콘텐츠를 삭제합니다. ### clipboard.availableFormats([type]) diff --git a/docs-translations/ko-KR/api/content-tracing.md b/docs-translations/ko-KR/api/content-tracing.md index ed73ce319f6..484197e2073 100644 --- a/docs-translations/ko-KR/api/content-tracing.md +++ b/docs-translations/ko-KR/api/content-tracing.md @@ -1,9 +1,10 @@ # contentTracing -`content-tracing` 모듈은 Chromium 컨텐츠 모듈단에서 생성된 데이터를 수집하고 -추적하는데 사용됩니다. 이 모듈은 웹 인터페이스를 포함하고 있지 않으며 크롬 -브라우저에서 `chrome://tracing/` 페이지를 열어 생성된 파일을 로드하면 결과를 볼 수 -있습니다. +> 성능상의 병목 현상과 느린 작업을 찾기 위해 Chromium의 콘텐츠 모듈에서 추적 데이터를 +수집합니다. + +이 모듈은 웹 인터페이스를 포함하고 있지 않으며 Chrome 브라우저에서 +`chrome://tracing/` 페이지를 열고 생성된 파일을 로드하면 결과를 볼 수 있습니다. ```javascript const contentTracing = require('electron').contentTracing; @@ -54,7 +55,7 @@ EnableRecording 요청을 받게 됩니다. 모든 child 프로세스가 `startR 필터는 `-` 접두사를 통해 특정 카테고리 그룹을 제외할 수 있습니다. 카테고리 패턴은 같은 리스트 내에서 포함과 제외를 함께 사용할 수 없습니다. -예제: +예시: * `test_MyTest*`, * `test_MyTest*,test_OtherStuff`, diff --git a/docs-translations/ko-KR/api/crash-reporter.md b/docs-translations/ko-KR/api/crash-reporter.md index e6174f3e1ef..90851f7ee5b 100644 --- a/docs-translations/ko-KR/api/crash-reporter.md +++ b/docs-translations/ko-KR/api/crash-reporter.md @@ -1,7 +1,6 @@ # crashReporter -`crash-reporter` 모듈은 어플리케이션의 크래시 정보를 자동으로 원격 서버에 -업로드하는데 사용합니다. +> 원격 서버에 크래시 정보를 보고합니다. 다음 예시는 윈격 서버에 어플리케이션 크래시 정보를 자동으로 보고하는 예시입니다: diff --git a/docs-translations/ko-KR/api/desktop-capturer.md b/docs-translations/ko-KR/api/desktop-capturer.md index 3b4f8c71983..0ee1b3e1d22 100644 --- a/docs-translations/ko-KR/api/desktop-capturer.md +++ b/docs-translations/ko-KR/api/desktop-capturer.md @@ -1,7 +1,7 @@ # desktopCapturer -`desktopCapturer` 모듈은 `getUserMedia`에서 사용 가능한 소스를 가져올 때 사용할 수 -있습니다. +> 마이크, 카메라 또는 화면에서 오디오, 비디오 그리고 이미지를 캡쳐하기 위한 +`getUserMedia` 소스를 나열합니다. ```javascript // 렌더러 프로세스 내부 diff --git a/docs-translations/ko-KR/api/dialog.md b/docs-translations/ko-KR/api/dialog.md index 8bf144077be..90d76df1669 100644 --- a/docs-translations/ko-KR/api/dialog.md +++ b/docs-translations/ko-KR/api/dialog.md @@ -1,8 +1,6 @@ # dialog -`dialog` 모듈은 파일 열기, 알림과 같은 네이티브 시스템의 대화 상자를 조작할 때 사용할 -수 있는 모듈입니다. 이 모듈을 사용하면 웹 어플리케이션에서 일반 네이티브 어플리케이션과 -비슷한 사용자 경험을 제공할 수 있습니다. +> 파일을 열거나 저장하고, 알림을 표시하기 위한 네이티브 시스템 대화 상자를 표시합니다. 다음 예시는 파일과 디렉터리를 다중으로 선택하는 대화 상자를 표시하는 예시입니다: @@ -126,9 +124,9 @@ OS X 또는 Windows에서 "확인", "취소"와 같은 순서로 버튼을 지 에러 메시지를 보여주는 대화 상자를 표시합니다. -이 API는 `app` 모듈의 `ready` 이벤트가 발생하기 전에 사용할 수 있습니다. 이 메서드는 +이 함수는 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 사용할 수 있습니다. 이 메서드는 보통 어플리케이션이 시작되기 전에 특정한 에러를 표시하기 위해 사용됩니다. 만약 -Linux에서 `ready` 이벤트가 호출되기 이전에 이 API를 호출할 경우, 메시지는 stderr를 +Linux에서 `ready` 이벤트가 발생하기 전에 이 API를 호출할 경우, 메시지는 stderr를 통해서 표시되며 GUI 대화 상자는 표시되지 않습니다. ## Sheets diff --git a/docs-translations/ko-KR/api/download-item.md b/docs-translations/ko-KR/api/download-item.md index 0356030d8fb..4267a41df71 100644 --- a/docs-translations/ko-KR/api/download-item.md +++ b/docs-translations/ko-KR/api/download-item.md @@ -1,5 +1,7 @@ # DownloadItem +> 원격 소스로부터의 파일 다운로드를 제어합니다. + `DownloadItem`은 EventEmitter를 상속받았으며 Electron의 다운로드 아이템을 표현합니다. 이 클래스 객체는 `Session` 모듈의 `will-download` 이벤트에 사용되며 사용자가 다운로드 아이템을 다룰 수 있도록 도와줍니다. diff --git a/docs-translations/ko-KR/api/environment-variables.md b/docs-translations/ko-KR/api/environment-variables.md index 465548e003d..55a5ac5385d 100644 --- a/docs-translations/ko-KR/api/environment-variables.md +++ b/docs-translations/ko-KR/api/environment-variables.md @@ -1,5 +1,7 @@ # 환경 변수 +> 어플리케이션의 구성과 동작을 코드 변경 없이 제어합니다. + Electron의 몇몇 동작은 명령 줄과 어플리케이션의 코드보다 먼저 초기화되어야 하므로 환경 변수에 의해 작동합니다. diff --git a/docs-translations/ko-KR/api/file-object.md b/docs-translations/ko-KR/api/file-object.md index eb7bd9a135b..6d7519a7ad2 100644 --- a/docs-translations/ko-KR/api/file-object.md +++ b/docs-translations/ko-KR/api/file-object.md @@ -1,8 +1,10 @@ # `File` 객체 -DOM의 File 인터페이스는 네이티브 파일을 추상화 합니다. 유저가 직접 HTML5 File API를 -이용하여 작업할 때 선택된 파일의 경로를 알 수 있도록 Electron은 파일의 실제 경로를 -담은 `path` 속성을 File 인터페이스에 추가하였습니다. +> HTML5 `File` API를 기본적인 파일 시스템의 파일처럼 사용합니다. + +DOM의 File 인터페이스는 네이티브 파일을 추상화 합니다. 사용자가 직접 HTML5 File +API를 사용하여 작업할 때 선택된 파일의 경로를 알 수 있도록, Electron은 파일의 실제 +경로를 담은 `path` 속성을 File 인터페이스에 추가했습니다. 다음 예시는 앱으로 드래그 앤 드롭한 파일의 실제 경로를 가져옵니다: diff --git a/docs-translations/ko-KR/api/frameless-window.md b/docs-translations/ko-KR/api/frameless-window.md index 747c7ed7881..199c3dcbd9f 100644 --- a/docs-translations/ko-KR/api/frameless-window.md +++ b/docs-translations/ko-KR/api/frameless-window.md @@ -1,5 +1,7 @@ # Frameless Window +> 툴바, 테두리, 시각적인 "chrome" 없이 윈도우를 엽니다. + Frameless Window는 [창 테두리](https://developer.mozilla.org/ko/docs/Glossary/Chrome)가 없는 윈도우를 말합니다. 이 기능은 윈도우의 일부분인 툴바와 같이 웹 페이지의 일부분이 아닌 부분을 보이지 않도록 합니다. [`BrowserWindow`](browser-window.md) 클래스의 diff --git a/docs-translations/ko-KR/api/global-shortcut.md b/docs-translations/ko-KR/api/global-shortcut.md index 6c01368a392..71b7ab00163 100644 --- a/docs-translations/ko-KR/api/global-shortcut.md +++ b/docs-translations/ko-KR/api/global-shortcut.md @@ -1,12 +1,14 @@ # globalSortcut +> 어플리케이션에 키보드 포커스가 없을 때도 키보드 이벤트를 받을 수 있도록 합니다. + `globalShortcut` 모듈은 운영체제의 전역 키보드 단축키를 등록/해제 하는 방법을 제공합니다. 이 모듈을 사용하여 사용자가 다양한 작업을 편하게 할 수 있도록 단축키를 정의 할 수 있습니다. **참고:** 등록된 단축키는 어플리케이션이 백그라운드로 작동(창이 포커스 되지 않음) 할 -때도 계속해서 작동합니다. 이 모듈은 `app` 모듈의 `ready` 이벤트 이전에 사용할 수 -없습니다. +때도 계속해서 작동합니다. 이 모듈은 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 +사용할 수 없습니다. ```javascript const electron = require('electron'); diff --git a/docs-translations/ko-KR/api/ipc-main.md b/docs-translations/ko-KR/api/ipc-main.md index cc44d48c4c9..8ae11a99815 100644 --- a/docs-translations/ko-KR/api/ipc-main.md +++ b/docs-translations/ko-KR/api/ipc-main.md @@ -1,5 +1,7 @@ # ipcMain +> 메인 프로세스에서 렌더러 프로세스로 비동기 통신을 합니다. + `ipcMain` 모듈은 [EventEmitter](https://nodejs.org/api/events.html) 클래스의 인스턴스입니다. 메인 프로세스에서 사용하면, 렌더러 프로세스(웹 페이지)에서 전달된 동기, 비동기 메시지를 주고 받는 방법을 제공합니다. 렌더러 프로세스에서 메시지를 전달하면 diff --git a/docs-translations/ko-KR/api/ipc-renderer.md b/docs-translations/ko-KR/api/ipc-renderer.md index a25900453a7..19681515fef 100644 --- a/docs-translations/ko-KR/api/ipc-renderer.md +++ b/docs-translations/ko-KR/api/ipc-renderer.md @@ -1,5 +1,7 @@ # ipcRenderer +> 렌더러 프로세스에서 메인 프로세스로 비동기 통신을 합니다. + `ipcRenderer` 모듈은 [EventEmitter](https://nodejs.org/api/events.html) 클래스의 인스턴스입니다. 렌더러 프로세스에서 메인 프로세스로 동기/비동기 메시지를 주고 받는 방법을 제공합니다. 또한 메인 프로세스로부터 받은 메시지에 응답할 수도 있습니다. diff --git a/docs-translations/ko-KR/api/menu-item.md b/docs-translations/ko-KR/api/menu-item.md index c34a53402ca..022e554688a 100644 --- a/docs-translations/ko-KR/api/menu-item.md +++ b/docs-translations/ko-KR/api/menu-item.md @@ -1,7 +1,6 @@ # MenuItem -`menu-item` 모듈은 어플리케이션 또는 컨텍스트 [`menu`](menu.md)에 항목 아이템을 -추가할 수 있도록 관련 클래스를 제공합니다. +> 네이티브 어플리케이션 메뉴와 컨텍스트 메뉴에 아이템을 추가합니다. [`menu`](menu.md)에서 예시를 확인할 수 있습니다. diff --git a/docs-translations/ko-KR/api/menu.md b/docs-translations/ko-KR/api/menu.md index 3c55d70c4b7..30990380d69 100644 --- a/docs-translations/ko-KR/api/menu.md +++ b/docs-translations/ko-KR/api/menu.md @@ -1,8 +1,9 @@ # Menu -`menu` 클래스는 어플리케이션 메뉴와 [컨텍스트 메뉴](https://developer.mozilla.org/ko/docs/Mozilla/Tech/XUL/PopupGuide/ContextMenus)를 -만들 때 사용됩니다. 이 모듈은 메인 프로세스용 모듈이지만 `remote` 모듈을 통해 렌더러 -프로세스에서도 사용할 수 있습니다. +> 네이티브 어플리케이션 메뉴와 컨텍스트 메뉴를 생성합니다. + +이 모듈은 메인 프로세스용 모듈이지만 `remote` 모듈을 통해 렌더러 프로세스에서도 사용할 +수 있습니다. 각 메뉴는 여러 개의 [메뉴 아이템](menu-item.md)으로 구성되고 서브 메뉴를 가질 수도 있습니다. diff --git a/docs-translations/ko-KR/api/native-image.md b/docs-translations/ko-KR/api/native-image.md index bc55e4913b1..95f213924f7 100644 --- a/docs-translations/ko-KR/api/native-image.md +++ b/docs-translations/ko-KR/api/native-image.md @@ -1,5 +1,7 @@ # nativeImage +> PNG 또는 JPG 파일을 사용하여 트레이, 독, 어플리케이션 아이콘을 생성합니다. + Electron은 파일 경로 또는 `nativeImage` 인스턴스를 통해 이미지를 사용할 수 있는 API를 가지고 있습니다. `null`을 전달할 경우 빈 이미지가 생성됩니다. diff --git a/docs-translations/ko-KR/api/power-monitor.md b/docs-translations/ko-KR/api/power-monitor.md index 9f543cd1921..d2f1635dfcc 100644 --- a/docs-translations/ko-KR/api/power-monitor.md +++ b/docs-translations/ko-KR/api/power-monitor.md @@ -1,9 +1,9 @@ # powerMonitor -`power-monitor` 모듈은 PC의 파워 상태를 나타냅니다. (주로 노트북 등에서 사용됩니다) -이 모듈은 메인 프로세스에서만 사용할 수 있으며, (remote 모듈(RPC)을 사용해도 작동이 -됩니다) 메인 프로세스의 `app` 모듈에서 `ready` 이벤트를 호출하기 전까지 사용할 수 -없습니다. +> 파워의 상태 변경을 모니터링합니다. + +이 모듈은 메인 프로세스에서만 사용할 수 있습니다. `app` 모듈의 `ready` 이벤트가 +발생한 이후에만 사용할 수 없습니다. 예시: diff --git a/docs-translations/ko-KR/api/power-save-blocker.md b/docs-translations/ko-KR/api/power-save-blocker.md index 4754f0e88bd..4a4f85c76c5 100644 --- a/docs-translations/ko-KR/api/power-save-blocker.md +++ b/docs-translations/ko-KR/api/power-save-blocker.md @@ -1,7 +1,6 @@ # powerSaveBlocker -`powerSaveBlocker` 모듈은 시스템이 저전력(슬립) 모드로 진입하는 것을 막고 앱 시스템과 -화면이 항상 활성화 상태를 유지할 수 있도록 하는 몇가지 유틸리티를 제공하는 모듈입니다. +> 시스템이 저전력 (슬립) 모드로 진입하는 것을 막습니다. 예시: diff --git a/docs-translations/ko-KR/api/process.md b/docs-translations/ko-KR/api/process.md index 3cdc10dd78c..a3c72a1d996 100644 --- a/docs-translations/ko-KR/api/process.md +++ b/docs-translations/ko-KR/api/process.md @@ -1,5 +1,7 @@ # process +> 현재 작동중인 어플리케이션의 정보를 가져옵니다. + Electron의 `process` 객체는 기존의 node와는 달리 약간의 차이점이 있습니다: * `process.type` String - 프로세스의 타입, `browser` (메인 프로세스) 또는 @@ -43,6 +45,10 @@ process.once('loaded', function() { `process` 객체는 다음과 같은 메서드를 가지고 있습니다: +### `process.crash()` + +현재 프로세스의 메인 스레드에 크래시를 일으킵니다. + ### `process.hang()` 현재 프로세스의 주 스레드를 중단시킵니다. diff --git a/docs-translations/ko-KR/api/protocol.md b/docs-translations/ko-KR/api/protocol.md index 5df6db37e60..51207f8e0ee 100644 --- a/docs-translations/ko-KR/api/protocol.md +++ b/docs-translations/ko-KR/api/protocol.md @@ -1,7 +1,6 @@ # protocol -`protocol` 모듈은 이미 있는 프로토콜의 동작을 가로채거나 새로운 프로토콜을 만들 수 -있는 기능을 제공합니다. +> 커스텀 프로토콜을 등록하거나 이미 존재하능 프로토콜의 요청의 동작을 변경합니다. 다음 예시는 `file://` 프로토콜과 비슷한 일을 하는 커스텀 프로토콜을 설정합니다: diff --git a/docs-translations/ko-KR/api/remote.md b/docs-translations/ko-KR/api/remote.md index 8c3583a159f..5e1446b5343 100644 --- a/docs-translations/ko-KR/api/remote.md +++ b/docs-translations/ko-KR/api/remote.md @@ -1,5 +1,7 @@ # remote +> 메인 프로세스 모듈을 렌더러 프로세스에서 사용합니다. + `remote` 모듈은 메인 프로세스와 렌더러 프로세스(웹 페이지) 사이의 inter-process (IPC) 통신을 간단하게 추상화 한 모듈입니다. diff --git a/docs-translations/ko-KR/api/screen.md b/docs-translations/ko-KR/api/screen.md index db832852f3d..4d66a885d52 100644 --- a/docs-translations/ko-KR/api/screen.md +++ b/docs-translations/ko-KR/api/screen.md @@ -1,6 +1,7 @@ # screen -`screen` 모듈은 화면 크기, 디스플레이, 커서 위치 등등의 다양한 정보를 가져옵니다. +> 화면 크기, 디스플레이, 커서 위치 등의 정보를 가져옵니다. + 이 모듈은 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 사용할 수 없습니다. (호출 또는 모듈 포함) @@ -8,10 +9,10 @@ 상속 받았습니다. **참고:** 렌더러 / DevTools에선 이미 DOM 속성이 `window.screen`을 가지고 있으므로 -`screen = require('screen')` 형식으로 모듈을 사용할 수 없습니다. 아래의 예제와 같이 +`screen = require('screen')` 형식으로 모듈을 사용할 수 없습니다. 아래의 예시와 같이 `electronScreen` 같은 이름으로 모듈 이름을 대체하여 사용해야 합니다. -다음 예제는 화면 전체를 채우는 윈도우 창을 생성합니다: +다음 예시는 화면 전체를 채우는 윈도우 창을 생성합니다: ```javascript const electron = require('electron'); @@ -27,7 +28,7 @@ app.on('ready', function() { }); ``` -다음 예제는 확장 디스플레이에 윈도우를 생성합니다: +다음 예시는 확장 디스플레이에 윈도우를 생성합니다: ```javascript var app = require('app'); @@ -63,8 +64,8 @@ app.on('ready', function() { * `display` object * `id` Integer - 디스플레이에 관련된 유일 식별자. - * `rotation` Integer - 값은 0, 1, 2, 3이 될 수 있고, 각 값은 시계 방향을 기준으로 - 0, 90, 180, 270도의 화면 회전 상태로 표현됩니다. + * `rotation` Integer - 값은 0, 90, 180, 270이 될 수 있고, 각 값은 시계 방향을 + 기준으로 0, 90, 180, 270도의 화면 회전 상태를 표현합니다. * `scaleFactor` Number - 기기의 픽셀 스케일 크기. * `touchSupport` String - 터치 스크린의 여부, `available`, `unavailable`, `unknown` 값으로 반환됩니다. diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index d6a782e3a45..a4f3d3dd706 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -1,5 +1,7 @@ # session +> 브라우저 세션, 쿠키, 캐시, 프록시 설정 등을 관리합니다. + `session` 모듈은 새로운 `Session` 객체를 만드는데 사용할 수 있습니다. 또한 존재하는 [`BrowserWindow`](browser-window.md)의 diff --git a/docs-translations/ko-KR/api/shell.md b/docs-translations/ko-KR/api/shell.md index 552584f170b..2882bdce6fb 100644 --- a/docs-translations/ko-KR/api/shell.md +++ b/docs-translations/ko-KR/api/shell.md @@ -1,5 +1,7 @@ # shell +> 파일과 URL을 각 기본 어플리케이션을 통해 관리합니다. + `shell` 모듈은 데스크톱 환경 통합에 관련한 유틸리티를 제공하는 모듈입니다. 다음 예시는 설정된 URL을 유저의 기본 브라우저로 엽니다: diff --git a/docs-translations/ko-KR/api/synopsis.md b/docs-translations/ko-KR/api/synopsis.md index 3493223cceb..02d269be241 100644 --- a/docs-translations/ko-KR/api/synopsis.md +++ b/docs-translations/ko-KR/api/synopsis.md @@ -1,5 +1,7 @@ # 개요 +> Node.js와 Electron API를 사용하는 방법. + Electron은 모든 [Node.js의 built-in 모듈](http://nodejs.org/api/)과 third-party node 모듈을 완벽하게 지원합니다. ([네이티브 모듈](../tutorial/using-native-node-modules.md) 포함) diff --git a/docs-translations/ko-KR/api/tray.md b/docs-translations/ko-KR/api/tray.md index b0293d40fcb..6162557e1a7 100644 --- a/docs-translations/ko-KR/api/tray.md +++ b/docs-translations/ko-KR/api/tray.md @@ -1,7 +1,6 @@ # Tray -`Tray`는 OS의 알림 영역에 아이콘을 표시합니다. 보통 컨텍스트 메뉴(context menu)를 -같이 사용합니다. +> 아이콘과 컨텍스트 메뉴를 시스템 알림 영역에 추가합니다. ```javascript const electron = require('electron'); diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 466ce9759bd..fa6b69b61bc 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -1,5 +1,7 @@ # webContents +> 웹 페이지를 렌더링하고 제어합니다. + `webContents`는 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)를 상속받았습니다. 웹 페이지의 렌더링과 관리를 책임지며 [`BrowserWindow`](browser-window.md)의 속성입니다. 다음은 `webContents` 객체에 diff --git a/docs-translations/ko-KR/api/web-frame.md b/docs-translations/ko-KR/api/web-frame.md index 292f7d81420..4b9ade4bebe 100644 --- a/docs-translations/ko-KR/api/web-frame.md +++ b/docs-translations/ko-KR/api/web-frame.md @@ -1,9 +1,8 @@ # webFrame -`web-frame` 모듈은 현재 웹 페이지의 렌더링 상태를 설정 할 수 있도록 관련 유틸리티를 -제공하는 모듈입니다. +> 현재 웹 페이지의 렌더링 상태를 커스터마이즈합니다. -다음 예제는 현재 페이지를 200% 줌 합니다: +다음 예시는 현재 페이지를 200% 줌 합니다: ```javascript var webFrame = require('electron').webFrame; @@ -13,7 +12,7 @@ webFrame.setZoomFactor(2); ## Methods -`web-frame` 모듈은 다음과 같은 메서드를 가지고 있습니다: +`webFrame` 모듈은 다음과 같은 메서드를 가지고 있습니다: ### `webFrame.setZoomFactor(factor)` @@ -56,7 +55,7 @@ Input field나 text area에 철자 검사(spell checking) 제공자를 설정합 `provider`는 반드시 전달된 단어의 철자가 맞았는지 검사하는 `spellCheck` 메소드를 가지고 있어야 합니다. -[node-spellchecker][spellchecker]를 철자 검사 제공자로 사용하는 예제입니다: +[node-spellchecker][spellchecker]를 철자 검사 제공자로 사용하는 예시입니다: ```javascript webFrame.setSpellCheckProvider("en-US", true, { @@ -72,14 +71,14 @@ webFrame.setSpellCheckProvider("en-US", true, { `scheme`을 보안 스킴으로 등록합니다. -보안 스킴은 혼합된 컨텐츠 경고를 발생시키지 않습니다. 예를 들어 `https` 와 `data`는 +보안 스킴은 혼합된 콘텐츠 경고를 발생시키지 않습니다. 예를 들어 `https` 와 `data`는 네트워크 공격자로부터 손상될 가능성이 없기 때문에 보안 스킴이라고 할 수 있습니다. ### `webFrame.registerURLSchemeAsBypassingCSP(scheme)` * `scheme` String -현재 페이지 컨텐츠의 보안 정책에 상관없이 `scheme`로부터 리소스가 로드됩니다. +현재 페이지 콘텐츠의 보안 정책에 상관없이 `scheme`로부터 리소스가 로드됩니다. ### `webFrame.registerURLSchemeAsPrivileged(scheme)` diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index 743fcc5e325..ae446975ef2 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -1,5 +1,7 @@ # `` 태그 +> 외부 웹 콘텐츠를 고립된 프레임과 프로세스에서 표시합니다. + `guest` 콘텐츠(웹 페이지)를 Electron 앱 페이지에 삽입하기 위해 `webview` 태그를 사용할 수 있습니다. 게스트 콘텐츠는 `webview` 컨테이너에 담겨 대상 페이지에 삽입되고 해당 페이지에선 게스트 콘텐츠의 배치 및 렌더링 과정을 조작할 수 있습니다. diff --git a/docs-translations/ko-KR/api/window-open.md b/docs-translations/ko-KR/api/window-open.md index 8969160c9ac..259b08dc596 100644 --- a/docs-translations/ko-KR/api/window-open.md +++ b/docs-translations/ko-KR/api/window-open.md @@ -1,5 +1,7 @@ # `window.open` 함수 +> 새 윈도우를 열고 URL을 로드합니다. + `window.open` 함수가 호출되면 새 창을 생성하고 `url` 페이지를 불러옵니다. 이 창은 지정한 `url`을 로드하여 만들어진 `BrowserWindow`의 새 인스턴스이며 본래 창 객체 대신 페이지의 컨트롤이 제한된 프록시 객체를 반환합니다. diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index 45342f14de2..8fd25a303af 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -66,7 +66,7 @@ Apple로부터 인증서를 취득했다면, [어플리케이션 배포](applica # 어플리케이션의 이름 APP="YourApp" # 서명할 어플리케이션의 경로 -APP_PATH="/path/to/YouApp.app" +APP_PATH="/path/to/YourApp.app" # 서명된 패키지의 출력 경로 RESULT_PATH="~/Desktop/$APP.pkg" # 요청한 인증서의 이름 diff --git a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md index 1437bbde92c..ed3caaabf43 100644 --- a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md +++ b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md @@ -12,8 +12,8 @@ Pepper 플래시 플러그인을 사용하려면 Pepper 플래시 플러그인 ## Electron 스위치 추가 플러그인을 사용하려면 Electron 커맨드 라인에 `--ppapi-flash-path` 와 -`ppapi-flash-version` 플래그를 app의 ready 이벤트가 호출되기 전에 추가해야 합니다. -그리고 `browser-window`에 `plugins` 스위치도 추가해야 합니다. +`ppapi-flash-version` 플래그를 `app`의 `ready` 이벤트가 발생하기 전에 추가해야 +합니다. 그리고 `browser-window`에 `plugins` 스위치도 추가해야 합니다. ```javascript // 플래시 플러그인의 위치를 설정합니다. From a554f9e6832846b248e331c46c6155a7b35d9c5a Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 1 May 2016 02:10:23 +0900 Subject: [PATCH 0666/1265] :memo: Update Korean docs as upstream [ci skip] --- .../ko-KR/tutorial/quick-start.md | 77 +++++++++++-------- 1 file changed, 47 insertions(+), 30 deletions(-) diff --git a/docs-translations/ko-KR/tutorial/quick-start.md b/docs-translations/ko-KR/tutorial/quick-start.md index bdd151f1535..7d64811f5fd 100644 --- a/docs-translations/ko-KR/tutorial/quick-start.md +++ b/docs-translations/ko-KR/tutorial/quick-start.md @@ -75,45 +75,61 @@ __알림__: 만약 `main` 필드가 `package.json`에 설정되어 있지 않으 다음과 같이 작성할 수 있습니다: ```javascript -'use strict'; - -const electron = require('electron'); -const app = electron.app; // 어플리케이션 기반을 조작 하는 모듈. -const BrowserWindow = electron.BrowserWindow; // 네이티브 브라우저 창을 만드는 모듈. +const electron = require('electron') +// 어플리케이션 생명주기를 조작 하는 모듈. +const app = electron.app +// 네이티브 브라우저 창을 만드는 모듈. +const BrowserWindow = electron.BrowserWindow // 윈도우 객체를 전역에 유지합니다. 만약 이렇게 하지 않으면 // 자바스크립트 GC가 일어날 때 창이 멋대로 닫혀버립니다. -var mainWindow = null; +let mainWindow -// 모든 창이 닫히면 어플리케이션 종료. -app.on('window-all-closed', function() { - // OS X의 대부분의 어플리케이션은 유저가 Cmd + Q 커맨드로 확실하게 종료하기 전까지 - // 메뉴바에 남아 계속 실행됩니다. - if (process.platform != 'darwin') { - app.quit(); - } -}); - -// 이 메서드는 Electron의 초기화가 모두 끝나고 -// 브라우저 창을 열 준비가 되었을 때 호출됩니다. -app.on('ready', function() { +function createWindow () { // 새로운 브라우저 창을 생성합니다. - mainWindow = new BrowserWindow({width: 800, height: 600}); + mainWindow = new BrowserWindow({width: 800, height: 600}) // 그리고 현재 디렉터리의 index.html을 로드합니다. - mainWindow.loadURL('file://' + __dirname + '/index.html'); + mainWindow.loadURL('file://' + __dirname + '/index.html') // 개발자 도구를 엽니다. - mainWindow.webContents.openDevTools(); + mainWindow.webContents.openDevTools() // 창이 닫히면 호출됩니다. - mainWindow.on('closed', function() { - // 윈도우 객체의 참조를 삭제합니다 보통 멀티 윈도우 지원을 위해 + mainWindow.on('closed', function () { + // 윈도우 객체의 참조를 삭제합니다. 보통 멀티 윈도우 지원을 위해 // 윈도우 객체를 배열에 저장하는 경우가 있는데 이 경우 // 해당하는 모든 윈도우 객체의 참조를 삭제해 주어야 합니다. - mainWindow = null; - }); -}); + mainWindow = null + }) +} + +// 이 메서드는 Electron의 초기화가 끝나면 실행되며 브라우저 +// 윈도우를 생성할 수 있습니다. 몇몇 API는 이 이벤트 이후에만 +// 사용할 수 있습니다. +app.on('ready', createWindow) + +// 모든 창이 닫히면 어플리케이션 종료. +app.on('window-all-closed', function () { + // OS X의 대부분의 어플리케이션은 유저가 Cmd + Q 커맨드로 확실하게 + // 종료하기 전까지 메뉴바에 남아 계속 실행됩니다. + if (process.platform !== 'darwin') { + app.quit() + } +}) + +app.on('activate', function () { + // OS X에선 보통 독 아이콘이 클릭되고 나서도 + // 열린 윈도우가 없으면, 새로운 윈도우를 다시 만듭니다. + if (mainWindow === null) { + createWindow() + } +}) + +// 이 파일엔 제작할 어플리케이션에 특화된 메인 프로세스 코드를 +// 포함할 수 있습니다. 또한 파일을 분리하여 require하는 방법으로 +// 코드를 작성할 수도 있습니다. + ``` 마지막으로, 사용자에게 보여줄 `index.html` 웹 페이지의 예시입니다: @@ -140,12 +156,13 @@ app.on('ready', function() { 패키징 하고 패키징한 앱을 실행할 수 있습니다. 또한 Electron 실행파일을 다운로드 받아 바로 실행해 볼 수도 있습니다. -### electron-prebuilt 사용 +### electron-prebuilt -`npm`을 통해 `electron-prebuilt` 패키지를 전역에 설치하면 간단한 명령으로 앱을 -실행할 수 있습니다. +[`electron-prebuilt`](https://github.com/electron-userland/electron-prebuilt)는 +Electron의 미리 컴파일된 바이너리를 포함하는 `npm` 모듈입니다. -앱 디렉터리 내에서 다음 명령으로 실행할 수 있습니다: +만약 `npm`을 통해 전역에 이 모듈을 설치했다면, 어플리케이션 소스 디렉터리에서 다음 +명령을 실행하면 바로 실행할 수 있습니다: ```bash electron . From 33aecb9978ee6f0962944c33c032a0edcec59cf5 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Sun, 1 May 2016 02:46:19 +0900 Subject: [PATCH 0667/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/README.md | 1 + docs-translations/ko-KR/api/app.md | 55 +++++-------- .../ko-KR/api/system-preferences.md | 79 +++++++++++++++++++ .../tutorial/using-pepper-flash-plugin.md | 31 +++++--- 4 files changed, 119 insertions(+), 47 deletions(-) create mode 100644 docs-translations/ko-KR/api/system-preferences.md diff --git a/docs-translations/ko-KR/README.md b/docs-translations/ko-KR/README.md index 717bfd5ef30..c0949a83966 100644 --- a/docs-translations/ko-KR/README.md +++ b/docs-translations/ko-KR/README.md @@ -66,6 +66,7 @@ Electron에 대해 자주 묻는 질문이 있습니다. 이슈를 생성하기 * [powerSaveBlocker](api/power-save-blocker.md) * [protocol](api/protocol.md) * [session](api/session.md) +* [systemPreferences](api/system-preferences.md) * [webContents](api/web-contents.md) * [Tray](api/tray.md) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 86f4c7da923..1d6140435e7 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -379,7 +379,7 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 **참고:** OS X에선, 어플리케이션의 `info.plist`에 등록해둔 프로토콜만 사용할 수 있습니다. 이는 런타임에서 변경될 수 없습니다. 이 파일은 간단히 텍스트 에디터를 사용하거나, 어플리케이션을 빌드할 때 스크립트가 생성되도록 할 수 있습니다. 자세한 -내용은 [Apple의 참조 문서를][CFBundleURLTypes] 확인하세요. +내용은 [Apple의 참조 문서][CFBundleURLTypes]를 확인하세요. 이 API는 내부적으로 Windows 레지스트리와 LSSetDefaultHandlerForURLScheme를 사용합니다. @@ -392,6 +392,21 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 **참고:** OS X에서는 앱을 제거하면 자동으로 기본 프로토콜 핸들러에서 제거됩니다. +### `app.isDefaultProtocolClient(protocol)` _OS X_ _Windows_ + +* `protocol` String - `://`를 제외한 프로토콜의 이름. + +이 메서드는 현재 실행 파일이 지정한 프로토콜에 대해 기본 동작인지 확인합니다. (URI +스킴) 만약 그렇다면 `true`를 반환하고 아닌 경우 `false`를 반환합니다. + +**참고:** OS X에선, 응용 프로그램이 프로토콜에 대한 기본 프로토콜 동작으로 +등록되었는지를 확인하기 위해 이 메서드를 사용할 수 있습니다. 또한 OS X에서 +`~/Library/Preferences/com.apple.LaunchServices.plist`를 확인하여 검증할 수도 +있습니다. 자세한 내용은 [Apple의 참조 문서][LSCopyDefaultHandlerForURLScheme]를 +참고하세요. + +이 API는 내부적으로 Windows 레지스트리와 LSSetDefaultHandlerForURLScheme를 사용합니다. + ### `app.setUserTasks(tasks)` _Windows_ * `tasks` Array - `Task` 객체의 배열 @@ -480,42 +495,7 @@ app.on('ready', function() { * `id` String -[Application User Model ID][app-user-model-id]를 `id`로 변경합니다. - -### `app.isAeroGlassEnabled()` _Windows_ - -이 메서드는 [DWM 컴포지션](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx) -(Aero Glass)가 활성화 되어있을 때 `true`를 반환합니다. 아닌 경우 `false`를 반환합니다. -이 메서드는 투명한 윈도우를 만들기 위해 사용 가능 여부를 확인할 때 사용할 수 있습니다. -(투명한 윈도우는 DWM 컴포지션이 비활성화되어있을 시 작동하지 않습니다) - -사용 예시: - -```js -let browserOptions = {width: 1000, height: 800}; - -// 플랫폼이 지원하는 경우에만 투명 윈도우를 생성 -if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { - browserOptions.transparent = true; - browserOptions.frame = false; -} - -// 원도우 생성 -win = new BrowserWindow(browserOptions); - -// 페이지 로드 -if (browserOptions.transparent) { - win.loadURL('file://' + __dirname + '/index.html'); -} else { - // 투명 윈도우 상태가 아니라면, 기본적인 폴백 스타일 사용 - win.loadURL('file://' + __dirname + '/fallback.html'); -} -``` - -### `app.isDarkMode()` _OS X_ - -이 메서드는 시스템이 다크 모드 상태인 경우 `true`를 반환하고 아닐 경우 `false`를 -반환합니다. +[어플리케이션의 사용자 모델 ID][app-user-model-id]를 `id`로 변경합니다. ### `app.importCertificate(options, callback)` _LINUX_ @@ -596,3 +576,4 @@ dock 아이콘의 `image`를 설정합니다. [tasks]:http://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 +[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme diff --git a/docs-translations/ko-KR/api/system-preferences.md b/docs-translations/ko-KR/api/system-preferences.md new file mode 100644 index 00000000000..8db4cc32cef --- /dev/null +++ b/docs-translations/ko-KR/api/system-preferences.md @@ -0,0 +1,79 @@ +# systemPreferences + +> 시스템 설정을 가져옵니다. + +## Methods + +### `systemPreferences.isDarkMode()` _OS X_ + +이 메서드는 시스템이 어두운 모드 상태인 경우 `true`를 반환하고 아닐 경우 `false`를 +반환합니다. + +### `systemPreferences.subscribeNotification(event, callback)` _OS X_ + +* `event` String +* `callback` Function + +OS X의 네이티브 알림을 구독하며, 해당하는 `event`가 발생하면 `callback`이 호출됩니다. +구독자의 `id`가 반환되며 `event`를 구독 해제할 때 사용할 수 있습니다. + +이 API는 후드에서 `NSDistributedNotificationCenter`를 구독하며, `event`에서 사용 +가능한 값은 다음과 같습니다: + +* `AppleInterfaceThemeChangedNotification` +* `AppleAquaColorVariantChanged` +* `AppleColorPreferencesChangedNotification` +* `AppleShowScrollBarsSettingChanged` + +### `systemPreferences.unsubscribeNotification(id)` _OS X_ + +* `id` Integer + +`id`와 함께 구독자를 제거합니다. + +### `systemPreferences.getUserDefault(key, type)` _OS X_ + +* `key` String +* `type` String - `string`, `boolean`, `integer`, `float`, `double`, `url` 값이 + 될 수 있습니다. + +시스템 설정에서 `key`에 해당하는 값을 가져옵니다. + +OS X에선 API가 `NSUserDefaults`를 읽어들입니다. 유명한 `key`와 `type`은 다음과 +같습니다: + +* `AppleInterfaceStyle: string` +* `AppleAquaColorVariant: integer` +* `AppleHighlightColor: string` +* `AppleShowScrollBars: string` + +### `systemPreferences.isAeroGlassEnabled()` _Windows_ + +이 메서드는 [DWM 컴포지션][dwm-composition] (Aero Glass)가 활성화 되어있을 때 +`true`를 반환합니다. 아닌 경우 `false`를 반환합니다. + +다음은 투명한 윈도우를 만들지, 일반 윈도우를 만들지를 판단하여 윈도우를 생성하는 +예시입니다 (투명한 윈도우는 DWM 컴포지션이 비활성화되어있을 시 작동하지 않습니다): + +```javascript +let browserOptions = {width: 1000, height: 800}; + +// 플랫폼이 지원하는 경우에만 투명 윈도우를 생성. +if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { + browserOptions.transparent = true; + browserOptions.frame = false; +} + +// 원도우 생성 +let win = new BrowserWindow(browserOptions); + +// 페이지 로드. +if (browserOptions.transparent) { + win.loadURL('file://' + __dirname + '/index.html'); +} else { + // 투명 윈도우 상태가 아니라면, 기본적인 스타일 사용 + win.loadURL('file://' + __dirname + '/fallback.html'); +} +``` + +[dwm-composition]:https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx diff --git a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md index ed3caaabf43..37e1c4188df 100644 --- a/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md +++ b/docs-translations/ko-KR/tutorial/using-pepper-flash-plugin.md @@ -1,7 +1,8 @@ # Pepper 플래시 플러그인 사용하기 -Electron은 Pepper 플래시 플러그인을 지원합니다. -Pepper 플래시 플러그인을 사용하려면 Pepper 플래시 플러그인의 위치를 지정해야 합니다. +Electron은 Pepper 플래시 플러그인을 지원합니다. Electron에서 Pepper 플래시 +플러그인을 사용하려면 Pepper 플래시 플러그인의 위치를 지정한 후 어플리케이션 내에서 +활성화 시켜야 합니다. ## 플래시 플러그인 준비하기 @@ -13,28 +14,28 @@ Pepper 플래시 플러그인을 사용하려면 Pepper 플래시 플러그인 플러그인을 사용하려면 Electron 커맨드 라인에 `--ppapi-flash-path` 와 `ppapi-flash-version` 플래그를 `app`의 `ready` 이벤트가 발생하기 전에 추가해야 -합니다. 그리고 `browser-window`에 `plugins` 스위치도 추가해야 합니다. +합니다. 그리고 `browser-window`에 `plugins` 옵션을 활성화해야 합니다. ```javascript // 플래시 플러그인의 위치를 설정합니다. -// Windows의 경우, /path/to/pepflashplayer.dll +// Windows의 경우, /path/to/pepflashplayer.dll 또는 main.js에 존재하는 경우 pepflashplayer.dll // OS X의 경우, /path/to/PepperFlashPlayer.plugin // Linux의 경우, /path/to/libpepflashplayer.so app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'); -// Specify flash version, for example, v17.0.0.169 +// 선택적인으로 플래시 플레이어의 버전을 설정합니다. 예시로는, v17.0.0.169 app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169'); app.on('ready', function() { mainWindow = new BrowserWindow({ - 'width': 800, - 'height': 600, - 'web-preferences': { - 'plugins': true + width: 800, + height: 600, + webPreferences: { + plugins: true } }); mainWindow.loadURL('file://' + __dirname + '/index.html'); - // Something else + // 이외의 코드 }); ``` @@ -45,3 +46,13 @@ app.on('ready', function() { ```html ``` + +## 문제 해결 + +개발자 도구의 콘솔에서 `navigator.plugins`를 탐색하면 Pepper 플래시 플러그인이 잘 +로드되었는지를 확인할 수 있습니다. (물론 플러그인의 경로를 잘 설정하지 않으면 확인할 +수 없습니다) + +Pepper 플래시 플러그인의 구조는 Electron과 일치해야 합니다. Windows에서 자주 +발생하는 문제는 32비트 버전의 플래시 플레이어를 64비트 버전의 Electron에서 사용하는 +것입니다. From 05493502ea48e3bd2713be11ce62858d5d65b15c Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Sat, 30 Apr 2016 11:17:29 -0700 Subject: [PATCH 0668/1265] Value first, key second. --- atom/browser/browser_mac.mm | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 627ed65dccd..a12bd8c8809 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -69,7 +69,7 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { return false; NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()]; - + CFStringRef bundle = LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)); NSString* bundleId = static_cast( @@ -77,7 +77,7 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { if (!bundleId) return false; - // Ensure the comparison is case-insensitive + // Ensure the comparison is case-insensitive // as LS does not persist the case of the bundle id. NSComparisonResult result = [bundleId caseInsensitiveCompare:identifier]; @@ -93,11 +93,11 @@ void Browser::SetUserActivity(const std::string& type, const std::map Date: Sat, 30 Apr 2016 13:03:10 -0700 Subject: [PATCH 0669/1265] :memo: about the plist changes. --- docs/api/app.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/api/app.md b/docs/api/app.md index 04f91b3a904..61e86b70f9a 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -123,6 +123,11 @@ Emitted during [handoff](https://developer.apple.com/library/ios/documentation/U resumed. You should call `event.preventDefault()` if you want to handle this event. +A user activity can be continued only in an app that has the same developer +Team ID as the activity's source app and that supports the activity's type. +Supported activity types are specified in the app's Info.plist under the +`NSUserActivityTypes` key. + ### Event: 'browser-window-blur' Returns: From abb60ecd2ee58226b8c83249cd388ed028ffed69 Mon Sep 17 00:00:00 2001 From: Adam Buckland Date: Sun, 1 May 2016 11:25:27 +0100 Subject: [PATCH 0670/1265] Fix autoUpdater error on OS X If there is no localizedFailureReason, then then this will no longer be added to the error string (which would result previously in it printing '(null)' as part of the string) --- atom/browser/auto_updater_mac.mm | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/atom/browser/auto_updater_mac.mm b/atom/browser/auto_updater_mac.mm index 9af920f5929..edc6972d16d 100644 --- a/atom/browser/auto_updater_mac.mm +++ b/atom/browser/auto_updater_mac.mm @@ -90,9 +90,14 @@ void AutoUpdater::CheckForUpdates() { delegate->OnUpdateNotAvailable(); } } error:^(NSError *error) { - delegate->OnError(base::SysNSStringToUTF8( - [NSString stringWithFormat:@"%@: %@", - error.localizedDescription, error.localizedFailureReason])); + NSString *failureString; + if(error.localizedFailureReason) { + failureString = [NSString stringWithFormat:@"%@: %@", + error.localizedDescription, error.localizedFailureReason]; + } else { + failureString = [NSString stringWithString: error.localizedDescription]; + } + delegate->OnError(base::SysNSStringToUTF8(failureString)); }]; } From 91911d2d3222195c1fa907b99e7f982dc70d318e Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sat, 30 Apr 2016 17:50:04 +0200 Subject: [PATCH 0671/1265] Fix systemPreferences docs --- docs/api/system-preferences.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md index 8fdd2b54cb0..df7ef89e65c 100644 --- a/docs/api/system-preferences.md +++ b/docs/api/system-preferences.md @@ -59,7 +59,7 @@ not (transparent windows won't work correctly when DWM composition is disabled): let browserOptions = {width: 1000, height: 800}; // Make the window transparent only if the platform supports it. -if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { +if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true; browserOptions.frame = false; } From 6cb8f278a2fff97b6906cc84529d304835a24b96 Mon Sep 17 00:00:00 2001 From: TyanNN Date: Sun, 1 May 2016 21:18:49 +0300 Subject: [PATCH 0672/1265] Translated application distribution and application packaging to ru_RU --- .../tutorial/application-distribution.md | 126 ++++++++++++ .../ru-RU/tutorial/application-packaging.md | 179 ++++++++++++++++++ 2 files changed, 305 insertions(+) create mode 100644 docs-translations/ru-RU/tutorial/application-distribution.md create mode 100644 docs-translations/ru-RU/tutorial/application-packaging.md diff --git a/docs-translations/ru-RU/tutorial/application-distribution.md b/docs-translations/ru-RU/tutorial/application-distribution.md new file mode 100644 index 00000000000..e8ddd9f22f2 --- /dev/null +++ b/docs-translations/ru-RU/tutorial/application-distribution.md @@ -0,0 +1,126 @@ +# Распространение приложения + +Чтобы разпространять ваше приложение на Electron, папка с вашим приложением +должна называться `app` и находиться в папке ресурсов Electron (на OS X это +`Electron.app/Contents/Resources/`, на Linux и Windows - `resources/`), +вот так: + +На OS X: + +```text +electron/Electron.app/Contents/Resources/app/ +├── package.json +├── main.js +└── index.html +``` + +На Windows и Linux: + +```text +electron/resources/app +├── package.json +├── main.js +└── index.html +``` + +Затем запустите `Electron.app` (или `electron` на Linux, `electron.exe` на Windows), +и Electron запустится как ваше приложение. Теперь папка `electron` и есть дистрибутив, +который вы должны распространять пользователям. + +## Упаковка вашего приложения в файл + +Если вы не хотите распространять исходные коды вашего проект, вы можете +упаковать его в архив [asar](https://github.com/atom/asar), чтобы не +показывать пользователям исходные коды. + +Чтобы использовать `asar` для замены папки `app` на архив вам нужно +переименовать архив в `app.asar` и положить его в папку ресурсов Electron, +после чего Electron попробует считать ресурсы и запустить архив. + + +На OS X: + +```text +electron/Electron.app/Contents/Resources/ +└── app.asar +``` + +На Windows и Linux: + +```text +electron/resources/ +└── app.asar +``` + +Больше деталей можна найти в [инстуркции по упаковке приложения](application-packaging.md). + +## Ребрендирование скачанных исполняемых файлов +После того, как вы подключили ваше приложение к Electron, +вам наверняка захочеться ребрендировать его перед распространением. + +### Windows + +Вы можете переименовать `electron.exe` как пожелаете и поменять иконку и прочую +информацию приложениями вроде [rcedit](https://github.com/atom/rcedit). + +### OS X + +Вы можете переименовать `Electron.app` как пожелаете, а также изменить +поля `CFBundleDisplayName`, `CFBundleIdentifier` и `CFBundleName` в следующих +файлах: + +* `Electron.app/Contents/Info.plist` +* `Electron.app/Contents/Frameworks/Electron Helper.app/Contents/Info.plist` + +Вы таже можете переименовать приложение-помощник, чтобы оно не показывало `Electron Helper`, +убедитесь, что вы переименовали его исполняемый файл. + +Структура переименованного приложения выглядит примерно так: + +``` +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 + +Вы можете переименовать исполняемый файл `electron` как пожелаете. + +## Rebranding by Rebuilding Electron from Source + +Вы также можете ребрендировать Electron изменив имя продукиа и собрав его +из исходных кодов. Чтобы сделать это вам нужно изменить `atom.gyp` и полностью +пересобрать Electron. + +### grunt-build-atom-shell + +Проверка и пересборка кода Electron довольно сложная задача, так что мы +мы сделали файл-инструкцию для Grunt, который будет делать это автоматически: +[grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell). + +Этот файл автоматически просмотрит изменения в `.gyp` фалле, соберёт +Electron из исходных кодов и пересоберёт модули Node, чтобы всё подходило +под новое имя. + +## Инструменты + +Вы также можете использовать инструменты оттретьих лиц, +которые сделают работу за вас: + +* [electron-packager](https://github.com/maxogden/electron-packager) +* [electron-builder](https://github.com/loopline-systems/electron-builder) diff --git a/docs-translations/ru-RU/tutorial/application-packaging.md b/docs-translations/ru-RU/tutorial/application-packaging.md new file mode 100644 index 00000000000..b63565ed7b8 --- /dev/null +++ b/docs-translations/ru-RU/tutorial/application-packaging.md @@ -0,0 +1,179 @@ +# Упаковка приложения + +Чтобы смягчить [проблемы](https://github.com/joyent/node/issues/6960) с длинными +именами под Windows, немного ускорить `require` и скрыть ваши исходные коды, вы +можете упаковать его в архив [asar][asar], немного поменяв исходный код. + +## Генерация архива `asar` + +Архив [asar][asar] - простой фомат похожий на tar, который собирает много файлов +в один. Electron может читать такой файл без распаковки. + +Шаги для упавки вашего приложения архив `asar`: + +### 1. Установите саму утилиту asar + +```bash +$ npm install -g asar +``` + +### 2. Упакуйте с помощью `asar pack` + +```bash +$ asar pack your-app app.asar +``` + +## Использование архивов `asar` + +В Electron есть два вида API: API Node, которые устанавливаются с помощью Node.Js и +веб API, которые предоставляюся Chromium. Оба предоставляют возможность считывать из +архивов `asar`. + +### Node API + +С специальными патчами в Electron, части Node API вроде `fs.readFile` и `require` +считают архивы `asar` виртуальными папками и файлы в них доступны как в обычных. + +Например, у нас есть арихив `example.asar` в `/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 +``` + +Прочитаеем файл в архиве `asar`: + +```javascript +const fs = require('fs'); +fs.readFileSync('/path/to/example.asar/file.txt'); +``` + +Список всех файлов начиная от корня архива: + +```javascript +const fs = require('fs'); +fs.readdirSync('/path/to/example.asar'); +``` + +Ичпользуем модуль из архива: + +```javascript +require('/path/to/example.asar/dir/module.js'); +``` + +Вы также можете показывать веб страницы из архива `asar` через `BrowserWindow`: + +```javascript +const BrowserWindow = require('electron').BrowserWindow; +var win = new BrowserWindow({width: 800, height: 600}); +win.loadURL('file:///path/to/example.asar/static/index.html'); +``` + +### Веб API + +На веб страницах файлы запрашиваются с помощью протокола `file:`. Как и в Node API +архивы `asar` считаются за директории. + +Пример получения файла с помощью `$.get`: + +```html + +``` + + +### Использование архива `asar` в качестве обычного файла + +Для случаев, когда вам, например, нужно проверить хэш-сумму архива `asar`, +нужно использовать архив как файл. Для этой цели существует встроенный модуль +`original-fs`, который предоставляет доступ к `fs` без поддежки `asar`: + +```javascript +var originalFs = require('original-fs'); +originalFs.readFileSync('/path/to/example.asar'); +``` +Вы также можете выставить `process.noAsar` в `true`, чтобы выключить поддержку `asar` +в модуле `fs`: + +```javascript +process.noAsar = true; +fs.readFileSync('/path/to/example.asar'); +``` + +## Ограничения Node API + +Хотя мы и старались как могли, чтобы сделать `asar` максимально похожим на папки, +всё ещё существуют некоторые ограничения из-за низкоуровневой натуры Node API. + +### Архивы только для чтения + +Архивы не могут быть изменены, так что все функции API Node, которые меняют файлы, +не буду работать с архивами `asar`. + +### Нельзя установить рабочую директорию в архиве + +Хотя архивы `asar` и считаются папками, они ими на самом деле не являются, +так что вы не можете установить в них рабочую директорию. Передача +архивов `asar` в качестве аргумента `cwd` некоторым API также может вызывать ошибки. + + +### Распаковка для некоторых API + +Большинство API `fs` могут читать файлы или получить сведения о них прямо из +архива, без распаковки, однако для некоторых, которые передают путь к системным +вызовам, Electron распакует нужный файл в временную папку и передаст путь к этому +файлу. + +API которым нужна распаковка: + +* `child_process.execFile` +* `child_process.execFileSync` +* `fs.open` +* `fs.openSync` +* `process.dlopen` - используется `require` на нативных модулях + +### Подельная информация для `fs.stat` + +Объект `Stats`, возвращаемый `fs.stat`, и его друзья для остальных файлов +в архиве `asar` специально генерируются, потому что на самом деле этих файлов +не существует в файловой системе. Вам не стоит доверять информации +из объектов `Stats`, кроме, разве что, размера и типа файлов. + +### Запуск исполняемых файлов из архивов `asar` + +Существуют некоторые API Node, которые исполняют файлы, например `child_process.exec`, +`child_process.spawn` и `child_process.execFile`, но только `execFile` может +исполнять файлы из архивов `asar`. + +Так вышло потому, что `exec` и `spawn` принимают `команду` а не `файл` как параметр, +а `команды` исполняются в оболочке. Нет никакой реальной возможности проверить, +реален ли файл или находится в архиве `asar`, и даже если мы смогли бы проверить, +то неясно, как земенить путь к файлу без побочных эффектов. + +## Добавление распакованых файлов в архив `asar` + +Как говорилось выше, некоторые API Node будут распаковывать файлв, +чтобы их использовать. Кроме увеличенного потребления ресурсов это также +может вызвать предупрждения от антивирусов. + +Чтобы обойти это, вы можете распаковать некоторые файлы, создавая архивы, +с помощью опции `--unpack`. Пример показывает распаковку нативных модулей: + +```bash +$ asar pack app app.asar --unpack *.node +``` + +После запуска команды выше в вашей папке, кроме `app.asar`, появится +`app.asar.unpacked`, которая будет содержать распакованные файлы, эту +папку стоит копировать вместе с `app.asar` при распространении. + +[asar]: https://github.com/atom/asar From a83b891a95ac87c52b65fdd45927a0a118d3e160 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Mon, 2 May 2016 10:21:27 +0900 Subject: [PATCH 0673/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/system-preferences.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/ko-KR/api/system-preferences.md b/docs-translations/ko-KR/api/system-preferences.md index 8db4cc32cef..c5707ea7eaf 100644 --- a/docs-translations/ko-KR/api/system-preferences.md +++ b/docs-translations/ko-KR/api/system-preferences.md @@ -59,7 +59,7 @@ OS X에선 API가 `NSUserDefaults`를 읽어들입니다. 유명한 `key`와 `ty let browserOptions = {width: 1000, height: 800}; // 플랫폼이 지원하는 경우에만 투명 윈도우를 생성. -if (process.platform !== 'win32' || app.isAeroGlassEnabled()) { +if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true; browserOptions.frame = false; } From 26c0ad1c2fb917215d22df766ff50f4e1f7f82ca Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 16:04:50 +0900 Subject: [PATCH 0674/1265] Add --build_libchromiumcontent option --- script/bootstrap.py | 26 ++++++++++++++-- script/build-libchromiumcontent.py | 48 ++++++++++++++++++++++++++++++ vendor/brightray | 2 +- 3 files changed, 73 insertions(+), 3 deletions(-) create mode 100755 script/build-libchromiumcontent.py diff --git a/script/bootstrap.py b/script/bootstrap.py index 54f59c68f90..3d61106f266 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -33,6 +33,19 @@ def main(): if sys.platform == 'cygwin': update_win32_python() + libcc_source_path = args.libcc_source_path + libcc_shared_library_path = args.libcc_shared_library_path + libcc_static_library_path = args.libcc_static_library_path + + # Redirect to use local libchromiumcontent build. + if args.build_libchromiumcontent: + build_libchromiumcontent(args.verbose, args.target_arch) + dist_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', + 'libchromiumcontent', 'dist', 'main') + libcc_source_path = os.path.join(dist_dir, 'src') + libcc_shared_library_path = os.path.join(dist_dir, 'shared_library') + libcc_static_library_path = os.path.join(dist_dir, 'static_library') + if PLATFORM != 'win32': update_clang() @@ -40,8 +53,8 @@ def main(): setup_python_libs() update_node_modules('.') bootstrap_brightray(args.dev, args.url, args.target_arch, - args.libcc_source_path, args.libcc_shared_library_path, - args.libcc_static_library_path) + libcc_source_path, libcc_shared_library_path, + libcc_static_library_path) if PLATFORM == 'linux': download_sysroot(args.target_arch) @@ -71,6 +84,8 @@ def parse_args(): 'prompts.') parser.add_argument('--target_arch', default=get_target_arch(), help='Manually specify the arch to build for') + parser.add_argument('--build_libchromiumcontent', action='store_true', + help='Build local version of libchromiumcontent') parser.add_argument('--libcc_source_path', required=False, help='The source path of libchromiumcontent. ' \ 'NOTE: All options of libchromiumcontent are ' \ @@ -159,6 +174,13 @@ def update_win32_python(): execute_stdout(['git', 'clone', PYTHON_26_URL]) +def build_libchromiumcontent(is_verbose_mode, target_arch): + args = [os.path.join(SOURCE_ROOT, 'script', 'build-libchromiumcontent.py')] + if is_verbose_mode: + args += ['-v'] + execute_stdout(args + ['--target_arch', target_arch]) + + def update_clang(): execute_stdout([os.path.join(SOURCE_ROOT, 'script', 'update-clang.sh')]) diff --git a/script/build-libchromiumcontent.py b/script/build-libchromiumcontent.py new file mode 100755 index 00000000000..2409d0125c3 --- /dev/null +++ b/script/build-libchromiumcontent.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +import argparse +import os +import sys + +from lib.config import enable_verbose_mode, get_target_arch +from lib.util import execute_stdout + + +SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + + +def main(): + os.chdir(SOURCE_ROOT) + + args = parse_args() + if args.verbose: + enable_verbose_mode() + + # ./script/bootstrap + # ./script/update -t x64 + # ./script/build --no_shared_library -t x64 + # ./script/create-dist -c static_library -t x64 --no_zip + script_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', + 'libchromiumcontent', 'script') + bootstrap = os.path.join(script_dir, 'bootstrap') + update = os.path.join(script_dir, 'update') + build = os.path.join(script_dir, 'build') + create_dist = os.path.join(script_dir, 'create-dist') + execute_stdout([sys.executable, bootstrap]) + execute_stdout([sys.executable, update, '-t', args.target_arch]) + execute_stdout([sys.executable, build, '-R', '-t', args.target_arch]) + execute_stdout([sys.executable, create_dist, '-c', 'static_library', + '--no_zip', '-t', args.target_arch]) + + +def parse_args(): + parser = argparse.ArgumentParser(description='Build libchromiumcontent') + parser.add_argument('--target_arch', + help='Specify the arch to build for') + parser.add_argument('-v', '--verbose', action='store_true', + help='Prints the output of the subprocesses') + return parser.parse_args() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/vendor/brightray b/vendor/brightray index 8dbaeed37b9..3d168efd1d2 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 8dbaeed37b9c4fb8ae985670b142f659bb265fb4 +Subproject commit 3d168efd1d27d4ac3869beac6290c5066c392721 From 64abae0b3c43e150f2007fe864ff0c8fbe9a6086 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 16:26:18 +0900 Subject: [PATCH 0675/1265] docs: Cleanup unnecessary parts in build-instructions-linux.md --- docs/development/build-instructions-linux.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 79fbc501489..49a78ba3ccb 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -4,6 +4,7 @@ Follow the guidelines below for building Electron on Linux. ## Prerequisites +* At least 25GB disk space and 8GB RAM. * Python 2.7.x. Some distributions like CentOS still use Python 2.6.x so you may need to check your Python version with `python -V`. * Node.js v0.12.x. There are various ways to install Node. You can download @@ -33,11 +34,6 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring- Other distributions may offer similar packages for installation via package managers such as pacman. Or one can compile from source code. -## If You Use Virtual Machines For Building - -If you plan to build Electron on a virtual machine you will need a fixed-size -device container of at least 25 gigabytes in size. - ## Getting the Code ```bash @@ -112,8 +108,6 @@ $ ./script/clean.py ## Troubleshooting -Make sure you have installed all of the build dependencies. - ### Error While Loading Shared Libraries: libtinfo.so.5 Prebulit `clang` will try to link to `libtinfo.so.5`. Depending on the host @@ -128,7 +122,7 @@ $ sudo ln -s /usr/lib/libncurses.so.5 /usr/lib/libtinfo.so.5 Test your changes conform to the project coding style using: ```bash -$ ./script/cpplint.py +$ npm run lint ``` Test functionality using: From 459a65d296aff06a9a6183ed4499a70f8f669cd4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 16:35:33 +0900 Subject: [PATCH 0676/1265] docs: the --build_libchromiumcontent switch --- docs/development/build-instructions-linux.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 49a78ba3ccb..870f4fca61f 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -130,3 +130,25 @@ Test functionality using: ```bash $ ./script/test.py ``` + +## Advanced topics + +The default building configuration is targeted for major desktop Linux +distributions, to build for a specific distribution or device, following +information may help you. + +### Build libchromiumcontent locally + +To avoid using the prebuilt binaries of libchromiumcontent, you can pass the +`--build_libchromiumcontent` switch to `bootstrap.py` script: + +```bash +$ ./script/bootstrap.py -v --build_libchromiumcontent +``` + +Note that by default the `shared_library` configuration is not built, so you can +only build `Release` version of Electron if you use this mode: + +```bash +$ ./script/build.py -c D +``` From cc24bea813305dc8a13e58aa4ff437550c4f4b84 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 16:38:58 +0900 Subject: [PATCH 0677/1265] Fix pylint warnings --- script/bootstrap.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index 3d61106f266..1138ead01e4 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -174,9 +174,9 @@ def update_win32_python(): execute_stdout(['git', 'clone', PYTHON_26_URL]) -def build_libchromiumcontent(is_verbose_mode, target_arch): +def build_libchromiumcontent(verbose, target_arch): args = [os.path.join(SOURCE_ROOT, 'script', 'build-libchromiumcontent.py')] - if is_verbose_mode: + if verbose: args += ['-v'] execute_stdout(args + ['--target_arch', target_arch]) From ad09196433c049a42825d1a918abeb258cf23878 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Mon, 2 May 2016 14:39:46 +0700 Subject: [PATCH 0678/1265] improve the `webContents.openDevTools` docs consistent value notation and explain the difference between `undocked` and `detach` mode. --- docs/api/web-contents.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 64e7cea60e7..4576e77ddf9 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -655,8 +655,9 @@ Removes the specified path from DevTools workspace. ### `webContents.openDevTools([options])` * `options` Object (optional) - * `mode` String - Opens the devtools with specified dock state, can be one of - "right", "bottom", "undocked", "detach". Defaults to last used dock state. + * `mode` String - Opens the devtools with specified dock state, can be + `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. + In `undocked` mode it's possible to dock back. In `detach` mode it's not. Opens the devtools. From bd70d9008f8f2b32084b057188a5d21567701e47 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 07:45:48 +0000 Subject: [PATCH 0679/1265] Update modules before calling build_libchromiumcontent --- script/bootstrap.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index 1138ead01e4..2aba23ba82f 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -33,6 +33,8 @@ def main(): if sys.platform == 'cygwin': update_win32_python() + update_submodules() + libcc_source_path = args.libcc_source_path libcc_shared_library_path = args.libcc_shared_library_path libcc_static_library_path = args.libcc_static_library_path @@ -49,7 +51,6 @@ def main(): if PLATFORM != 'win32': update_clang() - update_submodules() setup_python_libs() update_node_modules('.') bootstrap_brightray(args.dev, args.url, args.target_arch, From 26e4ce30bbcc05290f4ffbd320823414408f9d7a Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 20:06:21 +0900 Subject: [PATCH 0680/1265] Pass --disable_clang and --clang_dir to libchromiumcontent --- script/bootstrap.py | 14 +++++++++++--- script/build-libchromiumcontent.py | 12 +++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index 2aba23ba82f..cbc3b9921a4 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -41,14 +41,15 @@ def main(): # Redirect to use local libchromiumcontent build. if args.build_libchromiumcontent: - build_libchromiumcontent(args.verbose, args.target_arch) + build_libchromiumcontent(args.verbose, args.target_arch, args.disable_clang, + args.clang_dir) dist_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', 'libchromiumcontent', 'dist', 'main') libcc_source_path = os.path.join(dist_dir, 'src') libcc_shared_library_path = os.path.join(dist_dir, 'shared_library') libcc_static_library_path = os.path.join(dist_dir, 'static_library') - if PLATFORM != 'win32': + if PLATFORM != 'win32' and not args.disable_clang and args.clang_dir != '': update_clang() setup_python_libs() @@ -85,6 +86,9 @@ def parse_args(): 'prompts.') parser.add_argument('--target_arch', default=get_target_arch(), help='Manually specify the arch to build for') + parser.add_argument('--clang_dir', default='', help='Path to clang binaries') + parser.add_argument('--disable_clang', action='store_true', + help='Use compilers other than clang for building') parser.add_argument('--build_libchromiumcontent', action='store_true', help='Build local version of libchromiumcontent') parser.add_argument('--libcc_source_path', required=False, @@ -175,10 +179,14 @@ def update_win32_python(): execute_stdout(['git', 'clone', PYTHON_26_URL]) -def build_libchromiumcontent(verbose, target_arch): +def build_libchromiumcontent(verbose, target_arch, disable_clang, clang_dir): args = [os.path.join(SOURCE_ROOT, 'script', 'build-libchromiumcontent.py')] if verbose: args += ['-v'] + if disable_clang: + args += ['--disable_clang'] + if clang_dir: + args += ['--clang_dir', clang_dir] execute_stdout(args + ['--target_arch', target_arch]) diff --git a/script/build-libchromiumcontent.py b/script/build-libchromiumcontent.py index 2409d0125c3..a6662e8295e 100755 --- a/script/build-libchromiumcontent.py +++ b/script/build-libchromiumcontent.py @@ -18,6 +18,12 @@ def main(): if args.verbose: enable_verbose_mode() + extra_update_args = [] + if args.disable_clang: + extra_update_args += ['--disable_clang'] + if args.clang_dir: + extra_update_args += ['--clang_dir', args.clang_dir] + # ./script/bootstrap # ./script/update -t x64 # ./script/build --no_shared_library -t x64 @@ -29,7 +35,8 @@ def main(): build = os.path.join(script_dir, 'build') create_dist = os.path.join(script_dir, 'create-dist') execute_stdout([sys.executable, bootstrap]) - execute_stdout([sys.executable, update, '-t', args.target_arch]) + execute_stdout([sys.executable, update, '-t', args.target_arch] + + extra_update_args) execute_stdout([sys.executable, build, '-R', '-t', args.target_arch]) execute_stdout([sys.executable, create_dist, '-c', 'static_library', '--no_zip', '-t', args.target_arch]) @@ -39,6 +46,9 @@ def parse_args(): parser = argparse.ArgumentParser(description='Build libchromiumcontent') parser.add_argument('--target_arch', help='Specify the arch to build for') + parser.add_argument('--clang_dir', default='', help='Path to clang binaries') + parser.add_argument('--disable_clang', action='store_true', + help='Use compilers other than clang for building') parser.add_argument('-v', '--verbose', action='store_true', help='Prints the output of the subprocesses') return parser.parse_args() From 098d72b741fc8d974e1f83d5b78d9d86af13a7b2 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 21:19:16 +0900 Subject: [PATCH 0681/1265] Convert --clang_dir and --disable_clang to --defines --- script/bootstrap.py | 25 +++++++++++++++++-------- script/build-libchromiumcontent.py | 17 +++++------------ script/update.py | 16 ++++++++++++++++ vendor/brightray | 2 +- 4 files changed, 39 insertions(+), 21 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index cbc3b9921a4..6be186319b3 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -26,6 +26,7 @@ def main(): os.chdir(SOURCE_ROOT) args = parse_args() + defines = args_to_defines(args) if not args.yes and PLATFORM != 'win32': check_root() if args.verbose: @@ -63,7 +64,7 @@ def main(): create_chrome_version_h() touch_config_gypi() - run_update() + run_update(defines) update_electron_modules('spec', args.target_arch) @@ -102,6 +103,16 @@ def parse_args(): return parser.parse_args() +def args_to_defines(args): + defines = '' + if args.disable_clang: + defines += ' clang=0' + if args.clang_dir: + defines += ' make_clang_dir=' + args.clang_dir + defines += ' clang_use_chrome_plugins=0' + return defines + + def check_root(): if os.geteuid() == 0: print "We suggest not running this as root, unless you're really sure." @@ -179,14 +190,12 @@ def update_win32_python(): execute_stdout(['git', 'clone', PYTHON_26_URL]) -def build_libchromiumcontent(verbose, target_arch, disable_clang, clang_dir): +def build_libchromiumcontent(verbose, target_arch, defines): args = [os.path.join(SOURCE_ROOT, 'script', 'build-libchromiumcontent.py')] if verbose: args += ['-v'] - if disable_clang: - args += ['--disable_clang'] - if clang_dir: - args += ['--clang_dir', clang_dir] + if defines: + args += ['--defines', defines] execute_stdout(args + ['--target_arch', target_arch]) @@ -234,9 +243,9 @@ def touch_config_gypi(): f.write(content) -def run_update(): +def run_update(defines): update = os.path.join(SOURCE_ROOT, 'script', 'update.py') - execute_stdout([sys.executable, update]) + execute_stdout([sys.executable, update, '--defines', defines]) if __name__ == '__main__': diff --git a/script/build-libchromiumcontent.py b/script/build-libchromiumcontent.py index a6662e8295e..e0a95f69a46 100755 --- a/script/build-libchromiumcontent.py +++ b/script/build-libchromiumcontent.py @@ -18,14 +18,8 @@ def main(): if args.verbose: enable_verbose_mode() - extra_update_args = [] - if args.disable_clang: - extra_update_args += ['--disable_clang'] - if args.clang_dir: - extra_update_args += ['--clang_dir', args.clang_dir] - # ./script/bootstrap - # ./script/update -t x64 + # ./script/update -t x64 --defines='' # ./script/build --no_shared_library -t x64 # ./script/create-dist -c static_library -t x64 --no_zip script_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', @@ -35,8 +29,8 @@ def main(): build = os.path.join(script_dir, 'build') create_dist = os.path.join(script_dir, 'create-dist') execute_stdout([sys.executable, bootstrap]) - execute_stdout([sys.executable, update, '-t', args.target_arch] + - extra_update_args) + execute_stdout([sys.executable, update, '-t', args.target_arch, + '--defines', args.defines]) execute_stdout([sys.executable, build, '-R', '-t', args.target_arch]) execute_stdout([sys.executable, create_dist, '-c', 'static_library', '--no_zip', '-t', args.target_arch]) @@ -46,9 +40,8 @@ def parse_args(): parser = argparse.ArgumentParser(description='Build libchromiumcontent') parser.add_argument('--target_arch', help='Specify the arch to build for') - parser.add_argument('--clang_dir', default='', help='Path to clang binaries') - parser.add_argument('--disable_clang', action='store_true', - help='Use compilers other than clang for building') + parser.add_argument('--defines', default='', + help='The definetions passed to gyp') parser.add_argument('-v', '--verbose', action='store_true', help='Prints the output of the subprocesses') return parser.parse_args() diff --git a/script/update.py b/script/update.py index 33a4cff50f6..f820248d0aa 100755 --- a/script/update.py +++ b/script/update.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import argparse import os import platform import subprocess @@ -23,6 +24,13 @@ def main(): return update_gyp() +def parse_args(): + parser = argparse.ArgumentParser(description='Update build configurations') + parser.add_argument('--defines', default='', + help='The definetions passed to gyp') + return parser.parse_args() + + def update_external_binaries(): uf = os.path.join('script', 'update-external-binaries.py') subprocess.check_call([sys.executable, uf]) @@ -60,6 +68,7 @@ def run_gyp(target_arch, component): mas_build = 1 else: mas_build = 0 + defines = [ '-Dlibchromiumcontent_component={0}'.format(component), '-Dtarget_arch={0}'.format(target_arch), @@ -67,6 +76,13 @@ def run_gyp(target_arch, component): '-Dlibrary=static_library', '-Dmas_build={0}'.format(mas_build), ] + + # Add the defines passed from command line. + args = parse_args() + for define in [d.strip() for d in args.defines.split(' ')]: + if define: + defines += ['-D' + define] + return subprocess.call([python, gyp, '-f', 'ninja', '--depth', '.', 'electron.gyp', '-Icommon.gypi'] + defines, env=env) diff --git a/vendor/brightray b/vendor/brightray index 3d168efd1d2..9a5b443e495 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit 3d168efd1d27d4ac3869beac6290c5066c392721 +Subproject commit 9a5b443e4953fa51ddd0a8d4739e60edf0a666a3 From 34b4ebd9f3e9b253cdc28043ce3382022b9fb2c6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 12:15:10 +0000 Subject: [PATCH 0682/1265] Fix logic errors --- script/bootstrap.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index 6be186319b3..4ad30f4cb13 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -42,15 +42,14 @@ def main(): # Redirect to use local libchromiumcontent build. if args.build_libchromiumcontent: - build_libchromiumcontent(args.verbose, args.target_arch, args.disable_clang, - args.clang_dir) + build_libchromiumcontent(args.verbose, args.target_arch, defines) dist_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', 'libchromiumcontent', 'dist', 'main') libcc_source_path = os.path.join(dist_dir, 'src') libcc_shared_library_path = os.path.join(dist_dir, 'shared_library') libcc_static_library_path = os.path.join(dist_dir, 'static_library') - if PLATFORM != 'win32' and not args.disable_clang and args.clang_dir != '': + if PLATFORM != 'win32' and not args.disable_clang and args.clang_dir == '': update_clang() setup_python_libs() From ac3a704abcb214df2e1178a3e3be1c0a0cf0013e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 12:38:17 +0000 Subject: [PATCH 0683/1265] Avoid overriding environment variables --- script/bootstrap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index 4ad30f4cb13..ab72b6a7dc5 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -153,7 +153,7 @@ def bootstrap_brightray(is_dev, url, target_arch, libcc_source_path, def update_node_modules(dirname, env=None): if env is None: - env = os.environ + env = os.environ.copy() if PLATFORM == 'linux': # Use prebuilt clang for building native modules. llvm_dir = os.path.join(SOURCE_ROOT, 'vendor', 'llvm-build', From e39d5a9eb9729789a00125da569666c89bde6d76 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 2 May 2016 22:32:43 +0900 Subject: [PATCH 0684/1265] docs: Introduce clang flags --- docs/development/build-instructions-linux.md | 33 ++++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 870f4fca61f..78d3b1a102a 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -137,9 +137,9 @@ The default building configuration is targeted for major desktop Linux distributions, to build for a specific distribution or device, following information may help you. -### Build libchromiumcontent locally +### Building `libchromiumcontent` locally -To avoid using the prebuilt binaries of libchromiumcontent, you can pass the +To avoid using the prebuilt binaries of `libchromiumcontent`, you can pass the `--build_libchromiumcontent` switch to `bootstrap.py` script: ```bash @@ -150,5 +150,32 @@ Note that by default the `shared_library` configuration is not built, so you can only build `Release` version of Electron if you use this mode: ```bash -$ ./script/build.py -c D +$ ./script/build.py -c R +``` + +### Using system `clang` instead of downloaded `clang` binaries + +By default Electron is built with prebuilt `clang` binaries provided by Chromium +project. If for some reason you want to build with the `clang` installed in your +system, you can call `bootstrap.py` with `--clang_dir=` switch. By passing +it the build script will assume the clang binaries reside in `/bin/`. + +For example if you installed `clang` under `/user/local/bin/clang`: + +```bash +$ ./script/bootstrap.py -v --build_libchromiumcontent --clang_dir /usr/local +$ ./script/build.py -c R +``` + +### Using other compilers other than `clang` + +To build Electron with compilers like `g++`, you first need to disable `clang` +with `--disable_clang` switch first, and then set `CC` and `CXX` environment +variables to the ones you want. + +For example building with GCC toolchain: + +```bash +$ env CC=gcc CXX=g++ ./script/bootstrap.py -v --build_libchromiumcontent --disable_clang +$ ./script/build.py -c R ``` From fecd9ee4a0d500c416c414199c59de1da13fbc1e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Mon, 2 May 2016 08:59:25 -0700 Subject: [PATCH 0685/1265] Update link to AppVeyor build badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f8278f18586..5e891e5dd64 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) [![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron) -[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/kvxe4byi7jcxbe26/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) [![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron#info=devDependencies) [![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/) From be32039cf9091dc43b5917517f12ec168431f0f3 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 3 May 2016 02:43:21 +0900 Subject: [PATCH 0686/1265] :memo: Update Korean docs as upstream [ci skip] --- .../ko-KR/development/build-instructions-linux.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs-translations/ko-KR/development/build-instructions-linux.md b/docs-translations/ko-KR/development/build-instructions-linux.md index e5712fcac99..5a0dc2e5f3f 100644 --- a/docs-translations/ko-KR/development/build-instructions-linux.md +++ b/docs-translations/ko-KR/development/build-instructions-linux.md @@ -4,6 +4,7 @@ ## 빌드전 요구사양 +* 최소한 25GB 이상의 디스크 공간과 8GB 램이 필요합니다. * Python 2.7.x. 몇몇 CentOS와 같은 배포판들은 아직도 Python 2.6.x 버전을 사용합니다. 그래서 먼저 `python -V`를 통해 버전을 확인할 필요가 있습니다. * Node.js v0.12.x. Node를 설치하는 방법은 여러 가지가 있습니다. 먼저, @@ -36,11 +37,6 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring- 패키지의 이름은 대부분 위 예시와 비슷할 것입니다. 또는 소스코드를 내려받아 직접 빌드하는 방법도 있습니다. -## 가상머신을 사용하여 빌드 하는 경우 - -만약 Electron을 가상머신으로 빌드 할 계획이라면 해당 가상머신의 스토리지를 최소 25GB -이상 확보해 놓아야 합니다. - ## 코드 가져오기 ```bash @@ -114,8 +110,6 @@ $ ./script/clean.py ## 문제 해결 -개발 종속성 라이브러리들을 제대로 설치했는지 확인하세요. - ## libtinfo.so.5 동적 링크 라이브러리를 로드하는 도중 에러가 발생할 경우 미리 빌드된 `clang`은 `libtinfo.so.5`로 링크를 시도합니다. 따라서 플랫폼에 따라 @@ -130,7 +124,7 @@ $ sudo ln -s /usr/lib/libncurses.so.5 /usr/lib/libtinfo.so.5 프로젝트 코딩 스타일을 확인하려면: ```bash -$ ./script/cpplint.py +$ npm run lint ``` 테스트를 실행하려면: From 2295f3a8327d6df4031dcfcd8daebb771d0e3530 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Mon, 2 May 2016 14:45:59 -0700 Subject: [PATCH 0687/1265] Add some shady methods to get V8 objects or arrays from NSDictionary or NSArray. --- atom/browser/mac/atom_application_delegate.mm | 4 +- atom/browser/mac/mac_native_converter.h | 11 +++++ atom/browser/mac/mac_native_converter.mm | 46 +++++++++++++++++++ filenames.gypi | 2 + 4 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 atom/browser/mac/mac_native_converter.h create mode 100644 atom/browser/mac/mac_native_converter.mm diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index 33aa47ce240..f08cc84c466 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -63,9 +63,9 @@ continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); - + std::map user_info; - + NSArray* keys = [userActivity.userInfo allKeys]; for (NSString* key in keys) { diff --git a/atom/browser/mac/mac_native_converter.h b/atom/browser/mac/mac_native_converter.h new file mode 100644 index 00000000000..ac1a9a608d7 --- /dev/null +++ b/atom/browser/mac/mac_native_converter.h @@ -0,0 +1,11 @@ +#import + +#include "base/values.h" +#include "base/strings/sys_string_conversions.h" + +@interface MacNativeConverter : NSObject + +- (base::ListValue*)arrayToV8:(NSArray*)nsArray; +- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary; + +@end diff --git a/atom/browser/mac/mac_native_converter.mm b/atom/browser/mac/mac_native_converter.mm new file mode 100644 index 00000000000..63244036017 --- /dev/null +++ b/atom/browser/mac/mac_native_converter.mm @@ -0,0 +1,46 @@ +#import "atom/browser/mac/mac_native_converter.h" + +@implementation MacNativeConverter + +- (base::ListValue*)arrayToV8:(NSArray*)nsArray { + scoped_ptr list(new base::ListValue); + + for (id value in nsArray) { + if ([value isKindOfClass:[NSArray class]]) { + list->Append([self arrayToV8:value]); + } else if ([value isKindOfClass:[NSDictionary class]]) { + list->Append([self dictionaryToV8:value]); + } else if ([value isKindOfClass:[NSString class]]) { + list->AppendString(base::SysNSStringToUTF8(value)); + } else if ([value isKindOfClass:[NSNumber class]]) { + list->AppendInteger(((NSNumber* )value).intValue); + } + } + + return list.get(); +} + +- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary { + scoped_ptr dict(new base::DictionaryValue); + + NSEnumerator *it = [nsDictionary keyEnumerator]; + while (NSString *key = [it nextObject]) { + id value = [nsDictionary objectForKey:key]; + + std::string key_str(base::SysNSStringToUTF8(key)); + + if ([value isKindOfClass:[NSArray class]]) { + dict->Set(key_str, [self arrayToV8:value]); + } else if ([value isKindOfClass:[NSDictionary class]]) { + dict->Set(key_str, [self dictionaryToV8:value]); + } else if ([value isKindOfClass:[NSString class]]) { + dict->SetString(key_str, base::SysNSStringToUTF8(value)); + } else if ([value isKindOfClass:[NSNumber class]]) { + dict->SetInteger(key_str, ((NSNumber* )value).intValue); + } + } + + return dict.get(); +} + +@end diff --git a/filenames.gypi b/filenames.gypi index 783b5cb33d0..033d4959454 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -183,6 +183,8 @@ 'atom/browser/mac/atom_application.mm', 'atom/browser/mac/atom_application_delegate.h', 'atom/browser/mac/atom_application_delegate.mm', + 'atom/browser/mac/mac_native_converter.h', + 'atom/browser/mac/mac_native_converter.mm', 'atom/browser/native_window.cc', 'atom/browser/native_window.h', 'atom/browser/native_window_views_win.cc', From 90cc10944a64d9a4998a3d12a2559baa7705b3af Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Mon, 2 May 2016 16:18:58 -0700 Subject: [PATCH 0688/1265] Use a DictionaryValue everywhere instead of a string map. --- atom/browser/api/atom_api_app.cc | 2 +- atom/browser/api/atom_api_app.h | 2 +- atom/browser/browser.cc | 3 +-- atom/browser/browser.h | 5 +++-- atom/browser/browser_mac.mm | 15 ++++---------- atom/browser/browser_observer.h | 4 +++- atom/browser/mac/atom_application_delegate.mm | 17 +++++----------- atom/browser/mac/mac_native_converter.h | 7 +++++-- atom/browser/mac/mac_native_converter.mm | 20 +++++++++++++------ 9 files changed, 37 insertions(+), 38 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index ec6cdce417c..ee73e5b2151 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -252,7 +252,7 @@ void App::OnFinishLaunching() { void App::OnContinueUserActivity(bool* prevent_default, const std::string& type, - const std::map& user_info) { + const base::DictionaryValue& user_info) { *prevent_default = Emit("continue-activity", type, user_info); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 321230d711e..db510640fa6 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -74,7 +74,7 @@ class App : public AtomBrowserClient::Delegate, void OnLogin(LoginHandler* login_handler) override; void OnContinueUserActivity(bool* prevent_default, const std::string& type, - const std::map& user_info) override; + const base::DictionaryValue& user_info) override; // content::ContentBrowserClient: void AllowCertificateError( diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index ee2a225246b..62e0467e5d2 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -139,8 +139,7 @@ void Browser::Activate(bool has_visible_windows) { #if defined(OS_MACOSX) bool Browser::ContinueUserActivity(const std::string& type, - const std::map& user_info) { + const base::DictionaryValue& user_info) { bool prevent_default = false; FOR_EACH_OBSERVER(BrowserObserver, observers_, diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 14f94a061e4..4e282ed409a 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -10,6 +10,7 @@ #include #include "base/macros.h" +#include "base/values.h" #include "base/compiler_specific.h" #include "base/observer_list.h" #include "base/strings/string16.h" @@ -95,11 +96,11 @@ class Browser : public WindowListObserver { // Creates an activity and sets it as the one currently in use. void SetUserActivity(const std::string& type, - const std::map& user_info); + const base::DictionaryValue& user_info); // Resumes an activity via hand-off. bool ContinueUserActivity(const std::string& type, - const std::map& user_info); + const base::DictionaryValue& user_info); // Bounce the dock icon. enum BounceType { diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index a12bd8c8809..594624f511c 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -6,6 +6,7 @@ #include "atom/browser/mac/atom_application.h" #include "atom/browser/mac/atom_application_delegate.h" +#include "atom/browser/mac/mac_native_converter.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "base/mac/bundle_locations.h" @@ -87,20 +88,12 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { void Browser::SetAppUserModelID(const base::string16& name) { } -void Browser::SetUserActivity(const std::string& type, const std::map& user_info) { +void Browser::SetUserActivity(const std::string& type, const base::DictionaryValue& user_info) { NSString* type_ns = [NSString stringWithUTF8String:type.c_str()]; NSUserActivity *user_activity = [[NSUserActivity alloc] initWithActivityType:type_ns]; + MacNativeConverter* converter = [[MacNativeConverter alloc] init]; - NSMutableArray* user_info_args = [[NSMutableArray alloc] init]; - for (auto const &pair : user_info) { - NSString* value_ns = [NSString stringWithUTF8String:pair.second.c_str()]; - NSString* key_ns = [NSString stringWithUTF8String:pair.first.c_str()]; - - [user_info_args addObject:value_ns]; - [user_info_args addObject:key_ns]; - } - - user_activity.userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:user_info_args, nil]; + user_activity.userInfo = [converter dictionaryFromDictionaryValue:user_info]; [user_activity becomeCurrent]; } diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index 4ad001370c0..e297e16d80d 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -8,6 +8,8 @@ #include #include +#include "base/values.h" + namespace atom { class LoginHandler; @@ -49,7 +51,7 @@ class BrowserObserver { // The browser wants to resume a user activity via handoff. (OS X only) virtual void OnContinueUserActivity(bool* prevent_default, const std::string& type, - const std::map& user_info) {} + const base::DictionaryValue& user_info) {} protected: virtual ~BrowserObserver() {} diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index f08cc84c466..ffb0b988aa2 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -3,8 +3,9 @@ // found in the LICENSE file. #import "atom/browser/mac/atom_application_delegate.h" - #import "atom/browser/mac/atom_application.h" +#import "atom/browser/mac/mac_native_converter.h" + #include "atom/browser/browser.h" #include "base/strings/sys_string_conversions.h" @@ -64,19 +65,11 @@ continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); - std::map user_info; - - NSArray* keys = [userActivity.userInfo allKeys]; - for (NSString* key in keys) - { - NSString* value = [userActivity.userInfo objectForKey:key]; - std::string key_str(base::SysNSStringToUTF8(key)); - std::string value_str(base::SysNSStringToUTF8(value)); - user_info[key_str] = value_str; - } + MacNativeConverter* converter = [[MacNativeConverter alloc] init]; + const base::DictionaryValue* user_info = [converter dictionaryToDictionaryValue:userActivity.userInfo]; atom::Browser* browser = atom::Browser::Get(); - return browser->ContinueUserActivity(activity_type, user_info) ? YES : NO; + return browser->ContinueUserActivity(activity_type, *user_info) ? YES : NO; } @end diff --git a/atom/browser/mac/mac_native_converter.h b/atom/browser/mac/mac_native_converter.h index ac1a9a608d7..fcd1997fd1e 100644 --- a/atom/browser/mac/mac_native_converter.h +++ b/atom/browser/mac/mac_native_converter.h @@ -5,7 +5,10 @@ @interface MacNativeConverter : NSObject -- (base::ListValue*)arrayToV8:(NSArray*)nsArray; -- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary; +- (base::ListValue*)arrayToListValue:(NSArray*)nsArray; +- (base::DictionaryValue*)dictionaryToDictionaryValue:(NSDictionary*)nsDictionary; + +- (NSArray*)arrayFromListValue:(const base::ListValue&)list; +- (NSDictionary*)dictionaryFromDictionaryValue:(const base::DictionaryValue&)dict; @end diff --git a/atom/browser/mac/mac_native_converter.mm b/atom/browser/mac/mac_native_converter.mm index 63244036017..202f3e0ee4a 100644 --- a/atom/browser/mac/mac_native_converter.mm +++ b/atom/browser/mac/mac_native_converter.mm @@ -2,14 +2,14 @@ @implementation MacNativeConverter -- (base::ListValue*)arrayToV8:(NSArray*)nsArray { +- (base::ListValue*)arrayToListValue:(NSArray*)nsArray { scoped_ptr list(new base::ListValue); for (id value in nsArray) { if ([value isKindOfClass:[NSArray class]]) { - list->Append([self arrayToV8:value]); + list->Append([self arrayToListValue:value]); } else if ([value isKindOfClass:[NSDictionary class]]) { - list->Append([self dictionaryToV8:value]); + list->Append([self dictionaryToDictionaryValue:value]); } else if ([value isKindOfClass:[NSString class]]) { list->AppendString(base::SysNSStringToUTF8(value)); } else if ([value isKindOfClass:[NSNumber class]]) { @@ -20,7 +20,7 @@ return list.get(); } -- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary { +- (base::DictionaryValue*)dictionaryToDictionaryValue:(NSDictionary*)nsDictionary { scoped_ptr dict(new base::DictionaryValue); NSEnumerator *it = [nsDictionary keyEnumerator]; @@ -30,9 +30,9 @@ std::string key_str(base::SysNSStringToUTF8(key)); if ([value isKindOfClass:[NSArray class]]) { - dict->Set(key_str, [self arrayToV8:value]); + dict->Set(key_str, [self arrayToListValue:value]); } else if ([value isKindOfClass:[NSDictionary class]]) { - dict->Set(key_str, [self dictionaryToV8:value]); + dict->Set(key_str, [self dictionaryToDictionaryValue:value]); } else if ([value isKindOfClass:[NSString class]]) { dict->SetString(key_str, base::SysNSStringToUTF8(value)); } else if ([value isKindOfClass:[NSNumber class]]) { @@ -43,4 +43,12 @@ return dict.get(); } +- (NSArray*)arrayFromListValue:(const base::ListValue&)list { + return [[NSArray alloc] init]; +} + +- (NSDictionary*)dictionaryFromDictionaryValue:(const base::DictionaryValue&)dict { + return [[NSDictionary alloc] init]; +} + @end From 0567f09d6daf2657e0e725cf1df85496ad163df4 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 3 May 2016 08:29:23 +0900 Subject: [PATCH 0689/1265] docs: The building environment variables --- docs/development/build-instructions-linux.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 78d3b1a102a..97779f376c8 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -179,3 +179,25 @@ For example building with GCC toolchain: $ env CC=gcc CXX=g++ ./script/bootstrap.py -v --build_libchromiumcontent --disable_clang $ ./script/build.py -c R ``` + +### Environment variables + +Apart from `CC` and `CXX`, you can also set following environment variables to +custom the building configurations: + +* `CPPFLAGS` +* `CPPFLAGS_host` +* `CFLAGS` +* `CFLAGS_host` +* `CXXFLAGS` +* `CXXFLAGS_host` +* `AR` +* `AR_host` +* `CC` +* `CC_host` +* `CXX` +* `CXX_host` +* `LDFLAGS` + +The environment variables have to be set when executing the `bootstrap.py` +script, it won't work in the `build.py` script. From 49eed1ebb94bc237cf2dae00bc95c2f4630976e6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 3 May 2016 09:31:39 +0900 Subject: [PATCH 0690/1265] Ignore CC and CXX if user didn't change build configuration --- script/bootstrap.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index ab72b6a7dc5..a88527f0192 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -49,8 +49,11 @@ def main(): libcc_shared_library_path = os.path.join(dist_dir, 'shared_library') libcc_static_library_path = os.path.join(dist_dir, 'static_library') + update_clang() + if PLATFORM != 'win32' and not args.disable_clang and args.clang_dir == '': - update_clang() + # Build with prebuilt clang. + set_clang_env(os.environ) setup_python_libs() update_node_modules('.') @@ -151,15 +154,19 @@ def bootstrap_brightray(is_dev, url, target_arch, libcc_source_path, execute_stdout([sys.executable, bootstrap] + args) +def set_clang_env(env): + llvm_dir = os.path.join(SOURCE_ROOT, 'vendor', 'llvm-build', + 'Release+Asserts', 'bin') + env['CC'] = os.path.join(llvm_dir, 'clang') + env['CXX'] = os.path.join(llvm_dir, 'clang++') + + def update_node_modules(dirname, env=None): if env is None: env = os.environ.copy() if PLATFORM == 'linux': # Use prebuilt clang for building native modules. - llvm_dir = os.path.join(SOURCE_ROOT, 'vendor', 'llvm-build', - 'Release+Asserts', 'bin') - env['CC'] = os.path.join(llvm_dir, 'clang') - env['CXX'] = os.path.join(llvm_dir, 'clang++') + set_clang_env(env) env['npm_config_clang'] = '1' with scoped_cwd(dirname): args = [NPM, 'install'] From 67a768fc77a03ca40b7445640c377f331708a68c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 3 May 2016 09:38:15 +0900 Subject: [PATCH 0691/1265] Do not download clang on Windows --- script/bootstrap.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/script/bootstrap.py b/script/bootstrap.py index a88527f0192..816a6182b20 100755 --- a/script/bootstrap.py +++ b/script/bootstrap.py @@ -49,11 +49,12 @@ def main(): libcc_shared_library_path = os.path.join(dist_dir, 'shared_library') libcc_static_library_path = os.path.join(dist_dir, 'static_library') - update_clang() - - if PLATFORM != 'win32' and not args.disable_clang and args.clang_dir == '': - # Build with prebuilt clang. - set_clang_env(os.environ) + if PLATFORM != 'win32': + # Download prebuilt clang binaries. + update_clang() + if not args.disable_clang and args.clang_dir == '': + # Build with prebuilt clang. + set_clang_env(os.environ) setup_python_libs() update_node_modules('.') From f984536523b4a80f42ffb326603e5b3ca2f3b8bf Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 3 May 2016 12:07:06 +0900 Subject: [PATCH 0692/1265] :memo: Improve grammar [ci skip] --- README-ko.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README-ko.md b/README-ko.md index 4da9eb3f3f2..8239ad250aa 100644 --- a/README-ko.md +++ b/README-ko.md @@ -78,5 +78,4 @@ npm install electron-prebuilt --save-dev - [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(일본)* 커뮤니티 [awesome-electron](https://github.com/sindresorhus/awesome-electron) 프로젝트에 -커뮤니티가 운영중인 유용한 예제 어플리케이션과 도구, 리소스가 있으니 한번 참고해 보시기 -바랍니다. +커뮤니티가 운영중인 유용한 예제 어플리케이션과 도구, 리소스가 있으니 참고하기 바랍니다. From 0e7de568a2578707bce69d81f187709cfb0b79d0 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 3 May 2016 15:34:47 +0900 Subject: [PATCH 0693/1265] :memo: Small fixes [ci skip] --- README-ko.md | 2 +- docs-translations/ko-KR/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README-ko.md b/README-ko.md index 8239ad250aa..5f809bbf05f 100644 --- a/README-ko.md +++ b/README-ko.md @@ -78,4 +78,4 @@ npm install electron-prebuilt --save-dev - [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(일본)* 커뮤니티 [awesome-electron](https://github.com/sindresorhus/awesome-electron) 프로젝트에 -커뮤니티가 운영중인 유용한 예제 어플리케이션과 도구, 리소스가 있으니 참고하기 바랍니다. +커뮤니티가 운영중인 유용한 예시 어플리케이션과 도구, 리소스가 있으니 참고하기 바랍니다. diff --git a/docs-translations/ko-KR/README.md b/docs-translations/ko-KR/README.md index c0949a83966..0e6c0fda8c8 100644 --- a/docs-translations/ko-KR/README.md +++ b/docs-translations/ko-KR/README.md @@ -45,7 +45,7 @@ Electron에 대해 자주 묻는 질문이 있습니다. 이슈를 생성하기 * [크롬 명령줄 스위치 지원](api/chrome-command-line-switches.md) * [환경 변수](api/environment-variables.md) -### 커스텀 DOM elements: +### 커스텀 DOM 요소: * [`File` 객체](api/file-object.md) * [`` 태그](api/web-view-tag.md) From b15c07e1a837b6d40c117dacb42d838aeaa8a85c Mon Sep 17 00:00:00 2001 From: Ryan Patterson Date: Mon, 2 May 2016 23:54:21 -0700 Subject: [PATCH 0694/1265] Use select to query the uv kqueue This resolves #38. I've verified that events still get processed like they should on El Capitan 10.11.3 (15D21). --- atom/common/node_bindings_mac.cc | 24 +++++++++++------------- atom/common/node_bindings_mac.h | 3 --- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/atom/common/node_bindings_mac.cc b/atom/common/node_bindings_mac.cc index 877497d5a1e..9e61d27f496 100644 --- a/atom/common/node_bindings_mac.cc +++ b/atom/common/node_bindings_mac.cc @@ -5,6 +5,7 @@ #include "atom/common/node_bindings_mac.h" #include +#include #include #include #include @@ -14,13 +15,7 @@ namespace atom { NodeBindingsMac::NodeBindingsMac(bool is_browser) - : NodeBindings(is_browser), - kqueue_(kqueue()) { - // Add uv's backend fd to kqueue. - struct kevent ev; - EV_SET(&ev, uv_backend_fd(uv_loop_), EVFILT_READ, EV_ADD | EV_ENABLE, - 0, 0, 0); - kevent(kqueue_, &ev, 1, NULL, 0, NULL); + : NodeBindings(is_browser) { } NodeBindingsMac::~NodeBindingsMac() { @@ -44,19 +39,22 @@ void NodeBindingsMac::OnWatcherQueueChanged(uv_loop_t* loop) { } void NodeBindingsMac::PollEvents() { - struct timespec spec; + struct timeval tv; int timeout = uv_backend_timeout(uv_loop_); if (timeout != -1) { - spec.tv_sec = timeout / 1000; - spec.tv_nsec = (timeout % 1000) * 1000000; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; } + fd_set readset; + int fd = uv_backend_fd(uv_loop_); + FD_ZERO(&readset); + FD_SET(fd, &readset); + // Wait for new libuv events. int r; do { - struct kevent ev; - r = ::kevent(kqueue_, NULL, 0, &ev, 1, - timeout == -1 ? NULL : &spec); + r = select(fd + 1, &readset, NULL, NULL, timeout == -1 ? NULL : &tv); } while (r == -1 && errno == EINTR); } diff --git a/atom/common/node_bindings_mac.h b/atom/common/node_bindings_mac.h index 03152ada3ea..96c79ec6f0d 100644 --- a/atom/common/node_bindings_mac.h +++ b/atom/common/node_bindings_mac.h @@ -23,9 +23,6 @@ class NodeBindingsMac : public NodeBindings { void PollEvents() override; - // Kqueue to poll for uv's backend fd. - int kqueue_; - DISALLOW_COPY_AND_ASSIGN(NodeBindingsMac); }; From e9c9e22a9ecec3474d86ab3d39ae85fd192b1e86 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Tue, 3 May 2016 11:51:57 -0400 Subject: [PATCH 0695/1265] :memo: Fix Windows debug doc pointing to OS X [ci skip] --- docs/development/debug-instructions-windows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/debug-instructions-windows.md b/docs/development/debug-instructions-windows.md index 3a1a05e1103..509970237d6 100644 --- a/docs/development/debug-instructions-windows.md +++ b/docs/development/debug-instructions-windows.md @@ -11,7 +11,7 @@ with breakpoints inside Electron's source code. * **A debug build of Electron**: The easiest way is usually building it yourself, using the tools and prerequisites listed in the - [build instructions for Windows](build-instructions-osx.md). While you can + [build instructions for Windows](build-instructions-windows.md). While you can easily attach to and debug Electron as you can download it directly, you will find that it is heavily optimized, making debugging substantially more difficult: The debugger will not be able to show you the content of all From f84a973d69ecfc25f7a131c2ff43c8ee99308cdb Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 10:31:53 -0700 Subject: [PATCH 0696/1265] Revert "Use a DictionaryValue everywhere instead of a string map." This reverts commit 90cc10944a64d9a4998a3d12a2559baa7705b3af. --- atom/browser/api/atom_api_app.cc | 2 +- atom/browser/api/atom_api_app.h | 2 +- atom/browser/browser.cc | 3 ++- atom/browser/browser.h | 5 ++--- atom/browser/browser_mac.mm | 15 ++++++++++---- atom/browser/browser_observer.h | 4 +--- atom/browser/mac/atom_application_delegate.mm | 17 +++++++++++----- atom/browser/mac/mac_native_converter.h | 7 ++----- atom/browser/mac/mac_native_converter.mm | 20 ++++++------------- 9 files changed, 38 insertions(+), 37 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index ee73e5b2151..ec6cdce417c 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -252,7 +252,7 @@ void App::OnFinishLaunching() { void App::OnContinueUserActivity(bool* prevent_default, const std::string& type, - const base::DictionaryValue& user_info) { + const std::map& user_info) { *prevent_default = Emit("continue-activity", type, user_info); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index db510640fa6..321230d711e 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -74,7 +74,7 @@ class App : public AtomBrowserClient::Delegate, void OnLogin(LoginHandler* login_handler) override; void OnContinueUserActivity(bool* prevent_default, const std::string& type, - const base::DictionaryValue& user_info) override; + const std::map& user_info) override; // content::ContentBrowserClient: void AllowCertificateError( diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 62e0467e5d2..ee2a225246b 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -139,7 +139,8 @@ void Browser::Activate(bool has_visible_windows) { #if defined(OS_MACOSX) bool Browser::ContinueUserActivity(const std::string& type, - const base::DictionaryValue& user_info) { + const std::map& user_info) { bool prevent_default = false; FOR_EACH_OBSERVER(BrowserObserver, observers_, diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 4e282ed409a..14f94a061e4 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -10,7 +10,6 @@ #include #include "base/macros.h" -#include "base/values.h" #include "base/compiler_specific.h" #include "base/observer_list.h" #include "base/strings/string16.h" @@ -96,11 +95,11 @@ class Browser : public WindowListObserver { // Creates an activity and sets it as the one currently in use. void SetUserActivity(const std::string& type, - const base::DictionaryValue& user_info); + const std::map& user_info); // Resumes an activity via hand-off. bool ContinueUserActivity(const std::string& type, - const base::DictionaryValue& user_info); + const std::map& user_info); // Bounce the dock icon. enum BounceType { diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 594624f511c..a12bd8c8809 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -6,7 +6,6 @@ #include "atom/browser/mac/atom_application.h" #include "atom/browser/mac/atom_application_delegate.h" -#include "atom/browser/mac/mac_native_converter.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "base/mac/bundle_locations.h" @@ -88,12 +87,20 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { void Browser::SetAppUserModelID(const base::string16& name) { } -void Browser::SetUserActivity(const std::string& type, const base::DictionaryValue& user_info) { +void Browser::SetUserActivity(const std::string& type, const std::map& user_info) { NSString* type_ns = [NSString stringWithUTF8String:type.c_str()]; NSUserActivity *user_activity = [[NSUserActivity alloc] initWithActivityType:type_ns]; - MacNativeConverter* converter = [[MacNativeConverter alloc] init]; - user_activity.userInfo = [converter dictionaryFromDictionaryValue:user_info]; + NSMutableArray* user_info_args = [[NSMutableArray alloc] init]; + for (auto const &pair : user_info) { + NSString* value_ns = [NSString stringWithUTF8String:pair.second.c_str()]; + NSString* key_ns = [NSString stringWithUTF8String:pair.first.c_str()]; + + [user_info_args addObject:value_ns]; + [user_info_args addObject:key_ns]; + } + + user_activity.userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:user_info_args, nil]; [user_activity becomeCurrent]; } diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index e297e16d80d..4ad001370c0 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -8,8 +8,6 @@ #include #include -#include "base/values.h" - namespace atom { class LoginHandler; @@ -51,7 +49,7 @@ class BrowserObserver { // The browser wants to resume a user activity via handoff. (OS X only) virtual void OnContinueUserActivity(bool* prevent_default, const std::string& type, - const base::DictionaryValue& user_info) {} + const std::map& user_info) {} protected: virtual ~BrowserObserver() {} diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index ffb0b988aa2..f08cc84c466 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -3,9 +3,8 @@ // found in the LICENSE file. #import "atom/browser/mac/atom_application_delegate.h" -#import "atom/browser/mac/atom_application.h" -#import "atom/browser/mac/mac_native_converter.h" +#import "atom/browser/mac/atom_application.h" #include "atom/browser/browser.h" #include "base/strings/sys_string_conversions.h" @@ -65,11 +64,19 @@ continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); - MacNativeConverter* converter = [[MacNativeConverter alloc] init]; - const base::DictionaryValue* user_info = [converter dictionaryToDictionaryValue:userActivity.userInfo]; + std::map user_info; + + NSArray* keys = [userActivity.userInfo allKeys]; + for (NSString* key in keys) + { + NSString* value = [userActivity.userInfo objectForKey:key]; + std::string key_str(base::SysNSStringToUTF8(key)); + std::string value_str(base::SysNSStringToUTF8(value)); + user_info[key_str] = value_str; + } atom::Browser* browser = atom::Browser::Get(); - return browser->ContinueUserActivity(activity_type, *user_info) ? YES : NO; + return browser->ContinueUserActivity(activity_type, user_info) ? YES : NO; } @end diff --git a/atom/browser/mac/mac_native_converter.h b/atom/browser/mac/mac_native_converter.h index fcd1997fd1e..ac1a9a608d7 100644 --- a/atom/browser/mac/mac_native_converter.h +++ b/atom/browser/mac/mac_native_converter.h @@ -5,10 +5,7 @@ @interface MacNativeConverter : NSObject -- (base::ListValue*)arrayToListValue:(NSArray*)nsArray; -- (base::DictionaryValue*)dictionaryToDictionaryValue:(NSDictionary*)nsDictionary; - -- (NSArray*)arrayFromListValue:(const base::ListValue&)list; -- (NSDictionary*)dictionaryFromDictionaryValue:(const base::DictionaryValue&)dict; +- (base::ListValue*)arrayToV8:(NSArray*)nsArray; +- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary; @end diff --git a/atom/browser/mac/mac_native_converter.mm b/atom/browser/mac/mac_native_converter.mm index 202f3e0ee4a..63244036017 100644 --- a/atom/browser/mac/mac_native_converter.mm +++ b/atom/browser/mac/mac_native_converter.mm @@ -2,14 +2,14 @@ @implementation MacNativeConverter -- (base::ListValue*)arrayToListValue:(NSArray*)nsArray { +- (base::ListValue*)arrayToV8:(NSArray*)nsArray { scoped_ptr list(new base::ListValue); for (id value in nsArray) { if ([value isKindOfClass:[NSArray class]]) { - list->Append([self arrayToListValue:value]); + list->Append([self arrayToV8:value]); } else if ([value isKindOfClass:[NSDictionary class]]) { - list->Append([self dictionaryToDictionaryValue:value]); + list->Append([self dictionaryToV8:value]); } else if ([value isKindOfClass:[NSString class]]) { list->AppendString(base::SysNSStringToUTF8(value)); } else if ([value isKindOfClass:[NSNumber class]]) { @@ -20,7 +20,7 @@ return list.get(); } -- (base::DictionaryValue*)dictionaryToDictionaryValue:(NSDictionary*)nsDictionary { +- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary { scoped_ptr dict(new base::DictionaryValue); NSEnumerator *it = [nsDictionary keyEnumerator]; @@ -30,9 +30,9 @@ std::string key_str(base::SysNSStringToUTF8(key)); if ([value isKindOfClass:[NSArray class]]) { - dict->Set(key_str, [self arrayToListValue:value]); + dict->Set(key_str, [self arrayToV8:value]); } else if ([value isKindOfClass:[NSDictionary class]]) { - dict->Set(key_str, [self dictionaryToDictionaryValue:value]); + dict->Set(key_str, [self dictionaryToV8:value]); } else if ([value isKindOfClass:[NSString class]]) { dict->SetString(key_str, base::SysNSStringToUTF8(value)); } else if ([value isKindOfClass:[NSNumber class]]) { @@ -43,12 +43,4 @@ return dict.get(); } -- (NSArray*)arrayFromListValue:(const base::ListValue&)list { - return [[NSArray alloc] init]; -} - -- (NSDictionary*)dictionaryFromDictionaryValue:(const base::DictionaryValue&)dict { - return [[NSDictionary alloc] init]; -} - @end From 03d25ce6c074c28072bf7de147a32ad71e83958a Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 10:32:42 -0700 Subject: [PATCH 0697/1265] Revert "Add some shady methods to get V8 objects or arrays from NSDictionary or NSArray." This reverts commit 2295f3a8327d6df4031dcfcd8daebb771d0e3530. --- atom/browser/mac/atom_application_delegate.mm | 4 +- atom/browser/mac/mac_native_converter.h | 11 ----- atom/browser/mac/mac_native_converter.mm | 46 ------------------- filenames.gypi | 2 - 4 files changed, 2 insertions(+), 61 deletions(-) delete mode 100644 atom/browser/mac/mac_native_converter.h delete mode 100644 atom/browser/mac/mac_native_converter.mm diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index f08cc84c466..33aa47ce240 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -63,9 +63,9 @@ continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); - + std::map user_info; - + NSArray* keys = [userActivity.userInfo allKeys]; for (NSString* key in keys) { diff --git a/atom/browser/mac/mac_native_converter.h b/atom/browser/mac/mac_native_converter.h deleted file mode 100644 index ac1a9a608d7..00000000000 --- a/atom/browser/mac/mac_native_converter.h +++ /dev/null @@ -1,11 +0,0 @@ -#import - -#include "base/values.h" -#include "base/strings/sys_string_conversions.h" - -@interface MacNativeConverter : NSObject - -- (base::ListValue*)arrayToV8:(NSArray*)nsArray; -- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary; - -@end diff --git a/atom/browser/mac/mac_native_converter.mm b/atom/browser/mac/mac_native_converter.mm deleted file mode 100644 index 63244036017..00000000000 --- a/atom/browser/mac/mac_native_converter.mm +++ /dev/null @@ -1,46 +0,0 @@ -#import "atom/browser/mac/mac_native_converter.h" - -@implementation MacNativeConverter - -- (base::ListValue*)arrayToV8:(NSArray*)nsArray { - scoped_ptr list(new base::ListValue); - - for (id value in nsArray) { - if ([value isKindOfClass:[NSArray class]]) { - list->Append([self arrayToV8:value]); - } else if ([value isKindOfClass:[NSDictionary class]]) { - list->Append([self dictionaryToV8:value]); - } else if ([value isKindOfClass:[NSString class]]) { - list->AppendString(base::SysNSStringToUTF8(value)); - } else if ([value isKindOfClass:[NSNumber class]]) { - list->AppendInteger(((NSNumber* )value).intValue); - } - } - - return list.get(); -} - -- (base::DictionaryValue*)dictionaryToV8:(NSDictionary*)nsDictionary { - scoped_ptr dict(new base::DictionaryValue); - - NSEnumerator *it = [nsDictionary keyEnumerator]; - while (NSString *key = [it nextObject]) { - id value = [nsDictionary objectForKey:key]; - - std::string key_str(base::SysNSStringToUTF8(key)); - - if ([value isKindOfClass:[NSArray class]]) { - dict->Set(key_str, [self arrayToV8:value]); - } else if ([value isKindOfClass:[NSDictionary class]]) { - dict->Set(key_str, [self dictionaryToV8:value]); - } else if ([value isKindOfClass:[NSString class]]) { - dict->SetString(key_str, base::SysNSStringToUTF8(value)); - } else if ([value isKindOfClass:[NSNumber class]]) { - dict->SetInteger(key_str, ((NSNumber* )value).intValue); - } - } - - return dict.get(); -} - -@end diff --git a/filenames.gypi b/filenames.gypi index 033d4959454..783b5cb33d0 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -183,8 +183,6 @@ 'atom/browser/mac/atom_application.mm', 'atom/browser/mac/atom_application_delegate.h', 'atom/browser/mac/atom_application_delegate.mm', - 'atom/browser/mac/mac_native_converter.h', - 'atom/browser/mac/mac_native_converter.mm', 'atom/browser/native_window.cc', 'atom/browser/native_window.h', 'atom/browser/native_window_views_win.cc', From a5a2e204490d0af2ac80f5b99087a423a4edb302 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 10:34:59 -0700 Subject: [PATCH 0698/1265] :memo: on using only strings. --- docs/api/app.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/api/app.md b/docs/api/app.md index 61e86b70f9a..4bd121adfb6 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -117,7 +117,8 @@ Returns: * `event` Event * `type` String - A string identifying the event. Maps to [`NSUserActivity.activityType`](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType). -* `userInfo` Object - Contains app-specific state stored by the activity on another device. +* `userInfo` Object - Contains app-specific state stored by the activity on +another device. Currently only string data is supported. Emitted during [handoff](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html) when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this @@ -503,8 +504,8 @@ app.on('ready', function() { * `type` String - Uniquely identifies the activity. It's recommended to use a reverse-DNS string. -* `userInfo` Object - Contains app-specific state stored by the activity on -another device. +* `userInfo` Object - App-specific state to store for use by another device. +Currently only string data is supported. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [handoff](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html) to another device afterward. From ebd8d30f25c3c3999c3a58de71934cd9c22e03c2 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 4 May 2016 02:55:10 +0900 Subject: [PATCH 0699/1265] :memo: Small fixes [ci skip] --- docs-translations/ko-KR/README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs-translations/ko-KR/README.md b/docs-translations/ko-KR/README.md index 0e6c0fda8c8..63c8716e4fc 100644 --- a/docs-translations/ko-KR/README.md +++ b/docs-translations/ko-KR/README.md @@ -6,10 +6,9 @@ URL에 포함되어 있습니다. 만약 그렇지 않다면, 아마 현재 보 수 있습니다. 또한 GitHub 인터페이스의 "Switch branches/tags" 드롭다운 메뉴에서도 사용 중인 Electron 버전으로 변경할 수 있습니다. -**역주:** 한국어 번역 문서는 `atom.io`에 반영되어 있지 않습니다. 따라서 번역 문서는 -GitHub 프로젝트내에서만 볼 수 있으며 `master` 브랜치의 문서는 현재 개발중인 프로젝트의 -문서입니다. 한국어 번역 문서는 현재 `upstream` 원본 문서의 변경에 따라 최대한 문서의 -버전을 맞추려고 노력하고 있지만 가끔 누락된 번역이 존재할 수 있습니다. +**역주:** 한국어 번역 문서는 `atom.io`에 반영되어 있지 않습니다. 한국어 번역 문서는 +현재 `upstream` 원본 문서의 변경에 따라 최대한 문서의 버전을 맞추려고 노력하고 있지만 +가끔 누락된 번역이 존재할 수 있습니다. ## FAQ From 0fffbea79dd3b2789afc40264c2de505739459d9 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Mon, 2 May 2016 20:02:33 -0400 Subject: [PATCH 0700/1265] Add 'context-menu' event to 'WebContents' --- atom/browser/api/atom_api_web_contents.cc | 10 ++- .../native_mate_converters/blink_converter.cc | 88 +++++++++++++++++++ .../native_mate_converters/blink_converter.h | 17 ++++ .../content_converter.cc | 20 +++++ .../ui_base_types_converter.h | 34 +++++++ filenames.gypi | 1 + 6 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 atom/common/native_mate_converters/ui_base_types_converter.h diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index a48277490b0..7785808f369 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -440,11 +440,13 @@ void WebContents::RendererResponsive(content::WebContents* source) { } bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) { - if (!params.custom_context.is_pepper_menu) - return false; + if (params.custom_context.is_pepper_menu) { + Emit("pepper-context-menu", std::make_pair(params, web_contents())); + web_contents()->NotifyContextMenuClosed(params.custom_context); + } else { + Emit("context-menu", std::make_pair(params, web_contents())); + } - Emit("pepper-context-menu", std::make_pair(params, web_contents())); - web_contents()->NotifyContextMenuClosed(params.custom_context); return true; } diff --git a/atom/common/native_mate_converters/blink_converter.cc b/atom/common/native_mate_converters/blink_converter.cc index c58f830eb02..e63534820f0 100644 --- a/atom/common/native_mate_converters/blink_converter.cc +++ b/atom/common/native_mate_converters/blink_converter.cc @@ -15,6 +15,7 @@ #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" #include "third_party/WebKit/public/web/WebFindOptions.h" #include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/base/clipboard/clipboard.h" namespace { @@ -296,4 +297,91 @@ bool Converter::FromV8( return true; } +// static +v8::Local Converter::ToV8( + v8::Isolate* isolate, const blink::WebContextMenuData::MediaType& in) { + switch (in) { + case blink::WebContextMenuData::MediaTypeImage: + return mate::StringToV8(isolate, "image"); + case blink::WebContextMenuData::MediaTypeVideo: + return mate::StringToV8(isolate, "video"); + case blink::WebContextMenuData::MediaTypeAudio: + return mate::StringToV8(isolate, "audio"); + case blink::WebContextMenuData::MediaTypeCanvas: + return mate::StringToV8(isolate, "canvas"); + case blink::WebContextMenuData::MediaTypeFile: + return mate::StringToV8(isolate, "file"); + case blink::WebContextMenuData::MediaTypePlugin: + return mate::StringToV8(isolate, "plugin"); + default: + return mate::StringToV8(isolate, "none"); + } +} + +// static +v8::Local Converter::ToV8( + v8::Isolate* isolate, + const blink::WebContextMenuData::InputFieldType& in) { + switch (in) { + case blink::WebContextMenuData::InputFieldTypePlainText: + return mate::StringToV8(isolate, "plain-text"); + case blink::WebContextMenuData::InputFieldTypePassword: + return mate::StringToV8(isolate, "password"); + case blink::WebContextMenuData::InputFieldTypeOther: + return mate::StringToV8(isolate, "other"); + default: + return mate::StringToV8(isolate, "none"); + } +} + +v8::Local EditFlagsToV8(v8::Isolate* isolate, int editFlags) { + mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); + dict.Set("canUndo", + !!(editFlags & blink::WebContextMenuData::CanUndo)); + dict.Set("canRedo", + !!(editFlags & blink::WebContextMenuData::CanRedo)); + dict.Set("canCut", + !!(editFlags & blink::WebContextMenuData::CanCut)); + dict.Set("canCopy", + !!(editFlags & blink::WebContextMenuData::CanCopy)); + + bool pasteFlag = false; + if (editFlags & blink::WebContextMenuData::CanPaste) { + std::vector types; + bool ignore; + ui::Clipboard::GetForCurrentThread()->ReadAvailableTypes( + ui::CLIPBOARD_TYPE_COPY_PASTE, &types, &ignore); + pasteFlag = !types.empty(); + } + dict.Set("canPaste", pasteFlag); + + dict.Set("canDelete", + !!(editFlags & blink::WebContextMenuData::CanDelete)); + dict.Set("canSelectAll", + !!(editFlags & blink::WebContextMenuData::CanSelectAll)); + + return mate::ConvertToV8(isolate, dict); +} + +v8::Local MediaFlagsToV8(v8::Isolate* isolate, int mediaFlags) { + mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); + dict.Set("inError", + !!(mediaFlags & blink::WebContextMenuData::MediaInError)); + dict.Set("isPaused", + !!(mediaFlags & blink::WebContextMenuData::MediaPaused)); + dict.Set("isMuted", + !!(mediaFlags & blink::WebContextMenuData::MediaMuted)); + dict.Set("hasAudio", + !!(mediaFlags & blink::WebContextMenuData::MediaHasAudio)); + dict.Set("isLooping", + (mediaFlags & blink::WebContextMenuData::MediaLoop) != 0); + dict.Set("isControlsVisible", + (mediaFlags & blink::WebContextMenuData::MediaControls) != 0); + dict.Set("canToggleControls", + !!(mediaFlags & blink::WebContextMenuData::MediaCanToggleControls)); + dict.Set("canRotate", + !!(mediaFlags & blink::WebContextMenuData::MediaCanRotate)); + return mate::ConvertToV8(isolate, dict); +} + } // namespace mate diff --git a/atom/common/native_mate_converters/blink_converter.h b/atom/common/native_mate_converters/blink_converter.h index 6a360192921..514c6ab680c 100644 --- a/atom/common/native_mate_converters/blink_converter.h +++ b/atom/common/native_mate_converters/blink_converter.h @@ -6,6 +6,7 @@ #define ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ #include "native_mate/converter.h" +#include "third_party/WebKit/public/web/WebContextMenuData.h" namespace blink { class WebInputEvent; @@ -87,6 +88,22 @@ struct Converter { blink::WebFindOptions* out); }; +template<> +struct Converter { + static v8::Local ToV8(v8::Isolate* isolate, + const blink::WebContextMenuData::MediaType& in); +}; + +template<> +struct Converter { + static v8::Local ToV8(v8::Isolate* isolate, + const blink::WebContextMenuData::InputFieldType& in); +}; + +v8::Local EditFlagsToV8(v8::Isolate* isolate, int editFlags); + +v8::Local MediaFlagsToV8(v8::Isolate* isolate, int mediaFlags); + } // namespace mate #endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_ diff --git a/atom/common/native_mate_converters/content_converter.cc b/atom/common/native_mate_converters/content_converter.cc index 154dcf88ce3..5589c5a84af 100644 --- a/atom/common/native_mate_converters/content_converter.cc +++ b/atom/common/native_mate_converters/content_converter.cc @@ -9,8 +9,11 @@ #include "atom/browser/api/atom_api_web_contents.h" #include "atom/browser/web_contents_permission_helper.h" +#include "atom/common/native_mate_converters/blink_converter.h" #include "atom/common/native_mate_converters/callback.h" +#include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" +#include "atom/common/native_mate_converters/ui_base_types_converter.h" #include "content/public/browser/web_contents.h" #include "content/public/common/context_menu_params.h" #include "native_mate/dictionary.h" @@ -94,6 +97,23 @@ v8::Local Converter::ToV8( mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("x", params.x); dict.Set("y", params.y); + dict.Set("linkURL", params.link_url); + dict.Set("linkText", params.link_text); + dict.Set("pageURL", params.page_url); + dict.Set("frameURL", params.frame_url); + dict.Set("srcURL", params.src_url); + dict.Set("mediaType", params.media_type); + dict.Set("mediaFlags", MediaFlagsToV8(isolate, params.media_flags)); + dict.Set("hasImageContents", params.has_image_contents); + dict.Set("isEditable", params.is_editable); + dict.Set("editFlags", EditFlagsToV8(isolate, params.edit_flags)); + dict.Set("selectionText", params.selection_text); + dict.Set("titleText", params.title_text); + dict.Set("misspelledWord", params.misspelled_word); + dict.Set("frameCharset", params.frame_charset); + dict.Set("inputFieldType", params.input_field_type); + dict.Set("menuSourceType", params.source_type); + if (params.custom_context.is_pepper_menu) dict.Set("menu", MenuToV8(isolate, val.second, params.custom_context, params.custom_items)); diff --git a/atom/common/native_mate_converters/ui_base_types_converter.h b/atom/common/native_mate_converters/ui_base_types_converter.h new file mode 100644 index 00000000000..ac2920fcea4 --- /dev/null +++ b/atom/common/native_mate_converters/ui_base_types_converter.h @@ -0,0 +1,34 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_COMMON_NATIVE_MATE_CONVERTERS_UI_BASE_TYPES_CONVERTER_H_ +#define ATOM_COMMON_NATIVE_MATE_CONVERTERS_UI_BASE_TYPES_CONVERTER_H_ + +#include "native_mate/converter.h" +#include "ui/base/ui_base_types.h" + +namespace mate { + +template<> +struct Converter { + static v8::Local ToV8(v8::Isolate* isolate, + const ui::MenuSourceType& in) { + switch (in) { + case ui::MENU_SOURCE_MOUSE: + return mate::StringToV8(isolate, "mouse"); + case ui::MENU_SOURCE_KEYBOARD: + return mate::StringToV8(isolate, "keyboard"); + case ui::MENU_SOURCE_TOUCH: + return mate::StringToV8(isolate, "touch"); + case ui::MENU_SOURCE_TOUCH_EDIT_MENU: + return mate::StringToV8(isolate, "touch-menu"); + default: + return mate::StringToV8(isolate, "none"); + } + } +}; + +} // namespace mate + +#endif // ATOM_COMMON_NATIVE_MATE_CONVERTERS_UI_BASE_TYPES_CONVERTER_H_ diff --git a/filenames.gypi b/filenames.gypi index 1c213949756..3ad66e7fafc 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -362,6 +362,7 @@ 'atom/common/native_mate_converters/net_converter.cc', 'atom/common/native_mate_converters/net_converter.h', 'atom/common/native_mate_converters/string16_converter.h', + 'atom/common/native_mate_converters/ui_base_types_converter.h', 'atom/common/native_mate_converters/v8_value_converter.cc', 'atom/common/native_mate_converters/v8_value_converter.h', 'atom/common/native_mate_converters/value_converter.cc', From 81eb3e342871b40c28982f1a42cc0d0617084b10 Mon Sep 17 00:00:00 2001 From: Daniel Pham Date: Tue, 3 May 2016 08:48:16 -0400 Subject: [PATCH 0701/1265] :memo: Document 'context-menu' event --- docs/api/web-contents.md | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 64e7cea60e7..17cc31cf232 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -308,6 +308,63 @@ If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a `NativeImage`, and the `scale` will hold scaling information for the image. +### Event: 'context-menu' + +Returns: + +* `event` Event +* `params` Object + * `x` Integer - x coodinate + * `y` Integer - y coodinate + * `linkURL` String - URL of the link that encloses the node the context menu +was invoked on. + * `linkText` String - Text associated with the link. May be an empty +string if the contents of the link are an image. + * `pageURL` String - URL of the top level page that the context menu was +invoked on. + * `frameURL` String - URL of the subframe that the context menu was invoked +on. + * `srcURL` String - Source URL for the element that the context menu +was invoked on. Elements with source URLs are images, audio and video. + * `mediaType` String - Type of the node the context menu was invoked on. Can +be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. + * `mediaFlags` Object - Parameters for the media element the context menu was +invoked on. + * `inError` - Boolean + * `isPaused` - Boolean + * `isMuted` - Boolean + * `hasAudio` - Boolean + * `isLooping` - Boolean + * `isControlsVisible` - Boolean + * `canToggleControls` - Boolean + * `canRotate` - Boolean + * `hasImageContent` Boolean - Wether the context menu was invoked on an image +which has non-empty contents. + * `isEditable` Boolean - Wether the context is editable. + * `editFlags` Object - These flags indicate wether the renderer believes it is +able to perform the corresponding action. + * `canUndo` - Boolean + * `canRedo` - Boolean + * `canCut` - Boolean + * `canCopy` - Boolean + * `canPaste` - Boolean + * `canDelete` - Boolean + * `canSelectAll` - Boolean + * `selectionText` String - Text of the selection that the context menu was +invoked on. + * `titleText` String - Title or alt text of the selection that the context +was invoked on. + * `misspelledWord` String - The misspelled word under the cursor, if any. + * `frameCharset` String - The character encoding of the frame on which the +menu was invoked. + * `inputFieldType` String - If the context menu was invoked on an input +field, the type of that field. Possible values are `none`, `plain-text`, +`password`, `other`. + * `menuSourceType` String - Input source that invoked the context menu. +Can be `none`, `mouse`, `keyboard`, `touch`, `touch-menu`. + +Emitted when there is a new context menu that needs to be handled. + ## Instance Methods The `webContents` object has the following instance methods: From 42768bcc2bf709a34f6c3b9ba4a65ba96da081d2 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 14:57:16 -0700 Subject: [PATCH 0702/1265] Save the activity on the application instance to ensure we hold a reference. Activities that enable search need to persist. --- atom/browser/browser_mac.mm | 4 +++- atom/browser/mac/atom_application.h | 5 +++++ atom/browser/mac/atom_application.mm | 8 ++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index a12bd8c8809..58ee84613e4 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -89,7 +89,7 @@ void Browser::SetAppUserModelID(const base::string16& name) { void Browser::SetUserActivity(const std::string& type, const std::map& user_info) { NSString* type_ns = [NSString stringWithUTF8String:type.c_str()]; - NSUserActivity *user_activity = [[NSUserActivity alloc] initWithActivityType:type_ns]; + NSUserActivity* user_activity = [[NSUserActivity alloc] initWithActivityType:type_ns]; NSMutableArray* user_info_args = [[NSMutableArray alloc] init]; for (auto const &pair : user_info) { @@ -102,6 +102,8 @@ void Browser::SetUserActivity(const std::string& type, const std::map { @private BOOL handlingSendEvent_; + NSUserActivity* currentActivity_; } + (AtomApplication*)sharedApplication; @@ -18,4 +19,8 @@ // CrAppControlProtocol: - (void)setHandlingSendEvent:(BOOL)handlingSendEvent; +- (NSUserActivity*)getCurrentActivity; + +- (void)setCurrentActivity:(NSUserActivity*)userActivity; + @end diff --git a/atom/browser/mac/atom_application.mm b/atom/browser/mac/atom_application.mm index cc9c6accc83..3fe6658e4cf 100644 --- a/atom/browser/mac/atom_application.mm +++ b/atom/browser/mac/atom_application.mm @@ -28,6 +28,14 @@ handlingSendEvent_ = handlingSendEvent; } +- (void)setCurrentActivity:(NSUserActivity*)userActivity { + currentActivity_ = userActivity; +} + +- (NSUserActivity*)getCurrentActivity { + return currentActivity_; +} + - (void)awakeFromNib { [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self From 12764a66edb39af0332e1297d321a7045feb7b52 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 15:51:31 -0700 Subject: [PATCH 0703/1265] Add an accessor for the current activity type and write the simplest possible test. --- atom/browser/api/atom_api_app.cc | 2 ++ atom/browser/browser.h | 3 +++ atom/browser/browser_mac.mm | 15 ++++++++++----- atom/browser/mac/atom_application_delegate.mm | 7 +++---- docs/api/app.md | 4 ++++ spec/api-app-spec.js | 7 +++++++ 6 files changed, 29 insertions(+), 9 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index ec6cdce417c..f15fad9d47f 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -469,6 +469,8 @@ void App::BuildPrototype( .SetMethod("show", base::Bind(&Browser::Show, browser)) .SetMethod("setUserActivity", base::Bind(&Browser::SetUserActivity, browser)) + .SetMethod("getCurrentActivityType", + base::Bind(&Browser::GetCurrentActivityType, browser)) #endif #if defined(OS_WIN) .SetMethod("setUserTasks", diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 14f94a061e4..5c3dcaf5122 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -97,6 +97,9 @@ class Browser : public WindowListObserver { void SetUserActivity(const std::string& type, const std::map& user_info); + // Returns the type name of the current user activity. + std::string GetCurrentActivityType(); + // Resumes an activity via hand-off. bool ContinueUserActivity(const std::string& type, const std::map& user_info); diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 58ee84613e4..069579354bd 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -91,19 +91,24 @@ void Browser::SetUserActivity(const std::string& type, const std::map user_info; - + NSArray* keys = [userActivity.userInfo allKeys]; - for (NSString* key in keys) - { + for (NSString* key in keys) { NSString* value = [userActivity.userInfo objectForKey:key]; std::string key_str(base::SysNSStringToUTF8(key)); std::string value_str(base::SysNSStringToUTF8(value)); diff --git a/docs/api/app.md b/docs/api/app.md index 4bd121adfb6..3ade1da034f 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -510,6 +510,10 @@ Currently only string data is supported. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [handoff](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html) to another device afterward. +### `app.getCurrentActivityType()` _OS X_ + +Returns the type of the currently running activity. + ### `app.setAppUserModelId(id)` _Windows_ * `id` String diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 1c20ef8e452..809e5520b93 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -89,6 +89,13 @@ describe('app module', function () { }) }) + describe('app.setUserActivity(type, userInfo)', function () { + it('sets the current activity', function () { + app.setUserActivity('com.electron.testActivity', {testData: '123'}); + assert.equal(app.getCurrentActivityType(), 'com.electron.testActivity'); + }) + }) + describe('app.importCertificate', function () { if (process.platform !== 'linux') return From d63d570327e7e0ee55c358a27b29a899a6e6708e Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 4 May 2016 09:46:14 +0900 Subject: [PATCH 0704/1265] :memo: Fix typo [ci skip] --- docs-translations/ko-KR/tutorial/testing-on-headless-ci.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md index 4fec05e1505..8343777e436 100644 --- a/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md +++ b/docs-translations/ko-KR/tutorial/testing-on-headless-ci.md @@ -1,4 +1,4 @@ -# Headless CI 시스템에서 테스팅하기 (Travis, Jenkins) (Travis CI, Jenkins) +# Headless CI 시스템에서 테스팅하기 (Travis, Jenkins) Chromium을 기반으로 한 Electron은 작업을 위해 디스플레이 드라이버가 필요합니다. 만약 Chromium이 디스플레이 드라이버를 찾기 못한다면, Electron은 그대로 실행에 From 8be2239a457bd44d11384bba473ebd3ecc224b21 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 4 May 2016 14:34:11 +0900 Subject: [PATCH 0705/1265] :memo: Match code syntax [ci skip] --- docs/development/build-instructions-linux.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/build-instructions-linux.md b/docs/development/build-instructions-linux.md index 97779f376c8..d91b7192842 100644 --- a/docs/development/build-instructions-linux.md +++ b/docs/development/build-instructions-linux.md @@ -158,7 +158,7 @@ $ ./script/build.py -c R By default Electron is built with prebuilt `clang` binaries provided by Chromium project. If for some reason you want to build with the `clang` installed in your system, you can call `bootstrap.py` with `--clang_dir=` switch. By passing -it the build script will assume the clang binaries reside in `/bin/`. +it the build script will assume the `clang` binaries reside in `/bin/`. For example if you installed `clang` under `/user/local/bin/clang`: From 9fcafc6f9ee446b96e66cad4faa6beb35e421fec Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Wed, 4 May 2016 15:00:59 +0900 Subject: [PATCH 0706/1265] :memo: Update Korean docs as upstream [ci skip] --- .../development/build-instructions-linux.md | 74 ++++++++++++++++++- .../development/build-instructions-osx.md | 2 +- .../development/build-instructions-windows.md | 2 +- 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/docs-translations/ko-KR/development/build-instructions-linux.md b/docs-translations/ko-KR/development/build-instructions-linux.md index 5a0dc2e5f3f..3cd410a4bbf 100644 --- a/docs-translations/ko-KR/development/build-instructions-linux.md +++ b/docs-translations/ko-KR/development/build-instructions-linux.md @@ -71,7 +71,7 @@ $ sudo apt-get install libc6-dev-armhf-cross linux-libc-dev-armhf-cross \ $ ./script/bootstrap.py -v --target_arch=arm ``` -## 빌드 하기 +## 빌드하기 `Release` 와 `Debug` 두 타겟 모두 빌드 합니다: @@ -100,7 +100,7 @@ $ ./script/build.py -c D 빌드가 모두 끝나면 `out/D` 디렉터리에서 `electron` 디버그 바이너리를 찾을 수 있습니다. -## 정리 하기 +## 정리하기 빌드 파일들을 정리합니다: @@ -132,3 +132,73 @@ $ npm run lint ```bash $ ./script/test.py ``` + +## 고급 주제 + +기본적인 빌드 구성은 가장 주력인 Linux 배포판에 초점이 맞춰져있으며, 특정 배포판이나 +기기에 빌드할 계획이라면 다음 정보들이 도움이 될 것입니다. + +### 로컬에서 `libchromiumcontent` 빌드하기 + +미리 빌드된 `libchromiumcontent`를 사용하는 것을 피하기 위해, `bootstrap.py` +스크립트에 `--build_libchromiumcontent` 스위치를 추가할 수 있습니다: + +```bash +$ ./script/bootstrap.py -v --build_libchromiumcontent +``` + +참고로 `shared_library` 구성은 기본적으로 빌드되어있지 않으며, 다음 모드를 사용하면 +`Release` 버전의 Electron만 빌드할 수 있습니다: + +```bash +$ ./script/build.py -c R +``` + +### 다운로드된 `clang` 바이너리 대신 시스템의 `clang` 사용하기 + +기본적으로 Electron은 Chromium 프로젝트에서 제공하는 미리 빌드된 `clang` 바이너리를 +통해 빌드됩니다. 만약 어떤 이유로 시스템에 설치된 `clang`을 사용하여 빌드하고 싶다면, +`bootstrap.py`를 `--clang_dir=` 스위치와 함께 실행함으로써 해결할 수 있습니다. +빌드 스크립트를 이 스위치와 함께 실행할 때 스크립트는 `/bin/`와 같은 경로로 +`clang` 바이너리를 찾습니다. + +예를 들어 `clang`을 `/user/local/bin/clang`에 설치했다면 다음과 같습니다: + +```bash +$ ./script/bootstrap.py -v --build_libchromiumcontent --clang_dir /usr/local +$ ./script/build.py -c R +``` + +### `clang` 대신 다른 컴파일러 사용하기 + +Electron을 `g++`과 같은 다른 컴파일러로 빌드하려면, 먼저 `--disable_clang` 스위치를 +통해 `clang`을 비활성화 시켜야 하고, 필요하다면 `CC`와 `CXX` 환경 변수도 설정합니다. + +예를 들어 GCC 툴체인을 사용하여 빌드한다면 다음과 같습니다: + +```bash +$ env CC=gcc CXX=g++ ./script/bootstrap.py -v --build_libchromiumcontent --disable_clang +$ ./script/build.py -c R +``` + +### 환경 변수 + +또한 `CC`와 `CXX`와는 별개로, 빌드 구성을 변경하기 위해 다음 환경 변수들을 사용할 수 +있습니다: + +* `CPPFLAGS` +* `CPPFLAGS_host` +* `CFLAGS` +* `CFLAGS_host` +* `CXXFLAGS` +* `CXXFLAGS_host` +* `AR` +* `AR_host` +* `CC` +* `CC_host` +* `CXX` +* `CXX_host` +* `LDFLAGS` + +이 환경 변수는 `bootstrap.py` 스크립트를 실행할 때 설정되어야 하며, `build.py` +스크립트에선 작동하지 않습니다. diff --git a/docs-translations/ko-KR/development/build-instructions-osx.md b/docs-translations/ko-KR/development/build-instructions-osx.md index 1a1a13a4576..55a88b0cefd 100644 --- a/docs-translations/ko-KR/development/build-instructions-osx.md +++ b/docs-translations/ko-KR/development/build-instructions-osx.md @@ -29,7 +29,7 @@ $ cd electron $ ./script/bootstrap.py -v ``` -## 빌드 하기 +## 빌드하기 `Release` 와 `Debug` 두 타겟 모두 빌드 합니다: diff --git a/docs-translations/ko-KR/development/build-instructions-windows.md b/docs-translations/ko-KR/development/build-instructions-windows.md index 4d1c57a33b4..7d30635a6a0 100644 --- a/docs-translations/ko-KR/development/build-instructions-windows.md +++ b/docs-translations/ko-KR/development/build-instructions-windows.md @@ -41,7 +41,7 @@ $ cd electron $ python script\bootstrap.py -v ``` -## 빌드 하기 +## 빌드하기 `Release` 와 `Debug` 두 타겟 모두 빌드 합니다: From 7b207aa1b67b4068fd8cb1afd7dc715584faed9d Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Tue, 3 May 2016 23:33:40 -0700 Subject: [PATCH 0707/1265] Don't run this spec on platforms where the method is unavailable. --- spec/api-app-spec.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 809e5520b93..30df5361041 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -7,6 +7,7 @@ const remote = require('electron').remote const app = remote.require('electron').app const BrowserWindow = remote.require('electron').BrowserWindow +const isCI = remote.getGlobal('isCi') describe('electron module', function () { it('allows old style require by default', function () { @@ -90,6 +91,10 @@ describe('app module', function () { }) describe('app.setUserActivity(type, userInfo)', function () { + if (isCI && process.platform !== 'darwin') { + return + } + it('sets the current activity', function () { app.setUserActivity('com.electron.testActivity', {testData: '123'}); assert.equal(app.getCurrentActivityType(), 'com.electron.testActivity'); From 540076e9d55fcb2cd80368d971d1e8723c6167b8 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 4 May 2016 17:12:10 +0900 Subject: [PATCH 0708/1265] Fix code styling issue --- atom/browser/auto_updater_mac.mm | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/atom/browser/auto_updater_mac.mm b/atom/browser/auto_updater_mac.mm index edc6972d16d..ab996dda90a 100644 --- a/atom/browser/auto_updater_mac.mm +++ b/atom/browser/auto_updater_mac.mm @@ -90,13 +90,11 @@ void AutoUpdater::CheckForUpdates() { delegate->OnUpdateNotAvailable(); } } error:^(NSError *error) { - NSString *failureString; - if(error.localizedFailureReason) { - failureString = [NSString stringWithFormat:@"%@: %@", - error.localizedDescription, error.localizedFailureReason]; - } else { - failureString = [NSString stringWithString: error.localizedDescription]; - } + NSString* failureString = error.localizedFailureReason ? + [NSString stringWithFormat:@"%@: %@", + error.localizedDescription, + error.localizedFailureReason] : + [NSString stringWithString:error.localizedDescription]; delegate->OnError(base::SysNSStringToUTF8(failureString)); }]; } From 5e73b0372df30f13e993c33dbd71d04cf8699ee0 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 4 May 2016 17:38:03 +0900 Subject: [PATCH 0709/1265] Make the drag box fill the remaining height of window --- default_app/index.html | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index c10d67a089a..a6126e5de6c 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -10,10 +10,15 @@ font-variant: normal; padding: 0; margin: 0; + display: flex; + flex-direction: column; } .container { - padding: 15px 30px; + margin: 15px 30px 30px 30px; + flex: 1; + display: flex; + flex-direction: column; } .header { @@ -90,11 +95,9 @@ #holder { display: flex; + flex: 1; align-items: center; justify-content: center; - margin: 0 auto; - padding: 10px; - height: 275px; border: 1px solid #e0e5e6; background-color: #f6f8f8; color: #466a72; @@ -132,7 +135,7 @@ }; -
+
-
+
From 7074789011541b72ef838107baa2a1d68ef9cd76 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 4 May 2016 17:43:21 +0900 Subject: [PATCH 0710/1265] Remove some unnecessary css rules --- default_app/index.html | 6 ------ 1 file changed, 6 deletions(-) diff --git a/default_app/index.html b/default_app/index.html index a6126e5de6c..b7910f00ef8 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -4,11 +4,7 @@ +``` + +## Tag 属性 + +`webview`タグは下記のような属性を持っています: + +### `src` + +```html + +``` + +表示されているURLを返します。本属性への書き込みは、トップレベルナビゲーションを開始させます。 + +`src`の値を現在の値に再度設定することで、現在のページを再読み込みさせることができます。 + +また、`src`属性はdata URLを指定することができます(例: `data:text/plain,Hello, world!`)。 + +### `autosize` + +```html + +``` + +"on"の際は、`minwidth`, `minheight`, `maxwidth`, `maxheight`で設定された範囲内で、自動的に大きさが変化します。 +これらの制限値は、`autosize`が有効でない場合は影響しません。 +`autosize`が有効の際は、`webview`コンテナサイズは指定した最小値より小さくなりませんし、最大値より大きくなりません。 + +### `nodeintegration` + +```html + +``` + +"on"の際は、`webview`内のゲストページ(外部コンテンツ)でnode integrationが有効となり、`require`や`process`と行ったnode APIでシステムリソースにアクセスできるようになります。1 + +**注意:** 親ウィンドウでnode integrationが無効の場合は、`webview`でも常に無効になります。 + + +### `plugins` + +```html + +``` + +"on"の際は、ゲストページはブラウザプラグインを使用できます。 + +### `preload` + +```html + +``` + +ゲストページ上のスクリプトより先に実行されるスクリプトを指定してください。内部では、ゲストページ内で`require`で読み込まれるので、スクリプトのURLのプロトコルはは`file:`または`asar:`でなければなりません。 + +ゲストページがnode integrationが無効の場合でも、このスクリプトは全てのNode APIにアクセスできます。ただし、グローバルオブジェクトはこのスクリプトの実行終了後にすべて削除されます。 + +### `httpreferrer` + +```html + +``` + +ゲストページのためにリファラを設定します。 + +### `useragent` + +```html + +``` + +ページ遷移の前に、User agentを指定します。すでにページが読み込まれている場合は、`setUserAgent`メソッドを利用して変更してください。 + +### `disablewebsecurity` + +```html + +``` + +"on"の際は、ゲストページのウェブセキュリティは無効となります。 + +### `partition` + +```html + + +``` + +ページで使用されるセッションを設定します。もし、`partition`が`persist:`から始まる場合、アプリ上の同じ`partition`を指定した全てのページで有効な永続セッションを使用します。 +`persist:`接頭辞なしで指定した場合、メモリ内セッションを使用します。同じセッションを指定すると複数のページで同じセッションを使用できます。 +`partition`を設定しない場合は、アプリケーションのデフォルトセッションが使用されます。 + +レンダラプロセスのセッションは変更できないため、この値は最初のページ遷移の前に変更されないといけません。 +その後に変更をしようとしても、DOM例外を起こすことになります。 + +### `allowpopups` + +```html + +``` + +"on"の場合、ゲストページは新しいウィンドウを開くことができます。 + +### `blinkfeatures` + +```html + +``` + +有効にしたいblink featureを`,`で区切って指定します。 +サポートされている全ての機能は、[setFeatureEnabledFromString][blink-feature-string]にリストがあります。 + +## メソッド + +`webview`タグは、下記のようなメソッドを持っています: + +**注意:** webview要素はメソッドを使用する前に読み込まれていないといけません。 + +**例** + +```javascript +webview.addEventListener('dom-ready', () => { + webview.openDevTools(); +}); +``` + +### `.loadURL(url[, options])` + +* `url` URL +* `options` Object (optional) + * `httpReferrer` String - リファラURL + * `userAgent` String - リクエストに使用されるUser agent + * `extraHeaders` String - 追加のヘッダを"\n"で区切って指定します。 + +`url`をwebviewで読み込みます。`url`はプロトコル接頭辞(`http://`や`file://`など)を含んでいなければいけません。 + +### `.getURL()` + +ゲストページのURLを取得します。 + +### `.getTitle()` + +ゲストページのタイトルを返します。 + +### `.isLoading()` + +ゲストページが読み込み中かのbool値を返します。 + +### `.isWaitingForResponse()` + +ゲストページがページの最初の返答を待っているかのbool値を返します。 + +### `.stop()` + +実行待ち中のナビゲーションを中止します。 + +### `.reload()` + +ゲストページを再読み込みします。 + +### `.reloadIgnoringCache()` + +キャッシュを無効にして再読み込みします。 + +### `.canGoBack()` + +ページを戻ることができるかのbool値を返します。 + +### `.canGoForward()` + +ページを進むことができるかのbool値を返します。 + +### `.canGoToOffset(offset)` + +* `offset` Integer + +`offset`だけ、移動できるかのbool値を返します。 + +### `.clearHistory()` + +移動履歴をクリアします。 + +### `.goBack()` + +ページを戻ります。 + +### `.goForward()` + +ページを進みます。 + +### `.goToIndex(index)` + +* `index` Integer + +インデックスを指定して移動します。 + +### `.goToOffset(offset)` + +* `offset` Integer + +現在の場所からの移動量を指定して移動します。 + +### `.isCrashed()` + +レンダラプロセスがクラッシュしているかを返します。 + +### `.setUserAgent(userAgent)` + +* `userAgent` String + +ゲストページ用のUser agentを変更します。 + +### `.getUserAgent()` + +User agentを取得します。 + +### `.insertCSS(css)` + +* `css` String + +ゲストエージにCSSを追加します。 + +### `.executeJavaScript(code, userGesture, callback)` + +* `code` String +* `userGesture` Boolean - Default `false`. +* `callback` Function (optional) - Called after script has been executed. + * `result` + +ページ内で`code`を評価します。`userGesture`を設定した場合、ページ内でgesture contextを作成します。例えば`requestFullScreen`のようなユーザーの対応が必要なHTML APIでは、自動化時にこれが有利になる時があります。 + +### `.openDevTools()` + +DevToolsを開きます。 + +### `.closeDevTools()` + +DevToolsを閉じます。 + +### `.isDevToolsOpened()` + +DevToolsが開いているかのbool値を返します。 + +### `.isDevToolsFocused()` + +DevToolsがフォーカスを得ているかのbool値を返します。 + +### `.inspectElement(x, y)` + +* `x` Integer +* `y` Integer + +ゲストページの(`x`, `y`)の位置にある要素を調べます。 + +### `.inspectServiceWorker()` + +ゲストページのサービスワーカーのDevToolsを開きます。 + +### `.setAudioMuted(muted)` + +* `muted` Boolean + +ページをミュートするかを設定します。 + +### `.isAudioMuted()` + +ページがミュートされているかを返します。 + +### `.undo()` + +`undo` (元に戻す)を行います。 +Executes editing command `undo` in page. + +### `.redo()` + +`redo` (やり直し)を行います。 + +### `.cut()` + +`cut` (切り取り)を行います。 + +### `.copy()` + +`copy` (コピー)を行います。 + +### `.paste()` + +`paste` (貼り付け)を行います。 + +### `.pasteAndMatchStyle()` + +`pasteAndMatchStyle`(貼り付けてスタイルを合わせる)を行います。 + +### `.delete()` + +`delete` (削除)を行います。 + +### `.selectAll()` + +`selectAll` (全て選択)を行います。 + +### `.unselect()` + +`unselect` (選択を解除)を行います。 + +### `.replace(text)` + +* `text` String + +`replace` (置き換え)を行います。 + +### `.replaceMisspelling(text)` + +* `text` String + +`replaceMisspelling` (スペル違いを置き換え)を行います。 + +### `.insertText(text)` + +* `text` String + +`text`を選択された要素に挿入します。 + +### `.findInPage(text[, options])` + +* `text` String - 検索する文字列(空文字列にはできません) +* `options` Object (省略可) + * `forward` Boolean - 前方・後方のどちらを検索するかどうかです。省略時は`true`で前方に検索します。 + * `findNext` Boolean - 初回検索か、次を検索するかを選びます。省略時は`false`で、初回検索です。 + * `matchCase` Boolean - 大文字・小文字を区別するかを指定します。省略時は`false`で、区別しません。 + * `wordStart` Boolean - ワード始まりからの検索かを指定します。省略時は`false`で、語途中でもマッチします。 + * `medialCapitalAsWordStart` Boolean - `wordStart`指定時、CamelCaseの途中もワード始まりと見なすかを指定します。省略時は`false`です。 + +`text`をページ内全てから検索し、リクエストに使用するリクエストID(`Integer`)を返します。リクエストの結果は、[`found-in-page`](web-view-tag.md#event-found-in-page)イベントを介して受け取ることができます。 + +### `.stopFindInPage(action)` + +* `action` String - [`.findInPage`](web-view-tag.md#webviewtagfindinpage)リクエストを終わらせる時にとるアクションを指定します。 + * `clearSelection` - 選択をクリアします。 + * `keepSelection` - 選択を通常の選択へと変換します。 + * `activateSelection` - 選択ノードにフォーカスを当て、クリックします。 + +`action`にしたがって`webview`への`findInPage`リクエストを中止します。 + +### `.print([options])` + +`webview`で表示されているウェブページを印刷します。`webContents.print([options])`と同じです。 + +### `.printToPDF(options, callback)` + +`webview`のウェブサイトをPDFとして印刷します。`webContents.printToPDF(options, callback)`と同じです。 + +### `.send(channel[, arg1][, arg2][, ...])` + +* `channel` String +* `arg` (optional) + +`channel`を通じてレンダラプロセスに非同期メッセージを送ります。合わせて、 +任意のメッセージを送ることができます。レンダラプロセスは`ipcRenderer`モジュールを +使用して、`channel`イベントでメッセージを把握することができます。 + +サンプルが[webContents.send](web-contents.md#webcontentssendchannel-args)にあります。 + +### `.sendInputEvent(event)` + +* `event` Object + +入力イベント(`event`)をページに送ります。 + +`event`に関する詳しい説明は、[webContents.sendInputEvent](web-contents.md##webcontentssendinputeventevent)を +参照してください。 + +### `.getWebContents()` + +`webview`に関連付けられた[WebContents](web-contents.md)を取得します。 + +## DOM events + +`webview`タグで有効なイベントは次の通りです: + +### Event: 'load-commit' + +返り値: + +* `url` String +* `isMainFrame` Boolean + +読み込みが行われる時に発生するイベントです。 +これには、現在のドキュメントやサブフレームの読み込みが含まれます。ただし、非同期なリソース読み込みは含まれません。 + +### Event: 'did-finish-load' + +ナビゲーションが完了した際に発生するイベントです。 +言い換えると、タブ上の"くるくる"が止まった時に発生し、`onload`イベントが配信されます。 + +### Event: 'did-fail-load' + +返り値: + +* `errorCode` Integer +* `errorDescription` String +* `validatedURL` String +* `isMainFrame` Boolean + +`did-finish-load`と同じようですが、読み込みに失敗した時やキャンセルされた時に発生します。 +例えば、`window.stop()`が呼ばれた時などです。 + +### Event: 'did-frame-finish-load' + +返り値: + +* `isMainFrame` Boolean + +フレームがナビゲーションを終えた時に発生します。 + +### Event: 'did-start-loading' + +タブ上の"くるくる"が回転を始めた時点でこのイベントが発生します。 + +### Event: 'did-stop-loading' + +タブ上の"くるくる"が回転をやめた時点でこのイベントが発生します。 + +### Event: 'did-get-response-details' + +返り値: + +* `status` Boolean +* `newURL` String +* `originalURL` String +* `httpResponseCode` Integer +* `requestMethod` String +* `referrer` String +* `headers` Object +* `resourceType` String + +読み込むリソースの詳細がわかった時点で発生します。 +`status`は、リソースをダウンロードするソケット接続であるかを示します。 + +### Event: 'did-get-redirect-request' + +返り値: + +* `oldURL` String +* `newURL` String +* `isMainFrame` Boolean + +リソースの取得中に、リダイレクトを受け取った際に発生します。 + +### Event: 'dom-ready' + +該当フレーム内のドキュメントが読み込まれた時に発生します。 + +### Event: 'page-title-updated' + +返り値: + +* `title` String +* `explicitSet` Boolean + +ページのタイトルが設定された時に発生します。 +タイトルがurlから作られたものであれば、`explicitSet`は`false`になります。 + +### Event: 'page-favicon-updated' + +返り値: + +* `favicons` Array - URLの配列 + +ページのfavicon URLを受け取った時に発生します。 + +### Event: 'enter-html-full-screen' + +HTML APIでフルスクリーンになった際に発生します。 + +### Event: 'leave-html-full-screen' + +HTML APIでフルスクリーンでなくなった際に発生します。 + +### Event: 'console-message' + +返り値: + +* `level` Integer +* `message` String +* `line` Integer +* `sourceId` String + +ゲストウィンドウがコンソールメッセージを記録する際に発生します。 + +下記のサンプルは、埋め込まれたサイトのログを、log levelに関係なく親側に転送します。 + + +```javascript +webview.addEventListener('console-message', (e) => { + console.log('Guest page logged a message:', e.message); +}); +``` + +### Event: 'found-in-page' + +返り値: + +* `result` Object + * `requestId` Integer + * `finalUpdate` Boolean - 次のレスポンスが待っているかを示します。 + * `activeMatchOrdinal` Integer (optional) - このマッチの場所を示します。 + * `matches` Integer (optional) - マッチした数です。 + * `selectionArea` Object (optional) - 最初のマッチした場所です。 + +[`webview.findInPage`](web-view-tag.md#webviewtagfindinpage)リクエストで結果が得られた場合に発生します。 + +```javascript +webview.addEventListener('found-in-page', (e) => { + if (e.result.finalUpdate) + webview.stopFindInPage('keepSelection'); +}); + +const requestId = webview.findInPage('test'); +``` + +### Event: 'new-window' + +返り値: + +* `url` String +* `frameName` String +* `disposition` String -`default`, `foreground-tab`, `background-tab`, + `new-window`, `other`のどれかです。 +* `options` Object - 新しい`BrowserWindow`を作る際に使用されるoptionです。 + +ゲストページが新しいブラウザウィンドウを開こうとする際に発生します。 + +下記のサンプルは、新しいURLをシステムのデフォルトブラウザで開きます。 + +```javascript +const {shell} = require('electron'); + +webview.addEventListener('new-window', (e) => { + const protocol = require('url').parse(e.url).protocol; + if (protocol === 'http:' || protocol === 'https:') { + shell.openExternal(e.url); + } +}); +``` + +### Event: 'will-navigate' + +返り値: + +* `url` String + +ユーザーまたはページがナビゲーションを始めようとする際に発生します。これは、 +`window.location`が変更になる時や、ユーザーがリンクをクリックした際に発生します。 + +`.loadURL`や`.back`でプログラムによりナビゲーションが始まった場合は +このイベントは発生しません。 + +アンカーリンクのクリックや`window.location.hash`の変更といった、ページ内遷移でも、このイベントは発生しません。 +この場合は、`did-navigate-in-page`イベントを使ってください。 + +`event.preventDefault()`は使用しても__何も起こりません__。 + +### Event: 'did-navigate' + +返り値: + +* `url` String + +ナビゲーション終了時に呼ばれます。 + +アンカーリンクのクリックや`window.location.hash`の変更といった、ページ内遷移では、このイベントは発生しません。 +この場合は、`did-navigate-in-page`イベントを使ってください。 + +### Event: 'did-navigate-in-page' + +返り値: + +* `url` String + +ページ内遷移の際に発生します。 + +ページ内遷移の際は、ページURLは変更になりますが、ページ外部へのナビゲーションは発生しません。 +例として、アンカーリンクのクリック時や、DOMの`hashchange`イベントが発生した時にこれが起こります。 + +### Event: 'close' + +ゲストページそのものが、閉じられようとしている際に発生します。 + +下記のサンプルは、`webview`が閉じられる際に、`about:blank`にナビゲートします。 + +```javascript +webview.addEventListener('close', () => { + webview.src = 'about:blank'; +}); +``` + +### Event: 'ipc-message' + +返り値: + +* `channel` String +* `args` Array + +ゲストページが埋め込み元に非同期メッセージを送ってきた際に発生します。 + +`sendToHost`メソッドと、`ipc-message`イベントを利用すると、ゲストページと埋め込み元のページでデータのやり取りを簡単に行うことができます。 + +```javascript +// 埋め込み元ページ(があるページ)で +webview.addEventListener('ipc-message', (event) => { + console.log(event.channel); + // Prints "pong" +}); +webview.send('ping'); +``` + +```javascript +// ゲストページ(内)で +const {ipcRenderer} = require('electron'); +ipcRenderer.on('ping', () => { + ipcRenderer.sendToHost('pong'); +}); +``` + +### Event: 'crashed' + +プロセスがクラッシュした際に発生します。 + +### Event: 'gpu-crashed' + +GPUプロセスがクラッシュした際に発生します。 + +### Event: 'plugin-crashed' + +返り値: + +* `name` String +* `version` String + +プラグインプロセスがクラッシュした際に発生します。 + +### Event: 'destroyed' + +WebContentsが破壊された際に呼ばれます。 + +### Event: 'media-started-playing' + +メディアの再生が開始された際に呼ばれます。 + +### Event: 'media-paused' + +メディアが一時停止になるか、再生を終えた際に呼ばれます。 + +### Event: 'did-change-theme-color' + +返り値: + +* `themeColor` String + +ページのテーマカラーが変更になった際に呼ばれます。 +これは、下記のようなメタタグがある際に通常発生します: + +```html + +``` + +### Event: 'devtools-opened' + +DevToolsが開かれた際に発生します。 + +### Event: 'devtools-closed' + +DevToolsが閉じられた際に発生します。 + +### Event: 'devtools-focused' + +DevToolsにフォーカスが当たった際 / 開かれた際に発生します。 + +[blink-feature-string]: https://code.google.com/p/chromium/codesearch#chromium/src/out/Debug/gen/blink/platform/RuntimeEnabledFeatures.cpp&sq=package:chromium&type=cs&l=527 From 5ab86cc2dfc5bb550ff42b66824f95a90862041d Mon Sep 17 00:00:00 2001 From: TAKAHASHI Kyohei Date: Mon, 30 May 2016 14:02:15 +0900 Subject: [PATCH 1209/1265] :memo: trivial change in web-view-tag.md There is a mistake about the information of `stopFindInPage`. [ci skip] --- docs/api/web-view-tag.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/api/web-view-tag.md b/docs/api/web-view-tag.md index b1d3aaead1e..f99bb4fdb5a 100644 --- a/docs/api/web-view-tag.md +++ b/docs/api/web-view-tag.md @@ -171,7 +171,7 @@ page is loaded, use the `setUserAgent` method to change the user agent. If "on", the guest page will have web security disabled. -### partition +### `partition` ```html @@ -445,8 +445,8 @@ obtained by subscribing to [`found-in-page`](web-view-tag.md#event-found-in-page * `action` String - Specifies the action to take place when ending [`.findInPage`](web-view-tag.md#webviewtagfindinpage) request. - * `clearSelection` - Translate the selection into a normal selection. - * `keepSelection` - Clear the selection. + * `clearSelection` - Clear the selection. + * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webview` with the provided `action`. @@ -457,7 +457,7 @@ Prints `webview`'s web page. Same with `webContents.print([options])`. ### `.printToPDF(options, callback)` -Prints webview's web page as PDF, Same with `webContents.printToPDF(options, callback)` +Prints `webview`'s web page as PDF, Same with `webContents.printToPDF(options, callback)` ### `.send(channel[, arg1][, arg2][, ...])` @@ -628,7 +628,7 @@ webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection'); }); -const rquestId = webview.findInPage('test'); +const requestId = webview.findInPage('test'); ``` ### Event: 'new-window' From ce0d3d93abe060b5c46a55b85bc93eca1b6a9984 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 30 May 2016 15:20:53 +0900 Subject: [PATCH 1210/1265] spec: disablewebsecurity should not break preload and node integration --- spec/api-ipc-spec.js | 2 +- spec/webview-spec.js | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/spec/api-ipc-spec.js b/spec/api-ipc-spec.js index 66fa308dd62..e88815873af 100644 --- a/spec/api-ipc-spec.js +++ b/spec/api-ipc-spec.js @@ -29,7 +29,7 @@ describe('ipc module', function () { assert.equal(a.id, 1127) }) - it.only('should work when object has no prototype', function () { + it('should work when object has no prototype', function () { var a = remote.require(path.join(fixtures, 'module', 'no-prototype.js')) assert.equal(a.foo.bar, 'baz') assert.equal(a.foo.baz, false) diff --git a/spec/webview-spec.js b/spec/webview-spec.js index 7bdb3a632e0..b1fa4405ada 100644 --- a/spec/webview-spec.js +++ b/spec/webview-spec.js @@ -259,6 +259,30 @@ describe(' tag', function () { webview.src = 'data:text/html;base64,' + encoded document.body.appendChild(webview) }) + + it('does not break node integration', function (done) { + webview.addEventListener('console-message', function (e) { + assert.equal(e.message, 'function object object') + done() + }) + webview.setAttribute('nodeintegration', 'on') + webview.setAttribute('disablewebsecurity', '') + webview.src = 'file://' + fixtures + '/pages/d.html' + document.body.appendChild(webview) + }) + + it('does not break preload script', function (done) { + var listener = function (e) { + assert.equal(e.message, 'function object object') + webview.removeEventListener('console-message', listener) + done() + } + webview.addEventListener('console-message', listener) + webview.setAttribute('disablewebsecurity', '') + webview.setAttribute('preload', fixtures + '/module/preload.js') + webview.src = 'file://' + fixtures + '/pages/e.html' + document.body.appendChild(webview) + }) }) describe('partition attribute', function () { From 6755aa44f67b6dcad4937d09e14d87b38a8686e7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 30 May 2016 14:56:31 +0900 Subject: [PATCH 1211/1265] Initialize script context in DidClearWindowObject Doing it in RunScriptsAtDocumentStart would somehow result in weird results when webSecurity is off. --- atom/renderer/atom_renderer_client.cc | 12 +++++++++--- atom/renderer/atom_renderer_client.h | 1 + 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index 283930b829a..ee2dd7d54e0 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -68,6 +68,10 @@ class AtomRenderFrameObserver : public content::RenderFrameObserver { renderer_client_(renderer_client) {} // content::RenderFrameObserver: + void DidClearWindowObject() override { + renderer_client_->DidClearWindowObject(render_frame_); + } + void DidCreateScriptContext(v8::Handle context, int extension_group, int world_id) override { @@ -185,12 +189,14 @@ void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) { } } -void AtomRendererClient::RunScriptsAtDocumentStart( +void AtomRendererClient::DidClearWindowObject( content::RenderFrame* render_frame) { // Make sure every page will get a script context created. - render_frame->GetWebFrame()->executeScript( - blink::WebScriptSource("void 0")); + render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0")); +} +void AtomRendererClient::RunScriptsAtDocumentStart( + content::RenderFrame* render_frame) { // Inform the document start pharse. node::Environment* env = node_bindings_->uv_env(); if (env) { diff --git a/atom/renderer/atom_renderer_client.h b/atom/renderer/atom_renderer_client.h index 51872e5bcba..f4a548908e0 100644 --- a/atom/renderer/atom_renderer_client.h +++ b/atom/renderer/atom_renderer_client.h @@ -21,6 +21,7 @@ class AtomRendererClient : public content::ContentRendererClient { AtomRendererClient(); virtual ~AtomRendererClient(); + void DidClearWindowObject(content::RenderFrame* render_frame); void DidCreateScriptContext( v8::Handle context, content::RenderFrame* render_frame); void WillReleaseScriptContext( From 49f127860183bbc4fa9a95ceb7b2e3d08c3ec996 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 30 May 2016 20:31:00 +0900 Subject: [PATCH 1212/1265] Refactor the URLRequestFetchJob code This makes the read end and write end of the pipe have same logic, so it is more easy to maintain. --- atom/browser/net/url_request_fetch_job.cc | 93 +++++++++++------------ atom/browser/net/url_request_fetch_job.h | 25 +++--- spec/api-protocol-spec.js | 2 +- 3 files changed, 61 insertions(+), 59 deletions(-) diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index 388b9f9550b..0f293c22fcf 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -77,7 +77,8 @@ class ResponsePiper : public net::URLFetcherResponseWriter { URLRequestFetchJob::URLRequestFetchJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker(request, network_delegate), - pending_buffer_size_(0) { + pending_buffer_size_(0), + write_num_bytes_(0) { } void URLRequestFetchJob::BeforeStartInUI( @@ -169,22 +170,21 @@ void URLRequestFetchJob::HeadersCompleted() { int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { - // Store the data in a drainable IO buffer if pending_buffer_ is empty, i.e. - // there's no ReadRawData() operation waiting for IO completion. + // When pending_buffer_ is empty, there's no ReadRawData() operation waiting + // for IO completion, we have to save the parameters until the request is + // ready to read data. if (!pending_buffer_.get()) { - response_piper_callback_ = callback; - drainable_buffer_ = new net::DrainableIOBuffer(buffer, num_bytes); + write_buffer_ = buffer; + write_num_bytes_ = num_bytes; + write_callback_ = callback; return net::ERR_IO_PENDING; } - // pending_buffer_ is set to the IOBuffer instance provided to ReadRawData() - // by URLRequestJob. - int bytes_read = std::min(num_bytes, pending_buffer_size_); - memcpy(pending_buffer_->data(), buffer->data(), bytes_read); - - ClearPendingBuffer(); - + // Write data to the pending buffer and clear them after the writing. + int bytes_read = BufferCopy(buffer, num_bytes, + pending_buffer_.get(), pending_buffer_size_); ReadRawDataComplete(bytes_read); + ClearPendingBuffer(); return bytes_read; } @@ -193,46 +193,26 @@ void URLRequestFetchJob::Kill() { fetcher_.reset(); } -void URLRequestFetchJob::StartReading() { - if (drainable_buffer_.get()) { - auto num_bytes = drainable_buffer_->BytesRemaining(); - if (num_bytes <= 0 && !response_piper_callback_.is_null()) { - int size = drainable_buffer_->BytesConsumed(); - drainable_buffer_ = nullptr; - response_piper_callback_.Run(size); - response_piper_callback_.Reset(); - return; - } - - int bytes_read = std::min(num_bytes, pending_buffer_size_); - memcpy(pending_buffer_->data(), drainable_buffer_->data(), bytes_read); - - drainable_buffer_->DidConsume(bytes_read); - - ClearPendingBuffer(); - - ReadRawDataComplete(bytes_read); - } -} - -void URLRequestFetchJob::ClearPendingBuffer() { - // Clear the buffers before notifying the read is complete, so that it is - // safe for the observer to read. - pending_buffer_ = nullptr; - pending_buffer_size_ = 0; -} - int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); return net::OK; } - pending_buffer_ = dest; - pending_buffer_size_ = dest_size; - // Read from drainable_buffer_ if available, i.e. response data became - // available before ReadRawData was called. - StartReading(); - return net::ERR_IO_PENDING; + + // When write_buffer_ is empty, there is no data valable yet, we have to save + // the dest buffer util DataAvailable. + if (!write_buffer_.get()) { + pending_buffer_ = dest; + pending_buffer_size_ = dest_size; + return net::ERR_IO_PENDING; + } + + // Read from the write buffer and clear them after reading. + int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, + dest, dest_size); + write_callback_.Run(bytes_read); + ClearWriteBuffer(); + return bytes_read; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { @@ -264,6 +244,7 @@ void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { } ClearPendingBuffer(); + ClearWriteBuffer(); if (fetcher_->GetStatus().is_success()) ReadRawDataComplete(0); @@ -271,4 +252,22 @@ void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { NotifyStartError(fetcher_->GetStatus()); } +int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes, + net::IOBuffer* target, int target_size) { + int bytes_written = std::min(num_bytes, target_size); + memcpy(target->data(), source->data(), bytes_written); + return bytes_written; +} + +void URLRequestFetchJob::ClearPendingBuffer() { + pending_buffer_ = nullptr; + pending_buffer_size_ = 0; +} + +void URLRequestFetchJob::ClearWriteBuffer() { + write_buffer_ = nullptr; + write_num_bytes_ = 0; + write_callback_.Reset(); +} + } // namespace atom diff --git a/atom/browser/net/url_request_fetch_job.h b/atom/browser/net/url_request_fetch_job.h index da1c1678e58..906ba68d396 100644 --- a/atom/browser/net/url_request_fetch_job.h +++ b/atom/browser/net/url_request_fetch_job.h @@ -9,14 +9,10 @@ #include "atom/browser/net/js_asker.h" #include "browser/url_request_context_getter.h" -#include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_fetcher_delegate.h" -#include "net/url_request/url_request_job.h" namespace atom { -class AtomBrowserContext; - class URLRequestFetchJob : public JsAsker, public net::URLFetcherDelegate, public brightray::URLRequestContextGetter::Delegate { @@ -30,9 +26,6 @@ class URLRequestFetchJob : public JsAsker, const net::CompletionCallback& callback); protected: - void StartReading(); - void ClearPendingBuffer(); - // JsAsker: void BeforeStartInUI(v8::Isolate*, v8::Local) override; void StartAsync(std::unique_ptr options) override; @@ -48,13 +41,23 @@ class URLRequestFetchJob : public JsAsker, void OnURLFetchComplete(const net::URLFetcher* source) override; private: + int BufferCopy(net::IOBuffer* source, int num_bytes, + net::IOBuffer* target, int target_size); + void ClearPendingBuffer(); + void ClearWriteBuffer(); + scoped_refptr url_request_context_getter_; std::unique_ptr fetcher_; - scoped_refptr pending_buffer_; - scoped_refptr drainable_buffer_; - int pending_buffer_size_; std::unique_ptr response_info_; - net::CompletionCallback response_piper_callback_; + + // Saved arguments passed to ReadRawData. + scoped_refptr pending_buffer_; + int pending_buffer_size_; + + // Saved arguments passed to DataAvailable. + scoped_refptr write_buffer_; + int write_num_bytes_; + net::CompletionCallback write_callback_; DISALLOW_COPY_AND_ASSIGN(URLRequestFetchJob); }; diff --git a/spec/api-protocol-spec.js b/spec/api-protocol-spec.js index 1b46d586a41..80351191710 100644 --- a/spec/api-protocol-spec.js +++ b/spec/api-protocol-spec.js @@ -511,7 +511,7 @@ describe('protocol module', function () { }) }) - it('loads resource for webContents', function (done) { + it('works when target URL redirects', function (done) { var contents = null var server = http.createServer(function (req, res) { if (req.url == '/serverRedirect') { From f02143b8f2dbd125e40c13aa537c6a6a639299e7 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Mon, 30 May 2016 22:31:38 +0900 Subject: [PATCH 1213/1265] Clear the buffers before notifying the other end of the pipe --- atom/browser/net/url_request_fetch_job.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index 0f293c22fcf..8279d09d5da 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -183,8 +183,8 @@ int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, // Write data to the pending buffer and clear them after the writing. int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(), pending_buffer_size_); - ReadRawDataComplete(bytes_read); ClearPendingBuffer(); + ReadRawDataComplete(bytes_read); return bytes_read; } @@ -210,8 +210,9 @@ int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { // Read from the write buffer and clear them after reading. int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size); - write_callback_.Run(bytes_read); + net::CompletionCallback write_callback = write_callback_; ClearWriteBuffer(); + write_callback.Run(bytes_read); return bytes_read; } From 381da769671baf10008532c6dfb0cbda8fbddee5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 31 May 2016 10:19:13 +0900 Subject: [PATCH 1214/1265] Correctly redirect output to console --- atom/app/atom_main.cc | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/atom/app/atom_main.cc b/atom/app/atom_main.cc index 03055e04daf..1e69ba4ba83 100644 --- a/atom/app/atom_main.cc +++ b/atom/app/atom_main.cc @@ -15,6 +15,7 @@ #include "atom/app/atom_main_delegate.h" #include "atom/common/crash_reporter/win/crash_service_main.h" #include "base/environment.h" +#include "base/process/launch.h" #include "base/win/windows_version.h" #include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" @@ -46,10 +47,6 @@ bool IsEnvSet(const char* name) { #endif } -bool IsRunAsNode() { - return IsEnvSet(kRunAsNode); -} - } // namespace #if defined(OS_WIN) @@ -57,14 +54,11 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { int argc = 0; wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - // Make output work in console if we are not in cygiwn. - if (!IsEnvSet("TERM") && !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE")) { - AttachConsole(ATTACH_PARENT_PROCESS); + bool run_as_node = IsEnvSet(kRunAsNode); - FILE* dontcare; - freopen_s(&dontcare, "CON", "w", stdout); - freopen_s(&dontcare, "CON", "w", stderr); - } + // Make sure the output is printed to console. + if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE")) + base::RouteStdioToConsole(false); // Convert argv to to UTF8 char** argv = new char*[argc]; @@ -100,7 +94,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { } } - if (IsRunAsNode()) { + if (run_as_node) { // Now that argv conversion is done, we can finally start. base::AtExitManager atexit_manager; base::i18n::InitializeICU(); @@ -123,7 +117,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { #elif defined(OS_LINUX) // defined(OS_WIN) int main(int argc, const char* argv[]) { - if (IsRunAsNode()) { + if (IsEnvSet(kRunAsNode)) { base::i18n::InitializeICU(); base::AtExitManager atexit_manager; return atom::NodeMain(argc, const_cast(argv)); @@ -140,7 +134,7 @@ int main(int argc, const char* argv[]) { #else // defined(OS_LINUX) int main(int argc, const char* argv[]) { - if (IsRunAsNode()) { + if (IsEnvSet(kRunAsNode)) { return AtomInitializeICUandStartNode(argc, const_cast(argv)); } From 4d8994df921087653c2e134e39a1da16a957bf39 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 31 May 2016 10:26:19 +0900 Subject: [PATCH 1215/1265] spec: child_process.fork shouble be able to pipe stdio --- spec/fixtures/module/process-stdout.js | 1 + spec/node-spec.js | 13 +++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 spec/fixtures/module/process-stdout.js diff --git a/spec/fixtures/module/process-stdout.js b/spec/fixtures/module/process-stdout.js new file mode 100644 index 00000000000..953750a247f --- /dev/null +++ b/spec/fixtures/module/process-stdout.js @@ -0,0 +1 @@ +process.stdout.write('pipes stdio') diff --git a/spec/node-spec.js b/spec/node-spec.js index 71fdbac9866..93a247ef4ff 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -76,6 +76,19 @@ describe('node feature', function () { }) child.send('message') }) + + it('pipes stdio', function (done) { + let child = child_process.fork(path.join(fixtures, 'module', 'process-stdout.js'), {silent: true}) + let data = '' + child.stdout.on('data', (chunk) => { + data += String(chunk) + }) + child.on('exit', (code) => { + assert.equal(code, 0) + assert.equal(data, 'pipes stdio') + done() + }) + }) }) }) From 31f2ac8bf368fcbd24b1de1df9f7c12e50ab777f Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 31 May 2016 16:14:40 +0900 Subject: [PATCH 1216/1265] :memo: Update `README.md` [ci skip] --- README-ko.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README-ko.md b/README-ko.md index bb7684e9d53..7cabe5ed456 100644 --- a/README-ko.md +++ b/README-ko.md @@ -7,19 +7,18 @@ ### [Electron](https://github.com/electron/electron/) 한국어 참조 문서 -:zap: *이전까지 Atom Shell로 불렸지만, Electron으로 변경되었습니다* :zap: - Electron 프레임워크는 JavaScript, HTML 그리고 CSS를 사용하여 Cross-Platform 데스크톱 어플리케이션을 개발할 수 있도록 해주는 프레임워크입니다. [Node.js](https://nodejs.org/)와 [Chromium](http://www.chromium.org)을 기반으로 만들어졌으며 [Atom Editor](https://github.com/atom/atom)에 사용되고 있습니다. +더 많은 어플리케이션은 [이곳](http://electron.atom.io/apps)에서 확인하세요. Electron에 대한 중요한 알림을 받고 싶다면 Twitter에서 [@ElectronJS](https://twitter.com/electronjs)를 팔로우 하세요. 이 프로젝트는 기여자 규약인 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이 프로젝트의 개발에 참여하려면 이 규약을 지켜야 합니다. 받아들일 수 없는 행위를 발견했을 -경우 atom@github.com로 보고하세요. +경우 electron@github.com로 보고하세요. ## 다운로드 From a454cc82609d2cfdaa82368f752534f9db9f7c14 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Tue, 31 May 2016 16:14:56 +0900 Subject: [PATCH 1217/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/app.md | 13 ++- docs-translations/ko-KR/api/browser-window.md | 5 +- docs-translations/ko-KR/api/process.md | 109 +++++++++++++++--- docs-translations/ko-KR/api/web-view-tag.md | 12 +- .../development/build-instructions-linux.md | 4 +- .../source-code-directory-structure.md | 4 +- .../tutorial/application-distribution.md | 26 ++--- .../ko-KR/tutorial/application-packaging.md | 2 +- .../ko-KR/tutorial/devtools-extension.md | 2 +- 9 files changed, 130 insertions(+), 47 deletions(-) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index a33cc634bfa..4150b4d69a9 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -370,7 +370,7 @@ npm 모듈 규칙에 따라 대부분의 경우 `package.json`의 `name` 필드 **참고:** 패키징된 앱을 배포할 때, `locales` 폴더도 같이 배포해야 합니다. -**참고:** Windows에선 `ready` 이벤트가 발생한 이후에 이 메서드를 사용해야 합니다. +**참고:** Windows에선 `ready` 이벤트가 발생한 이후에 이 메서드를 호출해야 합니다. ### `app.addRecentDocument(path)` _OS X_ _Windows_ @@ -445,9 +445,7 @@ Windows에서 사용할 수 있는 JumpList의 [Tasks][tasks] 카테고리에 `t 아이콘을 가지고 있을 경우, 사용할 아이콘의 인덱스를 이 옵션으로 지정해 주어야 합니다. 단, 아이콘을 하나만 포함하고 있는 경우 0을 지정하면 됩니다. -### `app.allowNTLMCredentialsForAllDomains(allow)` - -* `allow` Boolean +### `app.allowNTLMCredentialsForAllDomains()` 항상 동적으로 HTTP NTLM 또는 Negotiate 인증에 자격 증명을 보낼 것인지 설정합니다. @@ -455,6 +453,8 @@ Windows에서 사용할 수 있는 JumpList의 [Tasks][tasks] 카테고리에 `t 보냅니다. (같은 도메인 내에서) 그러나 기업 네트워크가 잘못 구성된 경우 종종 작업에 실패할 수 있습니다. 이때 이 메서드를 통해 모든 URL을 허용할 수 있습니다. +**참고:** 이 메서드는 `ready` 이벤트가 발생하기 전에 호출해야 합니다. + ### `app.makeSingleInstance(callback)` * `callback` Function @@ -508,6 +508,11 @@ app.on('ready', () => { }); ``` +### `app.releaseSingleInstance()` + +모든 `makeSingleInstance`에 의해 생성된 제한을 해제합니다. 이 메서드는 다시 여러 +인스턴스의 어플리케이션이 나란히 실행될 수 있도록 합니다. + ### `app.setUserActivity(type, userInfo[, webpageURL])` _OS X_ * `type` String - 고유하게 activity를 식별합니다. diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index f8515c3b9ee..dfebf541fa8 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -63,8 +63,9 @@ win.show(); * `fullscreen` Boolean - 윈도우의 전체화면 활성화 여부. 이 속성을 명시적으로 `false`로 지정했을 경우, OS X에선 전체화면 버튼이 숨겨지거나 비활성됩니다. 기본값은 `false` 입니다. -* `fullscreenable` Boolean - OS X의 최대화/줌 버튼이 전체화면 모드 또는 윈도우 - 최대화를 토글할 수 있게 할지 여부입니다. 기본값은 `true` 입니다. +* `fullscreenable` Boolean - 윈도우가 전체화면 모드로 전환될 수 있는지 여부입니다. + 또한 OS X에선, 최대화/줌 버튼이 전체화면 모드 또는 윈도우 최대화를 실행할지 여부도 + 포함됩니다. 기본값은 `true`입니다. * `skipTaskbar` Boolean - 작업표시줄 어플리케이션 아이콘 표시 스킵 여부. 기본값은 `false`입니다. * `kiosk` Boolean - Kiosk(키오스크) 모드. 기본값은 `false`입니다. diff --git a/docs-translations/ko-KR/api/process.md b/docs-translations/ko-KR/api/process.md index f605521c404..946dd92eac5 100644 --- a/docs-translations/ko-KR/api/process.md +++ b/docs-translations/ko-KR/api/process.md @@ -1,21 +1,8 @@ -# process +# process -> 현재 작동중인 어플리케이션의 정보를 가져옵니다. +> process 객체에 대한 확장 기능. -Electron의 `process` 객체는 기존의 node와는 달리 약간의 차이점이 있습니다: - -* `process.type` String - 프로세스의 타입, `browser` (메인 프로세스) 또는 - `renderer`가 됩니다. -* `process.versions.electron` String - Electron의 버전. -* `process.versions.chrome` String - Chromium의 버전. -* `process.resourcesPath` String - JavaScript 소스 코드의 경로. -* `process.mas` Boolean - Mac 앱 스토어용 빌드일 때 `true`로 지정됩니다. 다른 - 빌드일 땐 `undefined`로 지정됩니다. -* `process.windowsStore` Boolean - 만약 앱이 Windows Store 앱 (appx)으로 작동하고 - 있다면, 이 값이 `true`로 지정되며 다른 빌드인 경우엔 `undefined`로 지정됩니다. -* `process.defaultApp` Boolean - 어플리케이션이 기본 어플리케이션 형식으로 전달되는 - 인수와 함께 실행됐을 때, 메인 프로세스에서 이 값이 `true`가 되며 다른 경우엔 - `undefined`가 됩니다. +`process` 객체는 Electron에서 약간 추가적인 기능이 있으며 API는 다음과 같습니다: ## Events @@ -41,6 +28,96 @@ process.once('loaded', () => { ### `process.noAsar` +Setting this to `true` can disable the support for `asar` archives in Node's +built-in modules. + +### `process.type` + +Current process's type, can be `"browser"` (i.e. main process) or `"renderer"`. + +### `process.versions.electron` + +Electron's version string. + +### `process.versions.chrome` + +Chrome's version string. + +### `process.resourcesPath` + +Path to the resources directory. + +### `process.mas` + +For Mac App Store build, this property is `true`, for other builds it is +`undefined`. + +### `process.windowsStore` + +If the app is running as a Windows Store app (appx), this property is `true`, +for otherwise it is `undefined`. + +### `process.defaultApp` + +When app is started by being passed as parameter to the default app, this +property is `true` in the main process, otherwise it is `undefined`. + +## Methods + +The `process` object has the following method: + +### `process.crash()` + +Causes the main thread of the current process crash. + +### `process.hang()` + +Causes the main thread of the current process hang. + +### `process.setFdLimit(maxDescriptors)` _OS X_ _Linux_ + +* `maxDescriptors` Integer + +Sets the file descriptor soft limit to `maxDescriptors` or the OS hard +limit, whichever is lower for the current process. + +### `process.getProcessMemoryInfo()` + +Returns an object giving memory usage statistics about the current process. Note +that all statistics are reported in Kilobytes. + +* `workingSetSize` - The amount of memory currently pinned to actual physical + RAM. +* `peakWorkingSetSize` - The maximum amount of memory that has ever been pinned + to actual physical RAM. +* `privateBytes` - The amount of memory not shared by other processes, such as + JS heap or HTML content. +* `sharedBytes` - The amount of memory shared between processes, typically + memory consumed by the Electron code itself + +### `process.getSystemMemoryInfo()` + +Returns an object giving memory usage statistics about the entire system. Note +that all statistics are reported in Kilobytes. + +* `total` - The total amount of physical memory in Kilobytes available to the + system. +* `free` - The total amount of memory not being used by applications or disk + cache. + +On Windows / Linux: + +* `swapTotal` - The total amount of swap memory in Kilobytes available to the + system. +* `swapFree` - The free amount of swap memory in Kilobytes available to the + system. + +---------------------------------------- + +## Properties + +### `process.noAsar` + 이 속성을 `true`로 지정하면 Node 빌트인 모듈의 `asar` 아카이브 지원을 비활성화 시킬 수 있습니다. diff --git a/docs-translations/ko-KR/api/web-view-tag.md b/docs-translations/ko-KR/api/web-view-tag.md index 7adbe5cbd18..71032fcb573 100644 --- a/docs-translations/ko-KR/api/web-view-tag.md +++ b/docs-translations/ko-KR/api/web-view-tag.md @@ -433,19 +433,19 @@ Service worker에 대한 개발자 도구를 엽니다. * `action` String - [`.findInPage`](web-view-tag.md#webviewtagfindinpage) 요청이 종료되었을 때 일어날 수 있는 작업을 지정합니다. - * `clearSelection` - 선택을 일반 선택으로 변경합니다. - * `keepSelection` - 선택을 취소합니다. + * `clearSelection` - 선택을 취소합니다. + * `keepSelection` - 선택을 일반 선택으로 변경합니다. * `activateSelection` - 포커스한 후 선택된 노드를 클릭합니다. 제공된 `action`에 대한 `webContents`의 모든 `findInPage` 요청을 중지합니다. ### `.print([options])` -Webview 페이지를 인쇄합니다. `webContents.print([options])` 메서드와 같습니다. +`webview` 페이지를 인쇄합니다. `webContents.print([options])` 메서드와 같습니다. ### `.printToPDF(options, callback)` -Webview 페이지를 PDF 형식으로 인쇄합니다. +`webview` 페이지를 PDF 형식으로 인쇄합니다. `webContents.printToPDF(options, callback)` 메서드와 같습니다. ### `.send(channel[, arg1][, arg2][, ...])` @@ -463,7 +463,7 @@ Webview 페이지를 PDF 형식으로 인쇄합니다. * `event` Object -페이지에 input `event`를 보냅니다. +페이지에 입력 `event`를 보냅니다. `event` 객체에 대해 자세히 알아보려면 [webContents.sendInputEvent](web-contents.md##webcontentssendinputeventevent)를 참고하세요. @@ -617,7 +617,7 @@ webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection'); }); -const rquestId = webview.findInPage('test'); +const requestId = webview.findInPage('test'); ``` ### Event: 'new-window' diff --git a/docs-translations/ko-KR/development/build-instructions-linux.md b/docs-translations/ko-KR/development/build-instructions-linux.md index 3cd410a4bbf..3fe755313eb 100644 --- a/docs-translations/ko-KR/development/build-instructions-linux.md +++ b/docs-translations/ko-KR/development/build-instructions-linux.md @@ -8,7 +8,7 @@ * Python 2.7.x. 몇몇 CentOS와 같은 배포판들은 아직도 Python 2.6.x 버전을 사용합니다. 그래서 먼저 `python -V`를 통해 버전을 확인할 필요가 있습니다. * Node.js v0.12.x. Node를 설치하는 방법은 여러 가지가 있습니다. 먼저, - [Node.js](http://nodejs.org) 사이트에서 소스코드를 받아 빌드하는 방법입니다. + [Node.js](http://nodejs.org) 사이트에서 소스 코드를 받아 빌드하는 방법입니다. 이렇게 하면 Node를 일반 유저로 홈 디렉터리에 설치할 수 있습니다. 다른 방법으로는 [NodeSource](https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories)에서 소스 파일을 받아와 설치할 수 있습니다. 자세한 내용은 [Node.js 설치 방법](https://github.com/joyent/node/wiki/Installation)을 @@ -34,7 +34,7 @@ $ sudo yum install clang dbus-devel gtk2-devel libnotify-devel libgnome-keyring- ``` 다른 배포판의 경우 pacman 같은 패키지 매니저를 통해 패키지를 설치 할 수 있습니다. -패키지의 이름은 대부분 위 예시와 비슷할 것입니다. 또는 소스코드를 내려받아 +패키지의 이름은 대부분 위 예시와 비슷할 것입니다. 또는 소스 코드를 내려받아 직접 빌드하는 방법도 있습니다. ## 코드 가져오기 diff --git a/docs-translations/ko-KR/development/source-code-directory-structure.md b/docs-translations/ko-KR/development/source-code-directory-structure.md index 003eca59683..860072ac8ad 100644 --- a/docs-translations/ko-KR/development/source-code-directory-structure.md +++ b/docs-translations/ko-KR/development/source-code-directory-structure.md @@ -27,7 +27,7 @@ Electron | └── common - 메인과 렌더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 | 함수들이 포함되어 있고 node의 메시지 루프와 Chromium의 메시지 루프를 통합. | └── api - 공통 API 구현들, 기초 Electron 빌트-인 모듈들. -├── chromium_src - Chromium에서 복사하여 가져온 소스코드. +├── chromium_src - Chromium에서 복사하여 가져온 소스 코드. ├── default_app - Electron에 앱이 제공되지 않았을 때 보여지는 기본 페이지. ├── docs - 참조 문서. ├── lib - JavaScript 소스 코드. @@ -48,7 +48,7 @@ Electron * **script** - 개발목적으로 사용되는 빌드, 패키징, 테스트, 기타등을 실행하는 스크립트. * **tools** - gyp 파일에서 사용되는 헬퍼 스크립트 `script`와는 다르게 유저로부터 직접 실행되지 않는 스크립트들을 이곳에 넣습니다. -* **vendor** - 소스코드의 서드파티 종속성 코드 소스 코드 디렉터리가 겹쳐 혼란을 일으킬 +* **vendor** - 소스 코드의 서드파티 종속성 코드 소스 코드 디렉터리가 겹쳐 혼란을 일으킬 수 있기 때문에 `third_party`와 같은 Chromium 소스 코드 디렉터리에서 사용된 폴더 이름은 사용하지 않았습니다. * **node_modules** - 빌드에 사용되는 node 서드파티 모듈. diff --git a/docs-translations/ko-KR/tutorial/application-distribution.md b/docs-translations/ko-KR/tutorial/application-distribution.md index 445a9dda21d..501de4da93f 100644 --- a/docs-translations/ko-KR/tutorial/application-distribution.md +++ b/docs-translations/ko-KR/tutorial/application-distribution.md @@ -31,7 +31,7 @@ electron/resources/app ## asar로 앱 패키징 하기 소스파일 전체를 복사해서 배포하는 것과는 별개로 [asar](https://github.com/electron/asar) -아카이브를 통해 어플리케이션의 소스코드가 사용자에게 노출되는 것을 방지할 수 있습니다. +아카이브를 통해 어플리케이션의 소스 코드가 사용자에게 노출되는 것을 방지할 수 있습니다. `asar` 아카이브를 사용할 땐 단순히 `app` 폴더 대신에 어플리케이션을 패키징한 `app.asar` 파일로 대체하면됩니다. Electron은 자동으로 `app`폴더 대신 asar 아카이브를 @@ -105,9 +105,17 @@ MyApp.app/Contents 아이콘은 [.desktop](https://developer.gnome.org/integration-guide/stable/desktop-files.html.en) 파일을 사용하여 지정할 수 있습니다. -## Electron 소스코드를 다시 빌드하여 리소스 수정하기 +## 패키징 툴 -또한 Electron 소스코드를 다시 빌드할 때 어플리케이션 이름을 변경할 수 있습니다. +어플리케이션을 일일이 수동으로 패키지로 만드는 대신, 서드 파티 패키징 툴을 사용하며 +이러한 작업을 자동화 시킬 수 있습니다: + +* [electron-packager](https://github.com/maxogden/electron-packager) +* [electron-builder](https://github.com/loopline-systems/electron-builder) + +## Electron 소스 코드를 다시 빌드하여 리소스 수정하기 + +또한 Electron 소스 코드를 다시 빌드할 때 어플리케이션 이름을 변경할 수 있습니다. `GYP_DEFINES` 환경변수를 사용하여 다음과 같이 다시 빌드할 수 있습니다: @@ -131,17 +139,9 @@ $ script/build.py -c Release -t myapp ### grunt-build-atom-shell -Electron의 소스코드를 수정하고 다시 빌드하는 작업은 상당히 복잡합니다. 일일이 -소스코드를 수정하는 대신 [grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell)을 +Electron의 소스 코드를 수정하고 다시 빌드하는 작업은 상당히 복잡합니다. 일일이 +소스 코드를 수정하는 대신 [grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell)을 사용하여 빌드를 자동화 시킬 수 있습니다. 이 툴을 사용하면 자동으로 `.gyp`파일을 수정하고 다시 빌드합니다. 그리고 어플리케이션의 네이티브 Node 모듈 또한 새로운 실행파일 이름으로 일치시킵니다. - -## 패키징 툴 - -어플리케이션을 일일이 수동으로 패키지로 만드는 대신, 서드 파티 패키징 툴을 사용하며 -이러한 작업을 자동화 시킬 수 있습니다: - -* [electron-packager](https://github.com/maxogden/electron-packager) -* [electron-builder](https://github.com/loopline-systems/electron-builder) diff --git a/docs-translations/ko-KR/tutorial/application-packaging.md b/docs-translations/ko-KR/tutorial/application-packaging.md index 8002350b56b..6dd52b34ef8 100644 --- a/docs-translations/ko-KR/tutorial/application-packaging.md +++ b/docs-translations/ko-KR/tutorial/application-packaging.md @@ -1,7 +1,7 @@ # 어플리케이션 패키징 Windows에서 일어나는 긴 경로 이름에 대한 [issues](https://github.com/joyent/node/issues/6960)를 -완화하고 `require` 속도를 약간 빠르게 하며 어플리케이션의 리소스와 소스코드를 좋지 않은 +완화하고 `require` 속도를 약간 빠르게 하며 어플리케이션의 리소스와 소스 코드를 좋지 않은 사용자로부터 보호하기 위해 어플리케이션을 [asar][asar] 아카이브로 패키징 할 수 있습니다. ## `asar` 아카이브 생성 diff --git a/docs-translations/ko-KR/tutorial/devtools-extension.md b/docs-translations/ko-KR/tutorial/devtools-extension.md index 07281620ec7..b9aa2edd946 100644 --- a/docs-translations/ko-KR/tutorial/devtools-extension.md +++ b/docs-translations/ko-KR/tutorial/devtools-extension.md @@ -13,7 +13,7 @@ 다음 예시는 [React DevTools Extension](https://github.com/facebook/react-devtools)을 사용합니다. -먼저 소스코드를 다운로드 받습니다: +먼저 소스 코드를 다운로드 받습니다: ```bash $ cd /some-directory From aea2135016a45c90b28d5e1c89fdd46787d328de Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Tue, 31 May 2016 17:47:45 +0900 Subject: [PATCH 1218/1265] Keep copies of window icons --- atom/browser/native_window_views.cc | 10 +++++++--- atom/browser/native_window_views.h | 5 +++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 21bff6388a6..e699892d4ac 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -786,12 +786,16 @@ gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() { } #if defined(OS_WIN) -void NativeWindowViews::SetIcon(HICON small_icon, HICON app_icon) { +void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { + // We are responsible for storing the images. + window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); + app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); + HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, - reinterpret_cast(small_icon)); + reinterpret_cast(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, - reinterpret_cast(app_icon)); + reinterpret_cast(app_icon_.get())); } #elif defined(USE_X11) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { diff --git a/atom/browser/native_window_views.h b/atom/browser/native_window_views.h index 85c7ddbeba7..909c5b6fd4b 100644 --- a/atom/browser/native_window_views.h +++ b/atom/browser/native_window_views.h @@ -17,6 +17,7 @@ #if defined(OS_WIN) #include "atom/browser/ui/win/message_handler_delegate.h" #include "atom/browser/ui/win/taskbar_host.h" +#include "base/win/scoped_gdi_object.h" #endif namespace views { @@ -205,6 +206,10 @@ class NativeWindowViews : public NativeWindow, // If true we have enabled a11y bool enabled_a11y_support_; + + // The icons of window and taskbar. + base::win::ScopedHICON window_icon_; + base::win::ScopedHICON app_icon_; #endif // Handles unhandled keyboard messages coming back from the renderer process. From fc6628d159395731832cf58c5adb61108923bcea Mon Sep 17 00:00:00 2001 From: Vasu Mahesh Date: Tue, 31 May 2016 22:29:07 +0530 Subject: [PATCH 1219/1265] Add: custom pageSize for printToPDF --- docs/api/web-contents.md | 2 +- lib/browser/api/web-contents.js | 28 ++++++++++++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index d0716305ab9..89d7e1245d7 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -655,7 +655,7 @@ size. * `marginsType` Integer - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. * `pageSize` String - Specify page size of the generated PDF. Can be `A3`, - `A4`, `A5`, `Legal`, `Letter` and `Tabloid`. + `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` & `width` in Microns. * `printBackground` Boolean - Whether to print CSS backgrounds. * `printSelectionOnly` Boolean - Whether to print selection only. * `landscape` Boolean - `true` for landscape, `false` for portrait. diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 0f79a185ffc..00057e16e8b 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -197,11 +197,31 @@ let wrapWebContents = function (webContents) { if (options.printBackground) { printingSetting.shouldPrintBackgrounds = options.printBackground } - if (options.pageSize && PDFPageSize[options.pageSize]) { - printingSetting.mediaSize = PDFPageSize[options.pageSize] - } else { - printingSetting.mediaSize = PDFPageSize['A4'] + + if (options.pageSize) { + let height = 0 + let width = 0 + if (typeof options.pageSize === 'object') { + // Dimensions in Microns + // 1 meter = 10^6 microns + height = options.pageSize.height ? options.pageSize.height : 0 + width = options.pageSize.width ? options.pageSize.width : 0 + } + + if (height > 0 && width > 0) { + printingSetting.mediaSize = { + height_microns: height, + name: 'CUSTOM', + width_microns: width, + custom_display_name: 'Custom' + } + } else if (PDFPageSize[options.pageSize]) { + printingSetting.mediaSize = PDFPageSize[options.pageSize] + } else { + printingSetting.mediaSize = PDFPageSize['A4'] + } } + return this._printToPDF(printingSetting, callback) } } From 606fc1a5b7b66cd23b489b8ecd7097ed3d0b46a4 Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 31 May 2016 16:48:03 -0700 Subject: [PATCH 1220/1265] Add plist path variables --- .../mac-app-store-submission-guide.md | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/tutorial/mac-app-store-submission-guide.md b/docs/tutorial/mac-app-store-submission-guide.md index c6ae061bd76..d240cc13371 100644 --- a/docs/tutorial/mac-app-store-submission-guide.md +++ b/docs/tutorial/mac-app-store-submission-guide.md @@ -94,21 +94,24 @@ RESULT_PATH="~/Desktop/$APP.pkg" # The name of certificates you requested. APP_KEY="3rd Party Mac Developer Application: Company Name (APPIDENTITY)" INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)" +# The path of your plist files. +CHILD_PLIST="/path/to/child.plist" +PARENT_PLIST="/path/to/parent.plist" FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$APP_PATH/Contents/MacOS/$APP" -codesign -s "$APP_KEY" -f --entitlements parent.plist "$APP_PATH" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$APP_PATH/Contents/MacOS/$APP" +codesign -s "$APP_KEY" -f --entitlements "$PARENT_PLIST" "$APP_PATH" productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH" ``` From 2aa1aedd92c58106ecbeddb31c4aeaabdfe9044c Mon Sep 17 00:00:00 2001 From: Garen Torikian Date: Tue, 31 May 2016 17:51:09 -0700 Subject: [PATCH 1221/1265] Fix typo --- docs/tutorial/electron-versioning.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/electron-versioning.md b/docs/tutorial/electron-versioning.md index 10e9679b0bd..bf442041c2c 100644 --- a/docs/tutorial/electron-versioning.md +++ b/docs/tutorial/electron-versioning.md @@ -4,7 +4,7 @@ If you are a seasoned Node developer, you are surely aware of `semver` - and might be used to giving your dependency management systems only rough guidelines rather than fixed version numbers. Due to the hard dependency on Node and Chromium, Electron is in a slightly more difficult position and does not follow -semver. You should therefor always reference a specific version of Electron. +semver. You should therefore always reference a specific version of Electron. Version numbers are bumped using the following rules: From d10552413578e24c4d4087268a3712767235761f Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 10:42:24 +0900 Subject: [PATCH 1222/1265] Cleanup the JavaScript code of session --- lib/browser/api/session.js | 19 ++++++++++++------- lib/browser/api/web-contents.js | 7 ------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/lib/browser/api/session.js b/lib/browser/api/session.js index 9c42f364560..49b169bd3ac 100644 --- a/lib/browser/api/session.js +++ b/lib/browser/api/session.js @@ -1,14 +1,12 @@ +const {EventEmitter} = require('events') const bindings = process.atomBinding('session') + const PERSIST_PREFIX = 'persist:' // Returns the Session from |partition| string. -exports.fromPartition = function (partition) { - if (partition == null) { - partition = '' - } - if (partition === '') { - return exports.defaultSession - } +exports.fromPartition = function (partition = '') { + if (partition === '') return exports.defaultSession + if (partition.startsWith(PERSIST_PREFIX)) { return bindings.fromPartition(partition.substr(PERSIST_PREFIX.length), false) } else { @@ -23,3 +21,10 @@ Object.defineProperty(exports, 'defaultSession', { return bindings.fromPartition('', false) } }) + +const wrapSession = function (session) { + // Session is an EventEmitter. + Object.setPrototypeOf(session, EventEmitter.prototype) +} + +bindings._setWrapSession(wrapSession) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 0f79a185ffc..fbb91879f80 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -5,7 +5,6 @@ const {ipcMain, Menu, NavigationController} = require('electron') const binding = process.atomBinding('web_contents') const debuggerBinding = process.atomBinding('debugger') -const sessionBinding = process.atomBinding('session') let nextId = 0 @@ -212,14 +211,8 @@ let wrapDebugger = function (webContentsDebugger) { Object.setPrototypeOf(webContentsDebugger, EventEmitter.prototype) } -var wrapSession = function (session) { - // session is an EventEmitter. - Object.setPrototypeOf(session, EventEmitter.prototype) -} - binding._setWrapWebContents(wrapWebContents) debuggerBinding._setWrapDebugger(wrapDebugger) -sessionBinding._setWrapSession(wrapSession) module.exports = { create (options = {}) { From 8dfbbcefc8213f6f7eca9dc2b023e1d47c6b50de Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 10:53:06 +0900 Subject: [PATCH 1223/1265] Throw error when session module is used before app is ready --- lib/browser/api/session.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/browser/api/session.js b/lib/browser/api/session.js index 49b169bd3ac..dc1c529878f 100644 --- a/lib/browser/api/session.js +++ b/lib/browser/api/session.js @@ -1,16 +1,26 @@ const {EventEmitter} = require('events') +const electron = require('electron') const bindings = process.atomBinding('session') const PERSIST_PREFIX = 'persist:' +// Wrapper of binding.fromPartition that checks for ready event. +const fromPartition = function (partition, persist) { + if (!electron.app.isReady()) { + throw new Error('session module can only be used when app is ready') + } + + return bindings.fromPartition(partition, persist) +} + // Returns the Session from |partition| string. exports.fromPartition = function (partition = '') { if (partition === '') return exports.defaultSession if (partition.startsWith(PERSIST_PREFIX)) { - return bindings.fromPartition(partition.substr(PERSIST_PREFIX.length), false) + return fromPartition(partition.substr(PERSIST_PREFIX.length), false) } else { - return bindings.fromPartition(partition, true) + return fromPartition(partition, true) } } @@ -18,7 +28,7 @@ exports.fromPartition = function (partition = '') { Object.defineProperty(exports, 'defaultSession', { enumerable: true, get: function () { - return bindings.fromPartition('', false) + return fromPartition('', false) } }) From 89adc122c3bfcb0bbd9404bfc5e85de7c952a9d1 Mon Sep 17 00:00:00 2001 From: Colin Eberhardt Date: Wed, 1 Jun 2016 06:36:45 +0100 Subject: [PATCH 1224/1265] Minor typo fixes --- docs/tutorial/security.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/security.md b/docs/tutorial/security.md index 94794872037..2ac25d135eb 100644 --- a/docs/tutorial/security.md +++ b/docs/tutorial/security.md @@ -9,7 +9,7 @@ discovered security threats. When working with Electron, it is important to understand that Electron is not a web browser. It allows you to build feature-rich desktop applications with familiar web technologies, but your code wields much greater power. JavaScript -can access to the filesystem, the user shell, and more. This allows you to build +can access the filesystem, user shell, and more. This allows you to build high quality native applications, but the inherent security risks scale with the additional powers granted to your code. From 523e8c2e1c815d58a7facf65a34f072f593ccfd5 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 14:01:59 +0900 Subject: [PATCH 1225/1265] Update libchromiumcontent and brightray for #5781 --- script/lib/config.py | 2 +- vendor/brightray | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/script/lib/config.py b/script/lib/config.py index 006faf1b920..43423e51436 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -8,7 +8,7 @@ import sys BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \ 'https://s3.amazonaws.com/github-janky-artifacts/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'eda589282bd7729f36960d2e669d4b81375b897c' +LIBCHROMIUMCONTENT_COMMIT = '8f2a0aa0a9dd107e4d574cc9d552781c55c86bab' PLATFORM = { 'cygwin': 'win32', diff --git a/vendor/brightray b/vendor/brightray index e9b2a4ffa29..9ccab3c9a87 160000 --- a/vendor/brightray +++ b/vendor/brightray @@ -1 +1 @@ -Subproject commit e9b2a4ffa29209fbd12a0b1613e8633d42f0b103 +Subproject commit 9ccab3c9a87cc57b4a37c4a03e17b589ac81d6ae From 5bb8da60737802d9c4e09b2c813ec93539fb92be Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 14:57:35 +0900 Subject: [PATCH 1226/1265] Explicitly initialize session before webContents --- lib/browser/api/app.js | 5 +++-- lib/browser/api/web-contents.js | 6 +++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/browser/api/app.js b/lib/browser/api/app.js index f8a531626bf..09835a792e0 100644 --- a/lib/browser/api/app.js +++ b/lib/browser/api/app.js @@ -1,6 +1,7 @@ 'use strict' -const {deprecate, Menu, session} = require('electron') +const electron = require('electron') +const {deprecate, Menu} = electron const {EventEmitter} = require('events') const bindings = process.atomBinding('app') @@ -49,7 +50,7 @@ app.allowNTLMCredentialsForAllDomains = function (allow) { if (!this.isReady()) { this.commandLine.appendSwitch('auth-server-whitelist', domains) } else { - session.defaultSession.allowNTLMCredentialsForDomains(domains) + electron.session.defaultSession.allowNTLMCredentialsForDomains(domains) } } diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index cb8cf41e3aa..059f204e1ee 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -1,7 +1,11 @@ 'use strict' const {EventEmitter} = require('events') -const {ipcMain, Menu, NavigationController} = require('electron') +const {ipcMain, session, Menu, NavigationController} = require('electron') + +// session is not used here, the purpose is to make sure session is initalized +// before the webContents module. +session const binding = process.atomBinding('web_contents') const debuggerBinding = process.atomBinding('debugger') From eb882855bcd5dc925695ceb54669da51696f9bcd Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 15:08:51 +0900 Subject: [PATCH 1227/1265] Cleanup the CoffeeScript converted code --- lib/browser/api/web-contents.js | 46 ++++++++++++++------------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index 059f204e1ee..d7bcdb455b3 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -11,12 +11,11 @@ const binding = process.atomBinding('web_contents') const debuggerBinding = process.atomBinding('debugger') let nextId = 0 - -let getNextId = function () { +const getNextId = function () { return ++nextId } -let PDFPageSize = { +const PDFPageSize = { A5: { custom_display_name: 'A5', height_microns: 210000, @@ -64,9 +63,9 @@ const webFrameMethods = [ 'setZoomLevelLimits' ] -let wrapWebContents = function (webContents) { +// Add JavaScript wrappers for WebContents class. +const wrapWebContents = function (webContents) { // webContents is an EventEmitter. - var controller, method, name, ref1 Object.setPrototypeOf(webContents, EventEmitter.prototype) // Every remote callback from renderer process would add a listenter to the @@ -85,21 +84,18 @@ let wrapWebContents = function (webContents) { webContents.sendToAll = sendWrapper.bind(null, true) // The navigation controller. - controller = new NavigationController(webContents) - ref1 = NavigationController.prototype - for (name in ref1) { - method = ref1[name] + const controller = new NavigationController(webContents) + for (const name in NavigationController.prototype) { + const method = NavigationController.prototype[name] if (method instanceof Function) { - (function (name, method) { - webContents[name] = function () { - return method.apply(controller, arguments) - } - })(name, method) + webContents[name] = function () { + return method.apply(controller, arguments) + } } } // Mapping webFrame methods. - for (let method of webFrameMethods) { + for (const method of webFrameMethods) { webContents[method] = function (...args) { this.send('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', method, args) } @@ -115,7 +111,7 @@ let wrapWebContents = function (webContents) { // Make sure webContents.executeJavaScript would run the code only when the // webContents has been loaded. webContents.executeJavaScript = function (code, hasUserGesture, callback) { - let requestId = getNextId() + const requestId = getNextId() if (typeof hasUserGesture === 'function') { callback = hasUserGesture hasUserGesture = false @@ -131,18 +127,16 @@ let wrapWebContents = function (webContents) { // Dispatch IPC messages to the ipc module. webContents.on('ipc-message', function (event, [channel, ...args]) { - ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) + ipcMain.emit(channel, event, ...args) }) webContents.on('ipc-message-sync', function (event, [channel, ...args]) { Object.defineProperty(event, 'returnValue', { set: function (value) { return event.sendReply(JSON.stringify(value)) }, - get: function () { - return undefined - } + get: function () {} }) - return ipcMain.emit.apply(ipcMain, [channel, event].concat(args)) + ipcMain.emit(channel, event, ...args) }) // Handle context menu action request from pepper plugin. @@ -164,8 +158,7 @@ let wrapWebContents = function (webContents) { }) webContents.printToPDF = function (options, callback) { - var printingSetting - printingSetting = { + const printingSetting = { pageRage: [], mediaSize: {}, landscape: false, @@ -229,13 +222,14 @@ let wrapWebContents = function (webContents) { } } -// Wrapper for native class. -let wrapDebugger = function (webContentsDebugger) { +binding._setWrapWebContents(wrapWebContents) + +// Add JavaScript wrappers for Debugger class. +const wrapDebugger = function (webContentsDebugger) { // debugger is an EventEmitter. Object.setPrototypeOf(webContentsDebugger, EventEmitter.prototype) } -binding._setWrapWebContents(wrapWebContents) debuggerBinding._setWrapDebugger(wrapDebugger) module.exports = { From a70749e80ae8fbc17f96c6007f3d440af5e38610 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Mon, 30 May 2016 18:08:09 +0530 Subject: [PATCH 1228/1265] browser: implement bluetooth chooser interface --- atom/browser/api/atom_api_web_contents.cc | 9 ++ atom/browser/api/atom_api_web_contents.h | 3 + atom/browser/bluetooth_chooser.cc | 107 ++++++++++++++++++++++ atom/browser/bluetooth_chooser.h | 45 +++++++++ filenames.gypi | 2 + 5 files changed, 166 insertions(+) create mode 100644 atom/browser/bluetooth_chooser.cc create mode 100644 atom/browser/bluetooth_chooser.h diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index 736fb7ca0fb..ab68fafe716 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -14,6 +14,7 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_security_state_model_client.h" +#include "atom/browser/bluetooth_chooser.h" #include "atom/browser/native_window.h" #include "atom/browser/net/atom_network_delegate.h" #include "atom/browser/web_contents_permission_helper.h" @@ -504,6 +505,14 @@ void WebContents::RequestToLockMouse( permission_helper->RequestPointerLockPermission(user_gesture); } +std::unique_ptr WebContents::RunBluetoothChooser( + content::RenderFrameHost* frame, + const content::BluetoothChooser::EventHandler& event_handler) { + std::unique_ptr bluetooth_chooser( + new BluetoothChooser(this, event_handler)); + return std::move(bluetooth_chooser); +} + void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index e03ab653a8c..85c43f1486a 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -211,6 +211,9 @@ class WebContents : public mate::TrackableObject, content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; + std::unique_ptr RunBluetoothChooser( + content::RenderFrameHost* frame, + const content::BluetoothChooser::EventHandler& handler) override; // content::WebContentsObserver: void BeforeUnloadFired(const base::TimeTicks& proceed_time) override; diff --git a/atom/browser/bluetooth_chooser.cc b/atom/browser/bluetooth_chooser.cc new file mode 100644 index 00000000000..37c30a36081 --- /dev/null +++ b/atom/browser/bluetooth_chooser.cc @@ -0,0 +1,107 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/bluetooth_chooser.h" +#include "atom/common/native_mate_converters/callback.h" +#include "atom/common/native_mate_converters/string16_converter.h" +#include "native_mate/dictionary.h" + +namespace mate { + +template<> +struct Converter { + static v8::Local ToV8( + v8::Isolate* isolate, const atom::BluetoothChooser::DeviceInfo& val) { + mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); + dict.Set("deviceName", val.device_name); + dict.Set("deviceId", val.device_id); + return mate::ConvertToV8(isolate, dict); + } +}; + +} // namespace mate + +namespace atom { + +namespace { + +const int kMaxScanRetries = 5; + +void OnDeviceChosen( + const content::BluetoothChooser::EventHandler& handler, + const std::string& device_id) { + if (device_id.empty()) { + handler.Run(content::BluetoothChooser::Event::CANCELLED, device_id); + } else { + handler.Run(content::BluetoothChooser::Event::SELECTED, device_id); + } +} + +} // namespace + +BluetoothChooser::BluetoothChooser( + api::WebContents* contents, + const EventHandler& event_handler) + : api_web_contents_(contents), + event_handler_(event_handler), + num_retries_(0) { +} + +BluetoothChooser::~BluetoothChooser() { +} + +void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { + switch (presence) { + case AdapterPresence::ABSENT: + case AdapterPresence::POWERED_OFF: + event_handler_.Run(Event::CANCELLED, ""); + break; + case AdapterPresence::POWERED_ON: + break; + } +} + +void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { + switch (state) { + case DiscoveryState::FAILED_TO_START: + event_handler_.Run(Event::CANCELLED, ""); + break; + case DiscoveryState::IDLE: + if (device_list_.empty()) { + auto event = ++num_retries_ > kMaxScanRetries ? Event::CANCELLED + : Event::RESCAN; + event_handler_.Run(event, ""); + } else { + bool prevent_default = + api_web_contents_->Emit("select-bluetooth-device", + device_list_, + base::Bind(&OnDeviceChosen, + event_handler_)); + if (!prevent_default) { + auto device_id = device_list_[0].device_id; + event_handler_.Run(Event::SELECTED, device_id); + } + } + break; + case DiscoveryState::DISCOVERING: + break; + } +} + +void BluetoothChooser::AddDevice(const std::string& device_id, + const base::string16& device_name) { + DeviceInfo info = {device_id, device_name}; + device_list_.push_back(info); +} + +void BluetoothChooser::RemoveDevice(const std::string& device_id) { + for (auto it = device_list_.begin(); it != device_list_.end(); ++it) { + if (it->device_id == device_id) { + device_list_.erase(it); + return; + } + } +} + +} // namespace atom diff --git a/atom/browser/bluetooth_chooser.h b/atom/browser/bluetooth_chooser.h new file mode 100644 index 00000000000..69617191ba4 --- /dev/null +++ b/atom/browser/bluetooth_chooser.h @@ -0,0 +1,45 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ +#define ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ + +#include +#include + +#include "atom/browser/api/atom_api_web_contents.h" +#include "content/public/browser/bluetooth_chooser.h" + +namespace atom { + +class BluetoothChooser : public content::BluetoothChooser { + public: + struct DeviceInfo { + std::string device_id; + base::string16 device_name; + }; + + explicit BluetoothChooser(api::WebContents* contents, + const EventHandler& handler); + ~BluetoothChooser() override; + + // content::BluetoothChooser: + void SetAdapterPresence(AdapterPresence presence) override; + void ShowDiscoveryState(DiscoveryState state) override; + void AddDevice(const std::string& device_id, + const base::string16& device_name) override; + void RemoveDevice(const std::string& device_id) override; + + private: + std::vector device_list_; + api::WebContents* api_web_contents_; + EventHandler event_handler_; + int num_retries_; + + DISALLOW_COPY_AND_ASSIGN(BluetoothChooser); +}; + +} // namespace atom + +#endif // ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ diff --git a/filenames.gypi b/filenames.gypi index ae71164a8ab..66874efc07d 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -167,6 +167,8 @@ 'atom/browser/atom_security_state_model_client.h', 'atom/browser/atom_speech_recognition_manager_delegate.cc', 'atom/browser/atom_speech_recognition_manager_delegate.h', + 'atom/browser/bluetooth_chooser.cc', + 'atom/browser/bluetooth_chooser.h', 'atom/browser/bridge_task_runner.cc', 'atom/browser/bridge_task_runner.h', 'atom/browser/browser.cc', From 51daf8e194d6d5660c29736f6dd1dc07d2ad24ee Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Tue, 31 May 2016 13:37:45 +0530 Subject: [PATCH 1229/1265] add docs --- docs/api/web-contents.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 89d7e1245d7..941879b7f74 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -373,6 +373,22 @@ The `editFlags` is an object with the following properties: Emitted when there is a new context menu that needs to be handled. +### Event: 'select-bluetooth-device' + +Returns: + +* `event` Event +* `devices` [Objects] + * `deviceName` String + * `deviceId` String +* `callback` Function + * `deviceId` String + +Emitted when bluetooth device needs to be selected on call to +`navigator.bluetooth.requestDevice`. If `event.preventDefault` is not called, +first available device will be selected. `callback` should be called with `deviceId` +to be selected. + ## Instance Methods The `webContents` object has the following instance methods: From db4dc4757aa85da8c6b46b6c4ea81eff8f9ee895 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 1 Jun 2016 11:17:21 +0530 Subject: [PATCH 1230/1265] move bluetooth_chooser to atom/browser/lib --- atom/browser/{ => lib}/bluetooth_chooser.cc | 0 atom/browser/{ => lib}/bluetooth_chooser.h | 0 filenames.gypi | 4 ++-- 3 files changed, 2 insertions(+), 2 deletions(-) rename atom/browser/{ => lib}/bluetooth_chooser.cc (100%) rename atom/browser/{ => lib}/bluetooth_chooser.h (100%) diff --git a/atom/browser/bluetooth_chooser.cc b/atom/browser/lib/bluetooth_chooser.cc similarity index 100% rename from atom/browser/bluetooth_chooser.cc rename to atom/browser/lib/bluetooth_chooser.cc diff --git a/atom/browser/bluetooth_chooser.h b/atom/browser/lib/bluetooth_chooser.h similarity index 100% rename from atom/browser/bluetooth_chooser.h rename to atom/browser/lib/bluetooth_chooser.h diff --git a/filenames.gypi b/filenames.gypi index 66874efc07d..f66b98134c6 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -167,8 +167,6 @@ 'atom/browser/atom_security_state_model_client.h', 'atom/browser/atom_speech_recognition_manager_delegate.cc', 'atom/browser/atom_speech_recognition_manager_delegate.h', - 'atom/browser/bluetooth_chooser.cc', - 'atom/browser/bluetooth_chooser.h', 'atom/browser/bridge_task_runner.cc', 'atom/browser/bridge_task_runner.h', 'atom/browser/browser.cc', @@ -183,6 +181,8 @@ 'atom/browser/common_web_contents_delegate.h', 'atom/browser/javascript_environment.cc', 'atom/browser/javascript_environment.h', + 'atom/browser/lib/bluetooth_chooser.cc', + 'atom/browser/lib/bluetooth_chooser.h', 'atom/browser/login_handler.cc', 'atom/browser/login_handler.h', 'atom/browser/mac/atom_application.h', From de4bff003f82344efa83f0c183c62e09b824c766 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 1 Jun 2016 11:24:41 +0530 Subject: [PATCH 1231/1265] fix header paths and comments --- atom/browser/api/atom_api_web_contents.cc | 2 +- atom/browser/lib/bluetooth_chooser.cc | 2 +- atom/browser/lib/bluetooth_chooser.h | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index ab68fafe716..9d93d980be4 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -14,7 +14,7 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_security_state_model_client.h" -#include "atom/browser/bluetooth_chooser.h" +#include "atom/browser/lib/bluetooth_chooser.h" #include "atom/browser/native_window.h" #include "atom/browser/net/atom_network_delegate.h" #include "atom/browser/web_contents_permission_helper.h" diff --git a/atom/browser/lib/bluetooth_chooser.cc b/atom/browser/lib/bluetooth_chooser.cc index 37c30a36081..2ed21bd333f 100644 --- a/atom/browser/lib/bluetooth_chooser.cc +++ b/atom/browser/lib/bluetooth_chooser.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#include "atom/browser/bluetooth_chooser.h" +#include "atom/browser/lib/bluetooth_chooser.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "native_mate/dictionary.h" diff --git a/atom/browser/lib/bluetooth_chooser.h b/atom/browser/lib/bluetooth_chooser.h index 69617191ba4..615dfcb8c66 100644 --- a/atom/browser/lib/bluetooth_chooser.h +++ b/atom/browser/lib/bluetooth_chooser.h @@ -2,8 +2,8 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#ifndef ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ -#define ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ +#ifndef ATOM_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ +#define ATOM_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ #include #include @@ -42,4 +42,4 @@ class BluetoothChooser : public content::BluetoothChooser { } // namespace atom -#endif // ATOM_BROWSER_BLUETOOTH_CHOOSER_H_ +#endif // ATOM_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ From 743483846344515aa971be3d786d14e3ba125c82 Mon Sep 17 00:00:00 2001 From: deepak1556 Date: Wed, 1 Jun 2016 11:39:14 +0530 Subject: [PATCH 1232/1265] fix docs --- docs/api/web-contents.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 941879b7f74..2d489c6726a 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -385,9 +385,29 @@ Returns: * `deviceId` String Emitted when bluetooth device needs to be selected on call to -`navigator.bluetooth.requestDevice`. If `event.preventDefault` is not called, -first available device will be selected. `callback` should be called with `deviceId` -to be selected. +`navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api +`webBluetooth` should be enabled. If `event.preventDefault` is not called, +first available device will be selected. `callback` should be called with +`deviceId` to be selected, passing empty string to `callback` will +cancel the request. + +```javacript +app.commandLine.appendSwitch('enable-web-bluetooth') + +app.on('ready', () => { + webContents.on('select-bluetooth-device', (event, deviceList, callback) => { + event.preventDefault() + let result = deviceList.find((device) => { + return device.deviceName === 'test' + }) + if (!result) { + callback('') + } else { + callback(result.deviceId) + } + }) +}) +``` ## Instance Methods From 0864d3b1ee7370ece474532ffbeda646c2e5ed5e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 15:24:53 +0900 Subject: [PATCH 1233/1265] Cleanup the printToPDF code --- lib/browser/api/web-contents.js | 81 +++++++++++++++++---------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/lib/browser/api/web-contents.js b/lib/browser/api/web-contents.js index d7bcdb455b3..ed7bfe0b8bd 100644 --- a/lib/browser/api/web-contents.js +++ b/lib/browser/api/web-contents.js @@ -15,7 +15,8 @@ const getNextId = function () { return ++nextId } -const PDFPageSize = { +// Stock page sizes +const PDFPageSizes = { A5: { custom_display_name: 'A5', height_microns: 210000, @@ -55,6 +56,31 @@ const PDFPageSize = { } } +// Default printing setting +const defaultPrintingSetting = { + pageRage: [], + mediaSize: {}, + landscape: false, + color: 2, + headerFooterEnabled: false, + marginsType: 0, + isFirstRequest: false, + requestID: getNextId(), + previewModifiable: true, + printToPDF: true, + printWithCloudPrint: false, + printWithPrivet: false, + printWithExtension: false, + deviceName: 'Save as PDF', + generateDraftData: true, + fitToPageEnabled: false, + duplex: 0, + copies: 1, + collate: true, + shouldPrintBackgrounds: false, + shouldPrintSelectionOnly: false +} + // Following methods are mapped to webFrame. const webFrameMethods = [ 'insertText', @@ -158,29 +184,7 @@ const wrapWebContents = function (webContents) { }) webContents.printToPDF = function (options, callback) { - const printingSetting = { - pageRage: [], - mediaSize: {}, - landscape: false, - color: 2, - headerFooterEnabled: false, - marginsType: 0, - isFirstRequest: false, - requestID: getNextId(), - previewModifiable: true, - printToPDF: true, - printWithCloudPrint: false, - printWithPrivet: false, - printWithExtension: false, - deviceName: 'Save as PDF', - generateDraftData: true, - fitToPageEnabled: false, - duplex: 0, - copies: 1, - collate: true, - shouldPrintBackgrounds: false, - shouldPrintSelectionOnly: false - } + const printingSetting = Object.assign({}, defaultPrintingSetting) if (options.landscape) { printingSetting.landscape = options.landscape } @@ -195,30 +199,29 @@ const wrapWebContents = function (webContents) { } if (options.pageSize) { - let height = 0 - let width = 0 - if (typeof options.pageSize === 'object') { + const pageSize = options.pageSize + if (typeof pageSize === 'object') { + if (!pageSize.height || !pageSize.width) { + return callback(new Error('Must define height and width for pageSize')) + } // Dimensions in Microns // 1 meter = 10^6 microns - height = options.pageSize.height ? options.pageSize.height : 0 - width = options.pageSize.width ? options.pageSize.width : 0 - } - - if (height > 0 && width > 0) { printingSetting.mediaSize = { - height_microns: height, name: 'CUSTOM', - width_microns: width, - custom_display_name: 'Custom' + custom_display_name: 'Custom', + height_microns: pageSize.height, + width_microns: pageSize.width } - } else if (PDFPageSize[options.pageSize]) { - printingSetting.mediaSize = PDFPageSize[options.pageSize] + } else if (PDFPageSizes[pageSize]) { + printingSetting.mediaSize = PDFPageSizes[pageSize] } else { - printingSetting.mediaSize = PDFPageSize['A4'] + return callback(new Error(`Does not support pageSize with ${pageSize}`)) } + } else { + printingSetting.mediaSize = PDFPageSizes['A4'] } - return this._printToPDF(printingSetting, callback) + this._printToPDF(printingSetting, callback) } } From 01b10b3b39d3e34f6aedbeaa431d18afdd58d060 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 15:27:17 +0900 Subject: [PATCH 1234/1265] Slightly improve docs of webContents.printToPDF --- docs/api/web-contents.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 89d7e1245d7..ca9cf43c468 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -655,7 +655,8 @@ size. * `marginsType` Integer - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. * `pageSize` String - Specify page size of the generated PDF. Can be `A3`, - `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` & `width` in Microns. + `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` + and `width` in microns. * `printBackground` Boolean - Whether to print CSS backgrounds. * `printSelectionOnly` Boolean - Whether to print selection only. * `landscape` Boolean - `true` for landscape, `false` for portrait. @@ -678,6 +679,8 @@ By default, an empty `options` will be regarded as: } ``` +An example of `webContents.printToPDF`: + ```javascript const {BrowserWindow} = require('electron'); const fs = require('fs'); From 97dd71d79e67a4a5769f65cfa44def05ba16127d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 16:15:53 +0900 Subject: [PATCH 1235/1265] Bump v1.2.1 --- atom/browser/resources/mac/Info.plist | 4 ++-- atom/browser/resources/win/atom.rc | 8 ++++---- atom/common/atom_version.h | 2 +- electron.gyp | 2 +- package.json | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index f1c6b413706..28eddfa6123 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 1.2.0 + 1.2.1 CFBundleShortVersionString - 1.2.0 + 1.2.1 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index 701e6fe2948..7e386d319d9 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,2,0,0 - PRODUCTVERSION 1,2,0,0 + FILEVERSION 1,2,1,0 + PRODUCTVERSION 1,2,1,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "1.2.0" + VALUE "FileVersion", "1.2.1" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "1.2.0" + VALUE "ProductVersion", "1.2.1" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index cf2ef14d8cc..455bfacbfc1 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -7,7 +7,7 @@ #define ATOM_MAJOR_VERSION 1 #define ATOM_MINOR_VERSION 2 -#define ATOM_PATCH_VERSION 0 +#define ATOM_PATCH_VERSION 1 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/electron.gyp b/electron.gyp index c1144412153..055cb0c209a 100644 --- a/electron.gyp +++ b/electron.gyp @@ -4,7 +4,7 @@ 'product_name%': 'Electron', 'company_name%': 'GitHub, Inc', 'company_abbr%': 'github', - 'version%': '1.2.0', + 'version%': '1.2.1', }, 'includes': [ 'filenames.gypi', diff --git a/package.json b/package.json index d96ed1cd42a..6f873786e3f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "electron", - "version": "1.2.0", + "version": "1.2.1", "devDependencies": { "asar": "^0.11.0", "request": "*", From 7b3ba739bf4b9452051369b431980f016f5967ec Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 16:26:08 +0900 Subject: [PATCH 1236/1265] Import chrome/browser/mac/relauncher.{cc,h} --- chromium_src/chrome/browser/mac/relauncher.cc | 381 ++++++++++++++++++ chromium_src/chrome/browser/mac/relauncher.h | 77 ++++ filenames.gypi | 2 + 3 files changed, 460 insertions(+) create mode 100644 chromium_src/chrome/browser/mac/relauncher.cc create mode 100644 chromium_src/chrome/browser/mac/relauncher.h diff --git a/chromium_src/chrome/browser/mac/relauncher.cc b/chromium_src/chrome/browser/mac/relauncher.cc new file mode 100644 index 00000000000..40ea5371bf9 --- /dev/null +++ b/chromium_src/chrome/browser/mac/relauncher.cc @@ -0,0 +1,381 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/mac/relauncher.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "base/files/file_util.h" +#include "base/files/scoped_file.h" +#include "base/logging.h" +#include "base/mac/mac_logging.h" +#include "base/mac/mac_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/path_service.h" +#include "base/posix/eintr_wrapper.h" +#include "base/process/launch.h" +#include "base/strings/stringprintf.h" +#include "base/strings/sys_string_conversions.h" +#include "chrome/browser/mac/install_from_dmg.h" +#include "chrome/common/chrome_switches.h" +#include "content/public/common/content_paths.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/main_function_params.h" + +namespace mac_relauncher { + +namespace { + +// The "magic" file descriptor that the relauncher process' write side of the +// pipe shows up on. Chosen to avoid conflicting with stdin, stdout, and +// stderr. +const int kRelauncherSyncFD = STDERR_FILENO + 1; + +// The argument separating arguments intended for the relauncher process from +// those intended for the relaunched process. "---" is chosen instead of "--" +// because CommandLine interprets "--" as meaning "end of switches", but +// for many purposes, the relauncher process' CommandLine ought to interpret +// arguments intended for the relaunched process, to get the correct settings +// for such things as logging and the user-data-dir in case it affects crash +// reporting. +const char kRelauncherArgSeparator[] = "---"; + +// When this argument is supplied to the relauncher process, it will launch +// the relaunched process without bringing it to the foreground. +const char kRelauncherBackgroundArg[] = "--background"; + +// The beginning of the "process serial number" argument that Launch Services +// sometimes inserts into command lines. A process serial number is only valid +// for a single process, so any PSN arguments will be stripped from command +// lines during relaunch to avoid confusion. +const char kPSNArg[] = "-psn_"; + +// Returns the "type" argument identifying a relauncher process +// ("--type=relauncher"). +std::string RelauncherTypeArg() { + return base::StringPrintf("--%s=%s", + switches::kProcessType, + switches::kRelauncherProcess); +} + +} // namespace + +bool RelaunchApp(const std::vector& args) { + // Use the currently-running application's helper process. The automatic + // update feature is careful to leave the currently-running version alone, + // so this is safe even if the relaunch is the result of an update having + // been applied. In fact, it's safer than using the updated version of the + // helper process, because there's no guarantee that the updated version's + // relauncher implementation will be compatible with the running version's. + base::FilePath child_path; + if (!PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { + LOG(ERROR) << "No CHILD_PROCESS_EXE"; + return false; + } + + std::vector relauncher_args; + return RelaunchAppWithHelper(child_path.value(), relauncher_args, args); +} + +bool RelaunchAppWithHelper(const std::string& helper, + const std::vector& relauncher_args, + const std::vector& args) { + std::vector relaunch_args; + relaunch_args.push_back(helper); + relaunch_args.push_back(RelauncherTypeArg()); + + // If this application isn't in the foreground, the relaunched one shouldn't + // be either. + if (!base::mac::AmIForeground()) { + relaunch_args.push_back(kRelauncherBackgroundArg); + } + + relaunch_args.insert(relaunch_args.end(), + relauncher_args.begin(), relauncher_args.end()); + + relaunch_args.push_back(kRelauncherArgSeparator); + + // When using the CommandLine interface, -psn_ may have been rewritten as + // --psn_. Look for both. + const char alt_psn_arg[] = "--psn_"; + for (size_t index = 0; index < args.size(); ++index) { + // Strip any -psn_ arguments, as they apply to a specific process. + if (args[index].compare(0, strlen(kPSNArg), kPSNArg) != 0 && + args[index].compare(0, strlen(alt_psn_arg), alt_psn_arg) != 0) { + relaunch_args.push_back(args[index]); + } + } + + int pipe_fds[2]; + if (HANDLE_EINTR(pipe(pipe_fds)) != 0) { + PLOG(ERROR) << "pipe"; + return false; + } + + // The parent process will only use pipe_read_fd as the read side of the + // pipe. It can close the write side as soon as the relauncher process has + // forked off. The relauncher process will only use pipe_write_fd as the + // write side of the pipe. In that process, the read side will be closed by + // base::LaunchApp because it won't be present in fd_map, and the write side + // will be remapped to kRelauncherSyncFD by fd_map. + base::ScopedFD pipe_read_fd(pipe_fds[0]); + base::ScopedFD pipe_write_fd(pipe_fds[1]); + + // Make sure kRelauncherSyncFD is a safe value. base::LaunchProcess will + // preserve these three FDs in forked processes, so kRelauncherSyncFD should + // not conflict with them. + static_assert(kRelauncherSyncFD != STDIN_FILENO && + kRelauncherSyncFD != STDOUT_FILENO && + kRelauncherSyncFD != STDERR_FILENO, + "kRelauncherSyncFD must not conflict with stdio fds"); + + base::FileHandleMappingVector fd_map; + fd_map.push_back(std::make_pair(pipe_write_fd.get(), kRelauncherSyncFD)); + + base::LaunchOptions options; + options.fds_to_remap = &fd_map; + if (!base::LaunchProcess(relaunch_args, options).IsValid()) { + LOG(ERROR) << "base::LaunchProcess failed"; + return false; + } + + // The relauncher process is now starting up, or has started up. The + // original parent process continues. + + pipe_write_fd.reset(); // close(pipe_fds[1]); + + // Synchronize with the relauncher process. + char read_char; + int read_result = HANDLE_EINTR(read(pipe_read_fd.get(), &read_char, 1)); + if (read_result != 1) { + if (read_result < 0) { + PLOG(ERROR) << "read"; + } else { + LOG(ERROR) << "read: unexpected result " << read_result; + } + return false; + } + + // Since a byte has been successfully read from the relauncher process, it's + // guaranteed to have set up its kqueue monitoring this process for exit. + // It's safe to exit now. + return true; +} + +namespace { + +// In the relauncher process, performs the necessary synchronization steps +// with the parent by setting up a kqueue to watch for it to exit, writing a +// byte to the pipe, and then waiting for the exit notification on the kqueue. +// If anything fails, this logs a message and returns immediately. In those +// situations, it can be assumed that something went wrong with the parent +// process and the best recovery approach is to attempt relaunch anyway. +void RelauncherSynchronizeWithParent() { + base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); + + int parent_pid = getppid(); + + // PID 1 identifies init. launchd, that is. launchd never starts the + // relauncher process directly, having this parent_pid means that the parent + // already exited and launchd "inherited" the relauncher as its child. + // There's no reason to synchronize with launchd. + if (parent_pid == 1) { + LOG(ERROR) << "unexpected parent_pid"; + return; + } + + // Set up a kqueue to monitor the parent process for exit. + base::ScopedFD kq(kqueue()); + if (!kq.is_valid()) { + PLOG(ERROR) << "kqueue"; + return; + } + + struct kevent change = { 0 }; + EV_SET(&change, parent_pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); + if (kevent(kq.get(), &change, 1, NULL, 0, NULL) == -1) { + PLOG(ERROR) << "kevent (add)"; + return; + } + + // Write a '\0' character to the pipe. + if (HANDLE_EINTR(write(relauncher_sync_fd.get(), "", 1)) != 1) { + PLOG(ERROR) << "write"; + return; + } + + // Up until now, the parent process was blocked in a read waiting for the + // write above to complete. The parent process is now free to exit. Wait for + // that to happen. + struct kevent event; + int events = kevent(kq.get(), NULL, 0, &event, 1, NULL); + if (events != 1) { + if (events < 0) { + PLOG(ERROR) << "kevent (monitor)"; + } else { + LOG(ERROR) << "kevent (monitor): unexpected result " << events; + } + return; + } + + if (event.filter != EVFILT_PROC || + event.fflags != NOTE_EXIT || + event.ident != static_cast(parent_pid)) { + LOG(ERROR) << "kevent (monitor): unexpected event, filter " << event.filter + << ", fflags " << event.fflags << ", ident " << event.ident; + return; + } +} + +} // namespace + +namespace internal { + +int RelauncherMain(const content::MainFunctionParams& main_parameters) { + // CommandLine rearranges the order of the arguments returned by + // main_parameters.argv(), rendering it impossible to determine which + // arguments originally came before kRelauncherArgSeparator and which came + // after. It's crucial to distinguish between these because only those + // after the separator should be given to the relaunched process; it's also + // important to not treat the path to the relaunched process as a "loose" + // argument. NXArgc and NXArgv are pointers to the original argc and argv as + // passed to main(), so use those. Access them through _NSGetArgc and + // _NSGetArgv because NXArgc and NXArgv are normally only available to a + // main executable via crt1.o and this code will run from a dylib, and + // because of http://crbug.com/139902. + const int* argcp = _NSGetArgc(); + if (!argcp) { + NOTREACHED(); + return 1; + } + int argc = *argcp; + + const char* const* const* argvp = _NSGetArgv(); + if (!argvp) { + NOTREACHED(); + return 1; + } + const char* const* argv = *argvp; + + if (argc < 4 || RelauncherTypeArg() != argv[1]) { + LOG(ERROR) << "relauncher process invoked with unexpected arguments"; + return 1; + } + + RelauncherSynchronizeWithParent(); + + // The capacity for relaunch_args is 4 less than argc, because it + // won't contain the argv[0] of the relauncher process, the + // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the + // executable path of the process to be launched. + base::ScopedCFTypeRef relaunch_args( + CFArrayCreateMutable(NULL, argc - 4, &kCFTypeArrayCallBacks)); + if (!relaunch_args) { + LOG(ERROR) << "CFArrayCreateMutable"; + return 1; + } + + // Figure out what to execute, what arguments to pass it, and whether to + // start it in the background. + bool background = false; + bool in_relaunch_args = false; + std::string dmg_bsd_device_name; + bool seen_relaunch_executable = false; + std::string relaunch_executable; + const std::string relauncher_arg_separator(kRelauncherArgSeparator); + const std::string relauncher_dmg_device_arg = + base::StringPrintf("--%s=", switches::kRelauncherProcessDMGDevice); + for (int argv_index = 2; argv_index < argc; ++argv_index) { + const std::string arg(argv[argv_index]); + + // Strip any -psn_ arguments, as they apply to a specific process. + if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) { + continue; + } + + if (!in_relaunch_args) { + if (arg == relauncher_arg_separator) { + in_relaunch_args = true; + } else if (arg == kRelauncherBackgroundArg) { + background = true; + } else if (arg.compare(0, + relauncher_dmg_device_arg.size(), + relauncher_dmg_device_arg) == 0) { + dmg_bsd_device_name.assign( + arg.substr(relauncher_dmg_device_arg.size())); + } + } else { + if (!seen_relaunch_executable) { + // The first argument after kRelauncherBackgroundArg is the path to + // the executable file or .app bundle directory. The Launch Services + // interface wants this separate from the rest of the arguments. In + // the relaunched process, this path will still be visible at argv[0]. + relaunch_executable.assign(arg); + seen_relaunch_executable = true; + } else { + base::ScopedCFTypeRef arg_cf( + base::SysUTF8ToCFStringRef(arg)); + if (!arg_cf) { + LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; + return 1; + } + CFArrayAppendValue(relaunch_args, arg_cf); + } + } + } + + if (!seen_relaunch_executable) { + LOG(ERROR) << "nothing to relaunch"; + return 1; + } + + FSRef app_fsref; + if (!base::mac::FSRefFromPath(relaunch_executable, &app_fsref)) { + LOG(ERROR) << "base::mac::FSRefFromPath failed for " << relaunch_executable; + return 1; + } + + LSApplicationParameters ls_parameters = { + 0, // version + kLSLaunchDefaults | kLSLaunchAndDisplayErrors | kLSLaunchNewInstance | + (background ? kLSLaunchDontSwitch : 0), + &app_fsref, + NULL, // asyncLaunchRefCon + NULL, // environment + relaunch_args, + NULL // initialEvent + }; + + OSStatus status = LSOpenApplication(&ls_parameters, NULL); + if (status != noErr) { + OSSTATUS_LOG(ERROR, status) << "LSOpenApplication"; + return 1; + } + + // The application should have relaunched (or is in the process of + // relaunching). From this point on, only clean-up tasks should occur, and + // failures are tolerable. + + if (!dmg_bsd_device_name.empty()) { + EjectAndTrashDiskImage(dmg_bsd_device_name); + } + + return 0; +} + +} // namespace internal + +} // namespace mac_relauncher diff --git a/chromium_src/chrome/browser/mac/relauncher.h b/chromium_src/chrome/browser/mac/relauncher.h new file mode 100644 index 00000000000..66391b423fe --- /dev/null +++ b/chromium_src/chrome/browser/mac/relauncher.h @@ -0,0 +1,77 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_MAC_RELAUNCHER_H_ +#define CHROME_BROWSER_MAC_RELAUNCHER_H_ + +// mac_relauncher implements main browser application relaunches on the Mac. +// When a browser wants to relaunch itself, it can't simply fork off a new +// process and exec a new browser from within. That leaves open a window +// during which two browser applications might be running concurrently. If +// that happens, each will wind up with a distinct Dock icon, which is +// especially bad if the user expected the Dock icon to be persistent by +// choosing Keep in Dock from the icon's contextual menu. +// +// mac_relauncher approaches this problem by introducing an intermediate +// process (the "relauncher") in between the original browser ("parent") and +// replacement browser ("relaunched"). The helper executable is used for the +// relauncher process; because it's an LSUIElement, it doesn't get a Dock +// icon and isn't visible as a running application at all. The parent will +// start a relauncher process, giving it the "writer" side of a pipe that it +// retains the "reader" end of. When the relauncher starts up, it will +// establish a kqueue to wait for the parent to exit, and will then write to +// the pipe. The parent, upon reading from the pipe, is free to exit. When the +// relauncher is notified via its kqueue that the parent has exited, it +// proceeds, launching the relaunched process. The handshake to synchronize +// the parent with the relauncher is necessary to avoid races: the relauncher +// needs to be sure that it's monitoring the parent and not some other process +// in light of PID reuse, so the parent must remain alive long enough for the +// relauncher to set up its kqueue. + +#include +#include + +namespace content { +struct MainFunctionParams; +} + +namespace mac_relauncher { + +// Relaunches the application using the helper application associated with the +// currently running instance of Chrome in the parent browser process as the +// executable for the relauncher process. |args| is an argv-style vector of +// command line arguments of the form normally passed to execv. args[0] is +// also the path to the relaunched process. Because the relauncher process +// will ultimately launch the relaunched process via Launch Services, args[0] +// may be either a pathname to an executable file or a pathname to an .app +// bundle directory. The caller should exit soon after RelaunchApp returns +// successfully. Returns true on success, although some failures can occur +// after this function returns true if, for example, they occur within the +// relauncher process. Returns false when the relaunch definitely failed. +bool RelaunchApp(const std::vector& args); + +// Identical to RelaunchApp, but uses |helper| as the path to the relauncher +// process, and allows additional arguments to be supplied to the relauncher +// process in relauncher_args. Unlike args[0], |helper| must be a pathname to +// an executable file. The helper path given must be from the same version of +// Chrome as the running parent browser process, as there are no guarantees +// that the parent and relauncher processes from different versions will be +// able to communicate with one another. This variant can be useful to +// relaunch the same version of Chrome from another location, using that +// location's helper. +bool RelaunchAppWithHelper(const std::string& helper, + const std::vector& relauncher_args, + const std::vector& args); + +namespace internal { + +// The entry point from ChromeMain into the relauncher process. This is not a +// user API. Don't call it if your name isn't ChromeMain. +int RelauncherMain(const content::MainFunctionParams& main_parameters); + +} // namespace internal + +} // namespace mac_relauncher + +#endif // CHROME_BROWSER_MAC_RELAUNCHER_H_ diff --git a/filenames.gypi b/filenames.gypi index f66b98134c6..0d1d97711b4 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -420,6 +420,8 @@ 'chromium_src/chrome/browser/extensions/global_shortcut_listener_x11.h', 'chromium_src/chrome/browser/extensions/global_shortcut_listener_win.cc', 'chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h', + 'chromium_src/chrome/browser/mac/relauncher.cc', + 'chromium_src/chrome/browser/mac/relauncher.h', 'chromium_src/chrome/browser/media/desktop_media_list.h', 'chromium_src/chrome/browser/media/desktop_media_list_observer.h', 'chromium_src/chrome/browser/media/native_desktop_media_list.cc', From abdcb9d4817ae025272aec2e3cfd567da6162670 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 18:22:14 +0900 Subject: [PATCH 1237/1265] Implement app.relaunch on OS X --- atom/app/atom_main_delegate.cc | 28 +++++++++++++++++++ atom/app/atom_main_delegate.h | 9 ++++++ atom/browser/api/atom_api_app.cc | 1 + atom/browser/browser.h | 4 +++ atom/browser/browser_mac.mm | 11 ++++++++ chromium_src/chrome/browser/mac/relauncher.cc | 18 +----------- 6 files changed, 54 insertions(+), 17 deletions(-) diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index 9ce8dc504a9..170bee2be84 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -21,10 +21,18 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" +#if defined(OS_MACOSX) +#include "chrome/browser/mac/relauncher.h" +#endif + namespace atom { namespace { +#if defined(OS_MACOSX) +const char* kRelauncherProcess = "relauncher"; +#endif + bool IsBrowserProcess(base::CommandLine* cmd) { std::string process_type = cmd->GetSwitchValueASCII(switches::kProcessType); return process_type.empty(); @@ -146,6 +154,26 @@ content::ContentUtilityClient* AtomMainDelegate::CreateContentUtilityClient() { return utility_client_.get(); } +#if defined(OS_MACOSX) +int AtomMainDelegate::RunProcess( + const std::string& process_type, + const content::MainFunctionParams& main_function_params) { + if (process_type == kRelauncherProcess) + return mac_relauncher::internal::RelauncherMain(main_function_params); + else + return -1; +} + +bool AtomMainDelegate::ShouldSendMachPort(const std::string& process_type) { + return process_type != kRelauncherProcess; +} + +bool AtomMainDelegate::DelaySandboxInitialization( + const std::string& process_type) { + return process_type == kRelauncherProcess; +} +#endif + std::unique_ptr AtomMainDelegate::CreateContentClient() { return std::unique_ptr(new AtomContentClient); diff --git a/atom/app/atom_main_delegate.h b/atom/app/atom_main_delegate.h index 2f9474cff56..b12a6dcdc4a 100644 --- a/atom/app/atom_main_delegate.h +++ b/atom/app/atom_main_delegate.h @@ -5,6 +5,8 @@ #ifndef ATOM_APP_ATOM_MAIN_DELEGATE_H_ #define ATOM_APP_ATOM_MAIN_DELEGATE_H_ +#include + #include "brightray/common/main_delegate.h" #include "brightray/common/content_client.h" @@ -22,6 +24,13 @@ class AtomMainDelegate : public brightray::MainDelegate { content::ContentBrowserClient* CreateContentBrowserClient() override; content::ContentRendererClient* CreateContentRendererClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override; +#if defined(OS_MACOSX) + int RunProcess( + const std::string& process_type, + const content::MainFunctionParams& main_function_params) override; + bool ShouldSendMachPort(const std::string& process_type) override; + bool DelaySandboxInitialization(const std::string& process_type) override; +#endif // brightray::MainDelegate: std::unique_ptr CreateContentClient() override; diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 3599e3195fc..c5bce573ddf 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -450,6 +450,7 @@ void App::BuildPrototype( mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("quit", base::Bind(&Browser::Quit, browser)) .SetMethod("exit", base::Bind(&Browser::Exit, browser)) + .SetMethod("relaunch", base::Bind(&Browser::Relaunch, browser)) .SetMethod("focus", base::Bind(&Browser::Focus, browser)) .SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser)) .SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser)) diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 18d0c97c93a..2b446d621fd 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -53,6 +53,10 @@ class Browser : public WindowListObserver { // Cleanup everything and shutdown the application gracefully. void Shutdown(); + // Restart the app. + void Relaunch(const std::vector& args, + const std::string& app); + // Focus the application. void Focus(); diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 4561eab8c95..9149a212697 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -13,11 +13,22 @@ #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "brightray/common/application_info.h" +#include "brightray/common/mac/main_application_bundle.h" +#include "chrome/browser/mac/relauncher.h" #include "net/base/mac/url_conversions.h" #include "url/gurl.h" namespace atom { +void Browser::Relaunch(const std::vector& args, + const std::string& app) { + std::vector args_with_app(args); + args_with_app.insert( + args_with_app.begin(), + app.empty() ? brightray::MainApplicationBundlePath().value() : app); + mac_relauncher::RelaunchApp(args_with_app); +} + void Browser::Focus() { [[AtomApplication sharedApplication] activateIgnoringOtherApps:YES]; } diff --git a/chromium_src/chrome/browser/mac/relauncher.cc b/chromium_src/chrome/browser/mac/relauncher.cc index 40ea5371bf9..f76e44c637e 100644 --- a/chromium_src/chrome/browser/mac/relauncher.cc +++ b/chromium_src/chrome/browser/mac/relauncher.cc @@ -29,8 +29,6 @@ #include "base/process/launch.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" -#include "chrome/browser/mac/install_from_dmg.h" -#include "chrome/common/chrome_switches.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" @@ -66,9 +64,7 @@ const char kPSNArg[] = "-psn_"; // Returns the "type" argument identifying a relauncher process // ("--type=relauncher"). std::string RelauncherTypeArg() { - return base::StringPrintf("--%s=%s", - switches::kProcessType, - switches::kRelauncherProcess); + return base::StringPrintf("--%s=%s", switches::kProcessType, "relauncher"); } } // namespace @@ -292,12 +288,9 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // start it in the background. bool background = false; bool in_relaunch_args = false; - std::string dmg_bsd_device_name; bool seen_relaunch_executable = false; std::string relaunch_executable; const std::string relauncher_arg_separator(kRelauncherArgSeparator); - const std::string relauncher_dmg_device_arg = - base::StringPrintf("--%s=", switches::kRelauncherProcessDMGDevice); for (int argv_index = 2; argv_index < argc; ++argv_index) { const std::string arg(argv[argv_index]); @@ -311,11 +304,6 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { in_relaunch_args = true; } else if (arg == kRelauncherBackgroundArg) { background = true; - } else if (arg.compare(0, - relauncher_dmg_device_arg.size(), - relauncher_dmg_device_arg) == 0) { - dmg_bsd_device_name.assign( - arg.substr(relauncher_dmg_device_arg.size())); } } else { if (!seen_relaunch_executable) { @@ -369,10 +357,6 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // relaunching). From this point on, only clean-up tasks should occur, and // failures are tolerable. - if (!dmg_bsd_device_name.empty()) { - EjectAndTrashDiskImage(dmg_bsd_device_name); - } - return 0; } From 6df18956cdfe3329c9a046e3e3b96e4942d6a43c Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 22:04:20 +0900 Subject: [PATCH 1238/1265] Get ready to make relauncher cross-platform --- atom/app/atom_main_delegate.cc | 11 ++----- atom/app/atom_main_delegate.h | 2 -- atom/browser/browser_mac.mm | 4 +-- .../mac => atom/browser}/relauncher.cc | 20 ++---------- .../browser/mac => atom/browser}/relauncher.h | 31 ++++++++++--------- filenames.gypi | 4 +-- 6 files changed, 26 insertions(+), 46 deletions(-) rename {chromium_src/chrome/browser/mac => atom/browser}/relauncher.cc (95%) rename {chromium_src/chrome/browser/mac => atom/browser}/relauncher.h (77%) diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index 170bee2be84..dbd27123933 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -9,6 +9,7 @@ #include "atom/app/atom_content_client.h" #include "atom/browser/atom_browser_client.h" +#include "atom/browser/relauncher.h" #include "atom/common/google_api_key.h" #include "atom/renderer/atom_renderer_client.h" #include "atom/utility/atom_content_utility_client.h" @@ -21,17 +22,11 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" -#if defined(OS_MACOSX) -#include "chrome/browser/mac/relauncher.h" -#endif - namespace atom { namespace { -#if defined(OS_MACOSX) const char* kRelauncherProcess = "relauncher"; -#endif bool IsBrowserProcess(base::CommandLine* cmd) { std::string process_type = cmd->GetSwitchValueASCII(switches::kProcessType); @@ -154,12 +149,11 @@ content::ContentUtilityClient* AtomMainDelegate::CreateContentUtilityClient() { return utility_client_.get(); } -#if defined(OS_MACOSX) int AtomMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (process_type == kRelauncherProcess) - return mac_relauncher::internal::RelauncherMain(main_function_params); + return relauncher::RelauncherMain(main_function_params); else return -1; } @@ -172,7 +166,6 @@ bool AtomMainDelegate::DelaySandboxInitialization( const std::string& process_type) { return process_type == kRelauncherProcess; } -#endif std::unique_ptr AtomMainDelegate::CreateContentClient() { diff --git a/atom/app/atom_main_delegate.h b/atom/app/atom_main_delegate.h index b12a6dcdc4a..377665f629d 100644 --- a/atom/app/atom_main_delegate.h +++ b/atom/app/atom_main_delegate.h @@ -24,13 +24,11 @@ class AtomMainDelegate : public brightray::MainDelegate { content::ContentBrowserClient* CreateContentBrowserClient() override; content::ContentRendererClient* CreateContentRendererClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override; -#if defined(OS_MACOSX) int RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) override; bool ShouldSendMachPort(const std::string& process_type) override; bool DelaySandboxInitialization(const std::string& process_type) override; -#endif // brightray::MainDelegate: std::unique_ptr CreateContentClient() override; diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 9149a212697..271b88de4ce 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -8,13 +8,13 @@ #include "atom/browser/mac/atom_application_delegate.h" #include "atom/browser/mac/dict_util.h" #include "atom/browser/native_window.h" +#include "atom/browser/relauncher.h" #include "atom/browser/window_list.h" #include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "brightray/common/application_info.h" #include "brightray/common/mac/main_application_bundle.h" -#include "chrome/browser/mac/relauncher.h" #include "net/base/mac/url_conversions.h" #include "url/gurl.h" @@ -26,7 +26,7 @@ void Browser::Relaunch(const std::vector& args, args_with_app.insert( args_with_app.begin(), app.empty() ? brightray::MainApplicationBundlePath().value() : app); - mac_relauncher::RelaunchApp(args_with_app); + relauncher::RelaunchApp(args_with_app); } void Browser::Focus() { diff --git a/chromium_src/chrome/browser/mac/relauncher.cc b/atom/browser/relauncher.cc similarity index 95% rename from chromium_src/chrome/browser/mac/relauncher.cc rename to atom/browser/relauncher.cc index f76e44c637e..284093152ef 100644 --- a/chromium_src/chrome/browser/mac/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/mac/relauncher.h" +#include "atom/browser/relauncher.h" #include #include @@ -33,7 +33,7 @@ #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" -namespace mac_relauncher { +namespace relauncher { namespace { @@ -171,14 +171,6 @@ bool RelaunchAppWithHelper(const std::string& helper, return true; } -namespace { - -// In the relauncher process, performs the necessary synchronization steps -// with the parent by setting up a kqueue to watch for it to exit, writing a -// byte to the pipe, and then waiting for the exit notification on the kqueue. -// If anything fails, this logs a message and returns immediately. In those -// situations, it can be assumed that something went wrong with the parent -// process and the best recovery approach is to attempt relaunch anyway. void RelauncherSynchronizeWithParent() { base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); @@ -236,10 +228,6 @@ void RelauncherSynchronizeWithParent() { } } -} // namespace - -namespace internal { - int RelauncherMain(const content::MainFunctionParams& main_parameters) { // CommandLine rearranges the order of the arguments returned by // main_parameters.argv(), rendering it impossible to determine which @@ -360,6 +348,4 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { return 0; } -} // namespace internal - -} // namespace mac_relauncher +} // namespace relauncher diff --git a/chromium_src/chrome/browser/mac/relauncher.h b/atom/browser/relauncher.h similarity index 77% rename from chromium_src/chrome/browser/mac/relauncher.h rename to atom/browser/relauncher.h index 66391b423fe..f072a725336 100644 --- a/chromium_src/chrome/browser/mac/relauncher.h +++ b/atom/browser/relauncher.h @@ -1,11 +1,11 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_MAC_RELAUNCHER_H_ -#define CHROME_BROWSER_MAC_RELAUNCHER_H_ +#ifndef ATOM_BROWSER_RELAUNCHER_H_ +#define ATOM_BROWSER_RELAUNCHER_H_ -// mac_relauncher implements main browser application relaunches on the Mac. +// relauncher implements main browser application relaunches across platforms. // When a browser wants to relaunch itself, it can't simply fork off a new // process and exec a new browser from within. That leaves open a window // during which two browser applications might be running concurrently. If @@ -13,7 +13,7 @@ // especially bad if the user expected the Dock icon to be persistent by // choosing Keep in Dock from the icon's contextual menu. // -// mac_relauncher approaches this problem by introducing an intermediate +// relauncher approaches this problem by introducing an intermediate // process (the "relauncher") in between the original browser ("parent") and // replacement browser ("relaunched"). The helper executable is used for the // relauncher process; because it's an LSUIElement, it doesn't get a Dock @@ -36,7 +36,7 @@ namespace content { struct MainFunctionParams; } -namespace mac_relauncher { +namespace relauncher { // Relaunches the application using the helper application associated with the // currently running instance of Chrome in the parent browser process as the @@ -64,14 +64,17 @@ bool RelaunchAppWithHelper(const std::string& helper, const std::vector& relauncher_args, const std::vector& args); -namespace internal { +// In the relauncher process, performs the necessary synchronization steps +// with the parent by setting up a kqueue to watch for it to exit, writing a +// byte to the pipe, and then waiting for the exit notification on the kqueue. +// If anything fails, this logs a message and returns immediately. In those +// situations, it can be assumed that something went wrong with the parent +// process and the best recovery approach is to attempt relaunch anyway. +void RelauncherSynchronizeWithParent(); -// The entry point from ChromeMain into the relauncher process. This is not a -// user API. Don't call it if your name isn't ChromeMain. +// The entry point from ChromeMain into the relauncher process. int RelauncherMain(const content::MainFunctionParams& main_parameters); -} // namespace internal +} // namespace relauncher -} // namespace mac_relauncher - -#endif // CHROME_BROWSER_MAC_RELAUNCHER_H_ +#endif // ATOM_BROWSER_RELAUNCHER_H_ diff --git a/filenames.gypi b/filenames.gypi index 0d1d97711b4..3ce737f22a0 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -225,6 +225,8 @@ 'atom/browser/net/url_request_fetch_job.h', 'atom/browser/node_debugger.cc', 'atom/browser/node_debugger.h', + 'atom/browser/relauncher.cc', + 'atom/browser/relauncher.h', 'atom/browser/render_process_preferences.cc', 'atom/browser/render_process_preferences.h', 'atom/browser/ui/accelerator_util.cc', @@ -420,8 +422,6 @@ 'chromium_src/chrome/browser/extensions/global_shortcut_listener_x11.h', 'chromium_src/chrome/browser/extensions/global_shortcut_listener_win.cc', 'chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h', - 'chromium_src/chrome/browser/mac/relauncher.cc', - 'chromium_src/chrome/browser/mac/relauncher.h', 'chromium_src/chrome/browser/media/desktop_media_list.h', 'chromium_src/chrome/browser/media/desktop_media_list_observer.h', 'chromium_src/chrome/browser/media/native_desktop_media_list.cc', From fc30a2a084129f1f30678da7d922f33aaedb6f83 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Wed, 1 Jun 2016 22:15:50 +0900 Subject: [PATCH 1239/1265] Use AtomCommandLine to process command line parameters --- atom/browser/relauncher.cc | 41 +++++++------------------------------- 1 file changed, 7 insertions(+), 34 deletions(-) diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 284093152ef..d48f13b931a 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -5,11 +5,7 @@ #include "atom/browser/relauncher.h" #include -#include -#include -#include -#include -#include + #include #include #include @@ -18,8 +14,8 @@ #include #include +#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" -#include "base/files/scoped_file.h" #include "base/logging.h" #include "base/mac/mac_logging.h" #include "base/mac/mac_util.h" @@ -229,32 +225,9 @@ void RelauncherSynchronizeWithParent() { } int RelauncherMain(const content::MainFunctionParams& main_parameters) { - // CommandLine rearranges the order of the arguments returned by - // main_parameters.argv(), rendering it impossible to determine which - // arguments originally came before kRelauncherArgSeparator and which came - // after. It's crucial to distinguish between these because only those - // after the separator should be given to the relaunched process; it's also - // important to not treat the path to the relaunched process as a "loose" - // argument. NXArgc and NXArgv are pointers to the original argc and argv as - // passed to main(), so use those. Access them through _NSGetArgc and - // _NSGetArgv because NXArgc and NXArgv are normally only available to a - // main executable via crt1.o and this code will run from a dylib, and - // because of http://crbug.com/139902. - const int* argcp = _NSGetArgc(); - if (!argcp) { - NOTREACHED(); - return 1; - } - int argc = *argcp; + const std::vector& argv = atom::AtomCommandLine::argv(); - const char* const* const* argvp = _NSGetArgv(); - if (!argvp) { - NOTREACHED(); - return 1; - } - const char* const* argv = *argvp; - - if (argc < 4 || RelauncherTypeArg() != argv[1]) { + if (argv.size() < 4 || RelauncherTypeArg() != argv[1]) { LOG(ERROR) << "relauncher process invoked with unexpected arguments"; return 1; } @@ -266,7 +239,7 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the // executable path of the process to be launched. base::ScopedCFTypeRef relaunch_args( - CFArrayCreateMutable(NULL, argc - 4, &kCFTypeArrayCallBacks)); + CFArrayCreateMutable(NULL, argv.size() - 4, &kCFTypeArrayCallBacks)); if (!relaunch_args) { LOG(ERROR) << "CFArrayCreateMutable"; return 1; @@ -279,8 +252,8 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { bool seen_relaunch_executable = false; std::string relaunch_executable; const std::string relauncher_arg_separator(kRelauncherArgSeparator); - for (int argv_index = 2; argv_index < argc; ++argv_index) { - const std::string arg(argv[argv_index]); + for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { + const std::string& arg(argv[argv_index]); // Strip any -psn_ arguments, as they apply to a specific process. if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) { From 3b11355521d441ac000a27a7d95c4c479d66d00b Mon Sep 17 00:00:00 2001 From: Pierre-Yves Jamon Date: Wed, 1 Jun 2016 15:12:49 +0200 Subject: [PATCH 1240/1265] Add nuts link to the docs Add link to GitbookIO/nuts in the docs page for autoUpdater --- docs/api/auto-updater.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index cb6403a273e..a2eec31ecbf 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -8,6 +8,7 @@ The `autoUpdater` module provides an interface for the You can quickly launch a multi-platform release server for distributing your application by using one of these projects: +- [nuts][nuts]: *A smart release server for your applications, using GitHub as a backend. Auto-updates with Squirrel (Mac & Windows)* - [electron-release-server][electron-release-server]: *A fully featured, self-hosted release server for electron applications, compatible with auto-updater* @@ -118,3 +119,4 @@ should only be called after `update-downloaded` has been emitted. [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-release-server]: https://github.com/ArekSredzki/electron-release-server [squirrel-updates-server]: https://github.com/Aluxian/squirrel-updates-server +[nuts]: https://github.com/GitbookIO/nuts From 789a878f07e7a329524859e9cd113aa65086f01b Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 1 Jun 2016 13:16:53 -0700 Subject: [PATCH 1241/1265] Rename atom-shell-frameworks repo name and org --- script/update-external-binaries.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/script/update-external-binaries.py b/script/update-external-binaries.py index c70860707e8..470f735fdb4 100755 --- a/script/update-external-binaries.py +++ b/script/update-external-binaries.py @@ -10,7 +10,7 @@ from lib.util import safe_mkdir, rm_rf, extract_zip, tempdir, download VERSION = 'v1.0.0' SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) -FRAMEWORKS_URL = 'http://github.com/atom/atom-shell-frameworks/releases' \ +FRAMEWORKS_URL = 'http://github.com/electron/electron-frameworks/releases' \ '/download/' + VERSION From 060829da64cb3c5b6dff95bc02b525d81cbe6b39 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 09:09:32 +0900 Subject: [PATCH 1242/1265] Separate implementations of RelauncherMain and RelauncherSynchronizeWithParent --- atom/app/atom_main_delegate.cc | 2 +- atom/browser/relauncher.cc | 234 ++------------------------------- atom/browser/relauncher.h | 21 +++ atom/browser/relauncher_mac.cc | 187 ++++++++++++++++++++++++++ filenames.gypi | 1 + 5 files changed, 224 insertions(+), 221 deletions(-) create mode 100644 atom/browser/relauncher_mac.cc diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index dbd27123933..c601fd681e7 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -153,7 +153,7 @@ int AtomMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (process_type == kRelauncherProcess) - return relauncher::RelauncherMain(main_function_params); + return relauncher::internal::RelauncherMain(main_function_params); else return -1; } diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index d48f13b931a..41b67f38b5e 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -1,69 +1,31 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/relauncher.h" -#include - -#include -#include -#include -#include - #include #include -#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/mac/mac_logging.h" -#include "base/mac/mac_util.h" -#include "base/mac/scoped_cftyperef.h" #include "base/path_service.h" #include "base/posix/eintr_wrapper.h" #include "base/process/launch.h" #include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" namespace relauncher { -namespace { +namespace internal { -// The "magic" file descriptor that the relauncher process' write side of the -// pipe shows up on. Chosen to avoid conflicting with stdin, stdout, and -// stderr. const int kRelauncherSyncFD = STDERR_FILENO + 1; +const char* kRelauncherTypeArg = "--type=relauncher"; +const char* kRelauncherArgSeparator = "---"; -// The argument separating arguments intended for the relauncher process from -// those intended for the relaunched process. "---" is chosen instead of "--" -// because CommandLine interprets "--" as meaning "end of switches", but -// for many purposes, the relauncher process' CommandLine ought to interpret -// arguments intended for the relaunched process, to get the correct settings -// for such things as logging and the user-data-dir in case it affects crash -// reporting. -const char kRelauncherArgSeparator[] = "---"; - -// When this argument is supplied to the relauncher process, it will launch -// the relaunched process without bringing it to the foreground. -const char kRelauncherBackgroundArg[] = "--background"; - -// The beginning of the "process serial number" argument that Launch Services -// sometimes inserts into command lines. A process serial number is only valid -// for a single process, so any PSN arguments will be stripped from command -// lines during relaunch to avoid confusion. -const char kPSNArg[] = "-psn_"; - -// Returns the "type" argument identifying a relauncher process -// ("--type=relauncher"). -std::string RelauncherTypeArg() { - return base::StringPrintf("--%s=%s", switches::kProcessType, "relauncher"); -} - -} // namespace +} // namespace internal bool RelaunchApp(const std::vector& args) { // Use the currently-running application's helper process. The automatic @@ -87,29 +49,14 @@ bool RelaunchAppWithHelper(const std::string& helper, const std::vector& args) { std::vector relaunch_args; relaunch_args.push_back(helper); - relaunch_args.push_back(RelauncherTypeArg()); - - // If this application isn't in the foreground, the relaunched one shouldn't - // be either. - if (!base::mac::AmIForeground()) { - relaunch_args.push_back(kRelauncherBackgroundArg); - } + relaunch_args.push_back(internal::kRelauncherTypeArg); relaunch_args.insert(relaunch_args.end(), relauncher_args.begin(), relauncher_args.end()); - relaunch_args.push_back(kRelauncherArgSeparator); + relaunch_args.push_back(internal::kRelauncherArgSeparator); - // When using the CommandLine interface, -psn_ may have been rewritten as - // --psn_. Look for both. - const char alt_psn_arg[] = "--psn_"; - for (size_t index = 0; index < args.size(); ++index) { - // Strip any -psn_ arguments, as they apply to a specific process. - if (args[index].compare(0, strlen(kPSNArg), kPSNArg) != 0 && - args[index].compare(0, strlen(alt_psn_arg), alt_psn_arg) != 0) { - relaunch_args.push_back(args[index]); - } - } + relaunch_args.insert(relaunch_args.end(), args.begin(), args.end()); int pipe_fds[2]; if (HANDLE_EINTR(pipe(pipe_fds)) != 0) { @@ -129,13 +76,14 @@ bool RelaunchAppWithHelper(const std::string& helper, // Make sure kRelauncherSyncFD is a safe value. base::LaunchProcess will // preserve these three FDs in forked processes, so kRelauncherSyncFD should // not conflict with them. - static_assert(kRelauncherSyncFD != STDIN_FILENO && - kRelauncherSyncFD != STDOUT_FILENO && - kRelauncherSyncFD != STDERR_FILENO, + static_assert(internal::kRelauncherSyncFD != STDIN_FILENO && + internal::kRelauncherSyncFD != STDOUT_FILENO && + internal::kRelauncherSyncFD != STDERR_FILENO, "kRelauncherSyncFD must not conflict with stdio fds"); base::FileHandleMappingVector fd_map; - fd_map.push_back(std::make_pair(pipe_write_fd.get(), kRelauncherSyncFD)); + fd_map.push_back( + std::make_pair(pipe_write_fd.get(), internal::kRelauncherSyncFD)); base::LaunchOptions options; options.fds_to_remap = &fd_map; @@ -167,158 +115,4 @@ bool RelaunchAppWithHelper(const std::string& helper, return true; } -void RelauncherSynchronizeWithParent() { - base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); - - int parent_pid = getppid(); - - // PID 1 identifies init. launchd, that is. launchd never starts the - // relauncher process directly, having this parent_pid means that the parent - // already exited and launchd "inherited" the relauncher as its child. - // There's no reason to synchronize with launchd. - if (parent_pid == 1) { - LOG(ERROR) << "unexpected parent_pid"; - return; - } - - // Set up a kqueue to monitor the parent process for exit. - base::ScopedFD kq(kqueue()); - if (!kq.is_valid()) { - PLOG(ERROR) << "kqueue"; - return; - } - - struct kevent change = { 0 }; - EV_SET(&change, parent_pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); - if (kevent(kq.get(), &change, 1, NULL, 0, NULL) == -1) { - PLOG(ERROR) << "kevent (add)"; - return; - } - - // Write a '\0' character to the pipe. - if (HANDLE_EINTR(write(relauncher_sync_fd.get(), "", 1)) != 1) { - PLOG(ERROR) << "write"; - return; - } - - // Up until now, the parent process was blocked in a read waiting for the - // write above to complete. The parent process is now free to exit. Wait for - // that to happen. - struct kevent event; - int events = kevent(kq.get(), NULL, 0, &event, 1, NULL); - if (events != 1) { - if (events < 0) { - PLOG(ERROR) << "kevent (monitor)"; - } else { - LOG(ERROR) << "kevent (monitor): unexpected result " << events; - } - return; - } - - if (event.filter != EVFILT_PROC || - event.fflags != NOTE_EXIT || - event.ident != static_cast(parent_pid)) { - LOG(ERROR) << "kevent (monitor): unexpected event, filter " << event.filter - << ", fflags " << event.fflags << ", ident " << event.ident; - return; - } -} - -int RelauncherMain(const content::MainFunctionParams& main_parameters) { - const std::vector& argv = atom::AtomCommandLine::argv(); - - if (argv.size() < 4 || RelauncherTypeArg() != argv[1]) { - LOG(ERROR) << "relauncher process invoked with unexpected arguments"; - return 1; - } - - RelauncherSynchronizeWithParent(); - - // The capacity for relaunch_args is 4 less than argc, because it - // won't contain the argv[0] of the relauncher process, the - // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the - // executable path of the process to be launched. - base::ScopedCFTypeRef relaunch_args( - CFArrayCreateMutable(NULL, argv.size() - 4, &kCFTypeArrayCallBacks)); - if (!relaunch_args) { - LOG(ERROR) << "CFArrayCreateMutable"; - return 1; - } - - // Figure out what to execute, what arguments to pass it, and whether to - // start it in the background. - bool background = false; - bool in_relaunch_args = false; - bool seen_relaunch_executable = false; - std::string relaunch_executable; - const std::string relauncher_arg_separator(kRelauncherArgSeparator); - for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { - const std::string& arg(argv[argv_index]); - - // Strip any -psn_ arguments, as they apply to a specific process. - if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) { - continue; - } - - if (!in_relaunch_args) { - if (arg == relauncher_arg_separator) { - in_relaunch_args = true; - } else if (arg == kRelauncherBackgroundArg) { - background = true; - } - } else { - if (!seen_relaunch_executable) { - // The first argument after kRelauncherBackgroundArg is the path to - // the executable file or .app bundle directory. The Launch Services - // interface wants this separate from the rest of the arguments. In - // the relaunched process, this path will still be visible at argv[0]. - relaunch_executable.assign(arg); - seen_relaunch_executable = true; - } else { - base::ScopedCFTypeRef arg_cf( - base::SysUTF8ToCFStringRef(arg)); - if (!arg_cf) { - LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; - return 1; - } - CFArrayAppendValue(relaunch_args, arg_cf); - } - } - } - - if (!seen_relaunch_executable) { - LOG(ERROR) << "nothing to relaunch"; - return 1; - } - - FSRef app_fsref; - if (!base::mac::FSRefFromPath(relaunch_executable, &app_fsref)) { - LOG(ERROR) << "base::mac::FSRefFromPath failed for " << relaunch_executable; - return 1; - } - - LSApplicationParameters ls_parameters = { - 0, // version - kLSLaunchDefaults | kLSLaunchAndDisplayErrors | kLSLaunchNewInstance | - (background ? kLSLaunchDontSwitch : 0), - &app_fsref, - NULL, // asyncLaunchRefCon - NULL, // environment - relaunch_args, - NULL // initialEvent - }; - - OSStatus status = LSOpenApplication(&ls_parameters, NULL); - if (status != noErr) { - OSSTATUS_LOG(ERROR, status) << "LSOpenApplication"; - return 1; - } - - // The application should have relaunched (or is in the process of - // relaunching). From this point on, only clean-up tasks should occur, and - // failures are tolerable. - - return 0; -} - } // namespace relauncher diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index f072a725336..4134ef54225 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -64,6 +64,25 @@ bool RelaunchAppWithHelper(const std::string& helper, const std::vector& relauncher_args, const std::vector& args); +namespace internal { + +// The "magic" file descriptor that the relauncher process' write side of the +// pipe shows up on. Chosen to avoid conflicting with stdin, stdout, and +// stderr. +extern const int kRelauncherSyncFD; + +// The "type" argument identifying a relauncher process ("--type=relauncher"). +extern const char* kRelauncherTypeArg; + +// The argument separating arguments intended for the relauncher process from +// those intended for the relaunched process. "---" is chosen instead of "--" +// because CommandLine interprets "--" as meaning "end of switches", but +// for many purposes, the relauncher process' CommandLine ought to interpret +// arguments intended for the relaunched process, to get the correct settings +// for such things as logging and the user-data-dir in case it affects crash +// reporting. +extern const char* kRelauncherArgSeparator; + // In the relauncher process, performs the necessary synchronization steps // with the parent by setting up a kqueue to watch for it to exit, writing a // byte to the pipe, and then waiting for the exit notification on the kqueue. @@ -75,6 +94,8 @@ void RelauncherSynchronizeWithParent(); // The entry point from ChromeMain into the relauncher process. int RelauncherMain(const content::MainFunctionParams& main_parameters); +} // namespace internal + } // namespace relauncher #endif // ATOM_BROWSER_RELAUNCHER_H_ diff --git a/atom/browser/relauncher_mac.cc b/atom/browser/relauncher_mac.cc new file mode 100644 index 00000000000..39c478f1614 --- /dev/null +++ b/atom/browser/relauncher_mac.cc @@ -0,0 +1,187 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/relauncher.h" + +#include + +#include +#include +#include +#include + +#include "atom/common/atom_command_line.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/mac/mac_logging.h" +#include "base/mac/mac_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/posix/eintr_wrapper.h" +#include "base/strings/sys_string_conversions.h" + +namespace relauncher { + +namespace internal { + +namespace { + +// The beginning of the "process serial number" argument that Launch Services +// sometimes inserts into command lines. A process serial number is only valid +// for a single process, so any PSN arguments will be stripped from command +// lines during relaunch to avoid confusion. +const char kPSNArg[] = "-psn_"; + +} // namespace + +void RelauncherSynchronizeWithParent() { + base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); + + int parent_pid = getppid(); + + // PID 1 identifies init. launchd, that is. launchd never starts the + // relauncher process directly, having this parent_pid means that the parent + // already exited and launchd "inherited" the relauncher as its child. + // There's no reason to synchronize with launchd. + if (parent_pid == 1) { + LOG(ERROR) << "unexpected parent_pid"; + return; + } + + // Set up a kqueue to monitor the parent process for exit. + base::ScopedFD kq(kqueue()); + if (!kq.is_valid()) { + PLOG(ERROR) << "kqueue"; + return; + } + + struct kevent change = { 0 }; + EV_SET(&change, parent_pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); + if (kevent(kq.get(), &change, 1, NULL, 0, NULL) == -1) { + PLOG(ERROR) << "kevent (add)"; + return; + } + + // Write a '\0' character to the pipe. + if (HANDLE_EINTR(write(relauncher_sync_fd.get(), "", 1)) != 1) { + PLOG(ERROR) << "write"; + return; + } + + // Up until now, the parent process was blocked in a read waiting for the + // write above to complete. The parent process is now free to exit. Wait for + // that to happen. + struct kevent event; + int events = kevent(kq.get(), NULL, 0, &event, 1, NULL); + if (events != 1) { + if (events < 0) { + PLOG(ERROR) << "kevent (monitor)"; + } else { + LOG(ERROR) << "kevent (monitor): unexpected result " << events; + } + return; + } + + if (event.filter != EVFILT_PROC || + event.fflags != NOTE_EXIT || + event.ident != static_cast(parent_pid)) { + LOG(ERROR) << "kevent (monitor): unexpected event, filter " << event.filter + << ", fflags " << event.fflags << ", ident " << event.ident; + return; + } +} + +int RelauncherMain(const content::MainFunctionParams& main_parameters) { + const std::vector& argv = atom::AtomCommandLine::argv(); + + if (argv.size() < 4 || kRelauncherTypeArg != argv[1]) { + LOG(ERROR) << "relauncher process invoked with unexpected arguments"; + return 1; + } + + internal::RelauncherSynchronizeWithParent(); + + // The capacity for relaunch_args is 4 less than argc, because it + // won't contain the argv[0] of the relauncher process, the + // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the + // executable path of the process to be launched. + base::ScopedCFTypeRef relaunch_args( + CFArrayCreateMutable(NULL, argv.size() - 4, &kCFTypeArrayCallBacks)); + if (!relaunch_args) { + LOG(ERROR) << "CFArrayCreateMutable"; + return 1; + } + + // Figure out what to execute, what arguments to pass it, and whether to + // start it in the background. + bool in_relaunch_args = false; + bool seen_relaunch_executable = false; + std::string relaunch_executable; + const std::string relauncher_arg_separator(kRelauncherArgSeparator); + for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { + const std::string& arg(argv[argv_index]); + + // Strip any -psn_ arguments, as they apply to a specific process. + if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) { + continue; + } + + if (!in_relaunch_args && arg == relauncher_arg_separator) { + in_relaunch_args = true; + } else { + if (!seen_relaunch_executable) { + // The first argument after kRelauncherBackgroundArg is the path to + // the executable file or .app bundle directory. The Launch Services + // interface wants this separate from the rest of the arguments. In + // the relaunched process, this path will still be visible at argv[0]. + relaunch_executable.assign(arg); + seen_relaunch_executable = true; + } else { + base::ScopedCFTypeRef arg_cf( + base::SysUTF8ToCFStringRef(arg)); + if (!arg_cf) { + LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; + return 1; + } + CFArrayAppendValue(relaunch_args, arg_cf); + } + } + } + + if (!seen_relaunch_executable) { + LOG(ERROR) << "nothing to relaunch"; + return 1; + } + + FSRef app_fsref; + if (!base::mac::FSRefFromPath(relaunch_executable, &app_fsref)) { + LOG(ERROR) << "base::mac::FSRefFromPath failed for " << relaunch_executable; + return 1; + } + + LSApplicationParameters ls_parameters = { + 0, // version + kLSLaunchDefaults | kLSLaunchAndDisplayErrors | kLSLaunchNewInstance, + &app_fsref, + NULL, // asyncLaunchRefCon + NULL, // environment + relaunch_args, + NULL // initialEvent + }; + + OSStatus status = LSOpenApplication(&ls_parameters, NULL); + if (status != noErr) { + OSSTATUS_LOG(ERROR, status) << "LSOpenApplication"; + return 1; + } + + // The application should have relaunched (or is in the process of + // relaunching). From this point on, only clean-up tasks should occur, and + // failures are tolerable. + + return 0; +} + +} // namespace internal + +} // namespace relauncher diff --git a/filenames.gypi b/filenames.gypi index 3ce737f22a0..3cee4ca50c5 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -225,6 +225,7 @@ 'atom/browser/net/url_request_fetch_job.h', 'atom/browser/node_debugger.cc', 'atom/browser/node_debugger.h', + 'atom/browser/relauncher_mac.cc', 'atom/browser/relauncher.cc', 'atom/browser/relauncher.h', 'atom/browser/render_process_preferences.cc', From aa1b8cd74be1bc65f80c332401dc21579829e8ab Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Wed, 1 Jun 2016 18:53:49 -0700 Subject: [PATCH 1243/1265] Expose the NSArrayToListValue converter. --- atom/browser/mac/dict_util.h | 4 +++- atom/browser/mac/dict_util.mm | 4 ---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/atom/browser/mac/dict_util.h b/atom/browser/mac/dict_util.h index 404636d1901..3ffd8ba5100 100644 --- a/atom/browser/mac/dict_util.h +++ b/atom/browser/mac/dict_util.h @@ -10,7 +10,7 @@ #include "base/memory/scoped_ptr.h" namespace base { -class Value; +class ListValue; class DictionaryValue; } @@ -21,6 +21,8 @@ NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value); std::unique_ptr NSDictionaryToDictionaryValue( NSDictionary* dict); +std::unique_ptr NSArrayToListValue(NSArray* arr); + } // namespace atom #endif // ATOM_BROWSER_MAC_DICT_UTIL_H_ diff --git a/atom/browser/mac/dict_util.mm b/atom/browser/mac/dict_util.mm index 43b629cc32b..8692f001f6a 100644 --- a/atom/browser/mac/dict_util.mm +++ b/atom/browser/mac/dict_util.mm @@ -10,8 +10,6 @@ namespace atom { -namespace { - std::unique_ptr NSArrayToListValue(NSArray* arr) { if (!arr) return nullptr; @@ -51,8 +49,6 @@ std::unique_ptr NSArrayToListValue(NSArray* arr) { return result; } -} // namespace - NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value) { std::string json; if (!base::JSONWriter::Write(value, &json)) From 0230567891a7ba1850ff7901f5174c9b16b07464 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Wed, 1 Jun 2016 18:55:20 -0700 Subject: [PATCH 1244/1265] Write a new method that returns prefs under the NSGlobalDomain. --- .../browser/api/atom_api_system_preferences.h | 1 + .../api/atom_api_system_preferences_mac.mm | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 7779ce00781..0234d843440 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -39,6 +39,7 @@ class SystemPreferences : public mate::EventEmitter { void UnsubscribeNotification(int id); v8::Local GetUserDefault(const std::string& name, const std::string& type); + v8::Local GetGlobalDefault(const std::string& name); #endif bool IsDarkMode(); diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index f0b48adf256..2556fef35a6 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -9,6 +9,7 @@ #import #include "atom/browser/mac/dict_util.h" +#include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "base/strings/sys_string_conversions.h" #include "base/values.h" @@ -84,6 +85,26 @@ v8::Local SystemPreferences::GetUserDefault( } } +v8::Local SystemPreferences::GetGlobalDefault(const std::string& name) { + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + NSString* key = base::SysUTF8ToNSString(name); + + NSDictionary* globalPrefs = [defaults persistentDomainForName:NSGlobalDomain]; + id value = [globalPrefs objectForKey:key]; + + if ([value isKindOfClass:[NSString class]]) { + return mate::StringToV8(isolate(), base::SysNSStringToUTF8(value)); + } else if ([value isKindOfClass:[NSNumber class]]) { + return v8::Integer::New(isolate(), [value integerValue]); + } else if ([value isKindOfClass:[NSArray class]]) { + return mate::ConvertToV8(isolate(), *NSArrayToListValue(value)); + } else if ([value isKindOfClass:[NSDictionary class]]) { + return mate::ConvertToV8(isolate(), *NSDictionaryToDictionaryValue(value)); + } else { + return v8::Undefined(isolate()); + } +} + bool SystemPreferences::IsDarkMode() { NSString* mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; From 587dd2fe51767ceb362cfb326921775e4b5d8315 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Wed, 1 Jun 2016 18:56:25 -0700 Subject: [PATCH 1245/1265] Expose the method to JS and write a simple test. --- .../api/atom_api_system_preferences.cc | 1 + spec/api-system-preferences-spec.js | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 spec/api-system-preferences-spec.js diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 2b11aad2527..8a02859f297 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -54,6 +54,7 @@ void SystemPreferences::BuildPrototype( .SetMethod("unsubscribeNotification", &SystemPreferences::UnsubscribeNotification) .SetMethod("getUserDefault", &SystemPreferences::GetUserDefault) + .SetMethod("getGlobalDefault", &SystemPreferences::GetGlobalDefault) #endif .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); } diff --git a/spec/api-system-preferences-spec.js b/spec/api-system-preferences-spec.js new file mode 100644 index 00000000000..3cb0cd40666 --- /dev/null +++ b/spec/api-system-preferences-spec.js @@ -0,0 +1,25 @@ +const assert = require('assert') +const {remote} = require('electron') +const {systemPreferences} = remote + +describe('systemPreferences module', function () { + if (process.platform !== 'darwin') { + return + } + + it('returns user defaults', function () { + assert.notEqual(systemPreferences.getUserDefault('AppleInterfaceStyle', 'string'), null) + assert.notEqual(systemPreferences.getUserDefault('AppleAquaColorVariant', 'integer'), null) + }) + + it('returns defaults under the global domain', function () { + let locale = systemPreferences.getGlobalDefault('AppleLocale') + assert.notEqual(locale, null) + assert(locale.length > 0) + + let languages = systemPreferences.getGlobalDefault('AppleLanguages') + assert.notEqual(languages, null) + assert(languages.length > 0) + }) + +}) From fa3b17444f7b11d1aa687ea23c98937419e5193f Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Wed, 1 Jun 2016 19:21:17 -0700 Subject: [PATCH 1246/1265] All we really need to do is make getUserDefault support array / object types. --- .../api/atom_api_system_preferences.cc | 1 - .../browser/api/atom_api_system_preferences.h | 1 - .../api/atom_api_system_preferences_mac.mm | 34 ++++++------------- docs/api/system-preferences.md | 5 ++- spec/api-system-preferences-spec.js | 11 ++---- 5 files changed, 17 insertions(+), 35 deletions(-) diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 8a02859f297..2b11aad2527 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -54,7 +54,6 @@ void SystemPreferences::BuildPrototype( .SetMethod("unsubscribeNotification", &SystemPreferences::UnsubscribeNotification) .SetMethod("getUserDefault", &SystemPreferences::GetUserDefault) - .SetMethod("getGlobalDefault", &SystemPreferences::GetGlobalDefault) #endif .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); } diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 0234d843440..7779ce00781 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -39,7 +39,6 @@ class SystemPreferences : public mate::EventEmitter { void UnsubscribeNotification(int id); v8::Local GetUserDefault(const std::string& name, const std::string& type); - v8::Local GetGlobalDefault(const std::string& name); #endif bool IsDarkMode(); diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index 2556fef35a6..72011500bd0 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -67,8 +67,8 @@ v8::Local SystemPreferences::GetUserDefault( NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; NSString* key = base::SysUTF8ToNSString(name); if (type == "string") { - return mate::StringToV8( - isolate(), base::SysNSStringToUTF8([defaults stringForKey:key])); + return mate::StringToV8(isolate(), + base::SysNSStringToUTF8([defaults stringForKey:key])); } else if (type == "boolean") { return v8::Boolean::New(isolate(), [defaults boolForKey:key]); } else if (type == "float") { @@ -78,28 +78,14 @@ v8::Local SystemPreferences::GetUserDefault( } else if (type == "double") { return v8::Number::New(isolate(), [defaults doubleForKey:key]); } else if (type == "url") { - return mate::ConvertToV8( - isolate(), net::GURLWithNSURL([defaults URLForKey:key])); - } else { - return v8::Undefined(isolate()); - } -} - -v8::Local SystemPreferences::GetGlobalDefault(const std::string& name) { - NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; - NSString* key = base::SysUTF8ToNSString(name); - - NSDictionary* globalPrefs = [defaults persistentDomainForName:NSGlobalDomain]; - id value = [globalPrefs objectForKey:key]; - - if ([value isKindOfClass:[NSString class]]) { - return mate::StringToV8(isolate(), base::SysNSStringToUTF8(value)); - } else if ([value isKindOfClass:[NSNumber class]]) { - return v8::Integer::New(isolate(), [value integerValue]); - } else if ([value isKindOfClass:[NSArray class]]) { - return mate::ConvertToV8(isolate(), *NSArrayToListValue(value)); - } else if ([value isKindOfClass:[NSDictionary class]]) { - return mate::ConvertToV8(isolate(), *NSDictionaryToDictionaryValue(value)); + return mate::ConvertToV8(isolate(), + net::GURLWithNSURL([defaults URLForKey:key])); + } else if (type == "array") { + return mate::ConvertToV8(isolate(), + *NSArrayToListValue([defaults arrayForKey:key])); + } else if (type == "dictionary") { + return mate::ConvertToV8(isolate(), + *NSDictionaryToDictionaryValue([defaults dictionaryForKey:key])); } else { return v8::Undefined(isolate()); } diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md index 8f4dc899385..7b2f0724a4a 100644 --- a/docs/api/system-preferences.md +++ b/docs/api/system-preferences.md @@ -39,7 +39,7 @@ Removes the subscriber with `id`. * `key` String * `type` String - Can be `string`, `boolean`, `integer`, `float`, `double`, - `url`. + `url`, `array`, `dictionary` Get the value of `key` in system preferences. @@ -50,6 +50,9 @@ are: * `AppleAquaColorVariant: integer` * `AppleHighlightColor: string` * `AppleShowScrollBars: string` +* `NSNavRecentPlaces: array` +* `NSPreferredWebServices: dictionary` +* `NSUserDictionaryReplacementItems: array` ### `systemPreferences.isAeroGlassEnabled()` _Windows_ diff --git a/spec/api-system-preferences-spec.js b/spec/api-system-preferences-spec.js index 3cb0cd40666..220ff92709b 100644 --- a/spec/api-system-preferences-spec.js +++ b/spec/api-system-preferences-spec.js @@ -7,17 +7,12 @@ describe('systemPreferences module', function () { return } - it('returns user defaults', function () { - assert.notEqual(systemPreferences.getUserDefault('AppleInterfaceStyle', 'string'), null) - assert.notEqual(systemPreferences.getUserDefault('AppleAquaColorVariant', 'integer'), null) - }) - - it('returns defaults under the global domain', function () { - let locale = systemPreferences.getGlobalDefault('AppleLocale') + it('returns values for known user defaults', function () { + let locale = systemPreferences.getUserDefault('AppleLocale', 'string') assert.notEqual(locale, null) assert(locale.length > 0) - let languages = systemPreferences.getGlobalDefault('AppleLanguages') + let languages = systemPreferences.getUserDefault('AppleLanguages', 'array') assert.notEqual(languages, null) assert(languages.length > 0) }) From e377298cd2e6184ef57bc5f4cfaa939b9b571ff4 Mon Sep 17 00:00:00 2001 From: Charlie Hess Date: Wed, 1 Jun 2016 19:29:24 -0700 Subject: [PATCH 1247/1265] Be consistent in spec organization. --- spec/api-system-preferences-spec.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/spec/api-system-preferences-spec.js b/spec/api-system-preferences-spec.js index 220ff92709b..333c4dbacb4 100644 --- a/spec/api-system-preferences-spec.js +++ b/spec/api-system-preferences-spec.js @@ -7,14 +7,16 @@ describe('systemPreferences module', function () { return } - it('returns values for known user defaults', function () { - let locale = systemPreferences.getUserDefault('AppleLocale', 'string') - assert.notEqual(locale, null) - assert(locale.length > 0) + describe('systemPreferences.getUserDefault(key, type)', function () { + it('returns values for known user defaults', function () { + let locale = systemPreferences.getUserDefault('AppleLocale', 'string') + assert.notEqual(locale, null) + assert(locale.length > 0) - let languages = systemPreferences.getUserDefault('AppleLanguages', 'array') - assert.notEqual(languages, null) - assert(languages.length > 0) + let languages = systemPreferences.getUserDefault('AppleLanguages', 'array') + assert.notEqual(languages, null) + assert(languages.length > 0) + }) }) }) From c3fe2dae9d334ce4a16322d28a6bdaf5dd182961 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 16:23:46 +0900 Subject: [PATCH 1248/1265] Separate LaunchProgram from mac implementation --- atom/app/atom_main_delegate.cc | 2 +- atom/browser/relauncher.cc | 58 ++++++++++++++++++++++++++++++ atom/browser/relauncher.h | 8 +++-- atom/browser/relauncher_mac.cc | 64 +++++++--------------------------- 4 files changed, 77 insertions(+), 55 deletions(-) diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index c601fd681e7..dbd27123933 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -153,7 +153,7 @@ int AtomMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (process_type == kRelauncherProcess) - return relauncher::internal::RelauncherMain(main_function_params); + return relauncher::RelauncherMain(main_function_params); else return -1; } diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 41b67f38b5e..47c77a119ad 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -7,6 +7,7 @@ #include #include +#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" @@ -115,4 +116,61 @@ bool RelaunchAppWithHelper(const std::string& helper, return true; } +int RelauncherMain(const content::MainFunctionParams& main_parameters) { + const std::vector& argv = atom::AtomCommandLine::argv(); + + if (argv.size() < 4 || argv[1] != internal::kRelauncherTypeArg) { + LOG(ERROR) << "relauncher process invoked with unexpected arguments"; + return 1; + } + + internal::RelauncherSynchronizeWithParent(); + + // Figure out what to execute, what arguments to pass it, and whether to + // start it in the background. + bool in_relaunch_args = false; + bool seen_relaunch_executable = false; + std::string relaunch_executable; + std::vector relauncher_args; + std::vector launch_args; + for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { + const std::string& arg(argv[argv_index]); + if (!in_relaunch_args) { + if (arg == internal::kRelauncherArgSeparator) { + in_relaunch_args = true; + } else { + relauncher_args.push_back(arg); + } + } else { + if (!seen_relaunch_executable) { + // The first argument after kRelauncherBackgroundArg is the path to + // the executable file or .app bundle directory. The Launch Services + // interface wants this separate from the rest of the arguments. In + // the relaunched process, this path will still be visible at argv[0]. + relaunch_executable.assign(arg); + seen_relaunch_executable = true; + } else { + launch_args.push_back(arg); + } + } + } + + if (!seen_relaunch_executable) { + LOG(ERROR) << "nothing to relaunch"; + return 1; + } + + if (internal::LaunchProgram(relauncher_args, relaunch_executable, + launch_args) != 0) { + LOG(ERROR) << "failed to launch program"; + return 1; + } + + // The application should have relaunched (or is in the process of + // relaunching). From this point on, only clean-up tasks should occur, and + // failures are tolerable. + + return 0; +} + } // namespace relauncher diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index 4134ef54225..624a68eaf24 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -64,6 +64,9 @@ bool RelaunchAppWithHelper(const std::string& helper, const std::vector& relauncher_args, const std::vector& args); +// The entry point from ChromeMain into the relauncher process. +int RelauncherMain(const content::MainFunctionParams& main_parameters); + namespace internal { // The "magic" file descriptor that the relauncher process' write side of the @@ -91,8 +94,9 @@ extern const char* kRelauncherArgSeparator; // process and the best recovery approach is to attempt relaunch anyway. void RelauncherSynchronizeWithParent(); -// The entry point from ChromeMain into the relauncher process. -int RelauncherMain(const content::MainFunctionParams& main_parameters); +int LaunchProgram(const std::vector& relauncher_args, + const std::string& program, + const std::vector& argv); } // namespace internal diff --git a/atom/browser/relauncher_mac.cc b/atom/browser/relauncher_mac.cc index 39c478f1614..a537e311ce1 100644 --- a/atom/browser/relauncher_mac.cc +++ b/atom/browser/relauncher_mac.cc @@ -11,7 +11,6 @@ #include #include -#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/mac/mac_logging.h" @@ -91,16 +90,9 @@ void RelauncherSynchronizeWithParent() { } } -int RelauncherMain(const content::MainFunctionParams& main_parameters) { - const std::vector& argv = atom::AtomCommandLine::argv(); - - if (argv.size() < 4 || kRelauncherTypeArg != argv[1]) { - LOG(ERROR) << "relauncher process invoked with unexpected arguments"; - return 1; - } - - internal::RelauncherSynchronizeWithParent(); - +int LaunchProgram(const std::vector& relauncher_args, + const std::string& program, + const std::vector& argv) { // The capacity for relaunch_args is 4 less than argc, because it // won't contain the argv[0] of the relauncher process, the // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the @@ -112,50 +104,22 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { return 1; } - // Figure out what to execute, what arguments to pass it, and whether to - // start it in the background. - bool in_relaunch_args = false; - bool seen_relaunch_executable = false; - std::string relaunch_executable; - const std::string relauncher_arg_separator(kRelauncherArgSeparator); - for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { - const std::string& arg(argv[argv_index]); - + for (const std::string& arg : argv) { // Strip any -psn_ arguments, as they apply to a specific process. - if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) { + if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) continue; - } - if (!in_relaunch_args && arg == relauncher_arg_separator) { - in_relaunch_args = true; - } else { - if (!seen_relaunch_executable) { - // The first argument after kRelauncherBackgroundArg is the path to - // the executable file or .app bundle directory. The Launch Services - // interface wants this separate from the rest of the arguments. In - // the relaunched process, this path will still be visible at argv[0]. - relaunch_executable.assign(arg); - seen_relaunch_executable = true; - } else { - base::ScopedCFTypeRef arg_cf( - base::SysUTF8ToCFStringRef(arg)); - if (!arg_cf) { - LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; - return 1; - } - CFArrayAppendValue(relaunch_args, arg_cf); - } + base::ScopedCFTypeRef arg_cf(base::SysUTF8ToCFStringRef(arg)); + if (!arg_cf) { + LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; + return 1; } - } - - if (!seen_relaunch_executable) { - LOG(ERROR) << "nothing to relaunch"; - return 1; + CFArrayAppendValue(relaunch_args, arg_cf); } FSRef app_fsref; - if (!base::mac::FSRefFromPath(relaunch_executable, &app_fsref)) { - LOG(ERROR) << "base::mac::FSRefFromPath failed for " << relaunch_executable; + if (!base::mac::FSRefFromPath(program, &app_fsref)) { + LOG(ERROR) << "base::mac::FSRefFromPath failed for " << program; return 1; } @@ -175,10 +139,6 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { return 1; } - // The application should have relaunched (or is in the process of - // relaunching). From this point on, only clean-up tasks should occur, and - // failures are tolerable. - return 0; } From a3f39e9d0b1ffee1a299e2799948ca8dc445f052 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 16:54:21 +0900 Subject: [PATCH 1249/1265] Implement Relaunch on Linux --- atom/app/atom_main_delegate.cc | 2 + atom/app/atom_main_delegate.h | 2 + atom/browser/browser.cc | 12 ++++++ atom/browser/browser_mac.mm | 11 ----- atom/browser/relauncher.cc | 14 +++++- atom/browser/relauncher_linux.cc | 74 ++++++++++++++++++++++++++++++++ filenames.gypi | 1 + 7 files changed, 104 insertions(+), 12 deletions(-) create mode 100644 atom/browser/relauncher_linux.cc diff --git a/atom/app/atom_main_delegate.cc b/atom/app/atom_main_delegate.cc index dbd27123933..f4e0b604448 100644 --- a/atom/app/atom_main_delegate.cc +++ b/atom/app/atom_main_delegate.cc @@ -158,6 +158,7 @@ int AtomMainDelegate::RunProcess( return -1; } +#if defined(OS_MACOSX) bool AtomMainDelegate::ShouldSendMachPort(const std::string& process_type) { return process_type != kRelauncherProcess; } @@ -166,6 +167,7 @@ bool AtomMainDelegate::DelaySandboxInitialization( const std::string& process_type) { return process_type == kRelauncherProcess; } +#endif std::unique_ptr AtomMainDelegate::CreateContentClient() { diff --git a/atom/app/atom_main_delegate.h b/atom/app/atom_main_delegate.h index 377665f629d..58a380bd7d5 100644 --- a/atom/app/atom_main_delegate.h +++ b/atom/app/atom_main_delegate.h @@ -27,8 +27,10 @@ class AtomMainDelegate : public brightray::MainDelegate { int RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) override; +#if defined(OS_MACOSX) bool ShouldSendMachPort(const std::string& process_type) override; bool DelaySandboxInitialization(const std::string& process_type) override; +#endif // brightray::MainDelegate: std::unique_ptr CreateContentClient() override; diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 093209ef7c4..92da10bc5a6 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -8,6 +8,7 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" +#include "atom/browser/relauncher.h" #include "atom/browser/window_list.h" #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" @@ -33,6 +34,17 @@ Browser* Browser::Get() { return AtomBrowserMainParts::Get()->browser(); } +void Browser::Relaunch(const std::vector& args, + const std::string& app) { + base::FilePath exe_path; + PathService::Get(base::FILE_EXE, &exe_path); + + std::vector args_with_app(args); + args_with_app.insert(args_with_app.begin(), + app.empty() ? exe_path.value() : app); + relauncher::RelaunchApp(args_with_app); +} + void Browser::Quit() { if (is_quiting_) return; diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index 271b88de4ce..4561eab8c95 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -8,27 +8,16 @@ #include "atom/browser/mac/atom_application_delegate.h" #include "atom/browser/mac/dict_util.h" #include "atom/browser/native_window.h" -#include "atom/browser/relauncher.h" #include "atom/browser/window_list.h" #include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "brightray/common/application_info.h" -#include "brightray/common/mac/main_application_bundle.h" #include "net/base/mac/url_conversions.h" #include "url/gurl.h" namespace atom { -void Browser::Relaunch(const std::vector& args, - const std::string& app) { - std::vector args_with_app(args); - args_with_app.insert( - args_with_app.begin(), - app.empty() ? brightray::MainApplicationBundlePath().value() : app); - relauncher::RelaunchApp(args_with_app); -} - void Browser::Focus() { [[AtomApplication sharedApplication] activateIgnoringOtherApps:YES]; } diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 47c77a119ad..58c4d57df80 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -11,18 +11,24 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/posix/eintr_wrapper.h" #include "base/process/launch.h" #include "base/strings/stringprintf.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" +#if defined(OS_POSIX) +#include "base/posix/eintr_wrapper.h" +#endif + namespace relauncher { namespace internal { +#if defined(OS_POSIX) const int kRelauncherSyncFD = STDERR_FILENO + 1; +#endif + const char* kRelauncherTypeArg = "--type=relauncher"; const char* kRelauncherArgSeparator = "---"; @@ -59,6 +65,7 @@ bool RelaunchAppWithHelper(const std::string& helper, relaunch_args.insert(relaunch_args.end(), args.begin(), args.end()); +#if defined(OS_POSIX) int pipe_fds[2]; if (HANDLE_EINTR(pipe(pipe_fds)) != 0) { PLOG(ERROR) << "pipe"; @@ -85,9 +92,12 @@ bool RelaunchAppWithHelper(const std::string& helper, base::FileHandleMappingVector fd_map; fd_map.push_back( std::make_pair(pipe_write_fd.get(), internal::kRelauncherSyncFD)); +#endif base::LaunchOptions options; +#if defined(OS_POSIX) options.fds_to_remap = &fd_map; +#endif if (!base::LaunchProcess(relaunch_args, options).IsValid()) { LOG(ERROR) << "base::LaunchProcess failed"; return false; @@ -96,6 +106,7 @@ bool RelaunchAppWithHelper(const std::string& helper, // The relauncher process is now starting up, or has started up. The // original parent process continues. +#if defined(OS_POSIX) pipe_write_fd.reset(); // close(pipe_fds[1]); // Synchronize with the relauncher process. @@ -113,6 +124,7 @@ bool RelaunchAppWithHelper(const std::string& helper, // Since a byte has been successfully read from the relauncher process, it's // guaranteed to have set up its kqueue monitoring this process for exit. // It's safe to exit now. +#endif return true; } diff --git a/atom/browser/relauncher_linux.cc b/atom/browser/relauncher_linux.cc new file mode 100644 index 00000000000..7ad0c03cbd0 --- /dev/null +++ b/atom/browser/relauncher_linux.cc @@ -0,0 +1,74 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/relauncher.h" + +#include +#include +#include + +#include "atom/common/atom_command_line.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" +#include "base/process/launch.h" + +namespace relauncher { + +namespace internal { + +void RelauncherSynchronizeWithParent() { + base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); + + // Don't execute signal handlers of SIGUSR2. + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGUSR2); + if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { + PLOG(ERROR) << "sigprocmask"; + return; + } + + // Create a signalfd that watches for SIGUSR2. + int usr2_fd = signalfd(-1, &mask, 0); + if (usr2_fd < 0) { + PLOG(ERROR) << "signalfd"; + return; + } + + // Send SIGUSR2 to current process when parent process ends. + if (HANDLE_EINTR(prctl(PR_SET_PDEATHSIG, SIGUSR2)) != 0) { + PLOG(ERROR) << "prctl"; + return; + } + + // Write a '\0' character to the pipe. + if (HANDLE_EINTR(write(relauncher_sync_fd.get(), "", 1)) != 1) { + PLOG(ERROR) << "write"; + return; + } + + // Wait the SIGUSR2 signal to happen. + struct signalfd_siginfo si; + HANDLE_EINTR(read(usr2_fd, &si, sizeof(si))); +} + +int LaunchProgram(const std::vector& relauncher_args, + const std::string& program, + const std::vector& args) { + std::vector argv; + argv.reserve(1 + args.size()); + argv.push_back(program); + argv.insert(argv.end(), args.begin(), args.end()); + + base::LaunchOptions options; + options.allow_new_privs = true; + options.new_process_group = true; // detach + base::Process process = base::LaunchProcess(argv, options); + return process.IsValid() ? 0 : 1; +} + +} // namespace internal + +} // namespace relauncher diff --git a/filenames.gypi b/filenames.gypi index 3cee4ca50c5..0317aef6b10 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -225,6 +225,7 @@ 'atom/browser/net/url_request_fetch_job.h', 'atom/browser/node_debugger.cc', 'atom/browser/node_debugger.h', + 'atom/browser/relauncher_linux.cc', 'atom/browser/relauncher_mac.cc', 'atom/browser/relauncher.cc', 'atom/browser/relauncher.h', From 0646f6ea9e95295614f166ab6bfe55f4b00e5230 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 19:49:36 +0900 Subject: [PATCH 1250/1265] Implement Relaunch on Windows --- atom/app/atom_main.cc | 1 + atom/browser/browser.cc | 19 ++++---- atom/browser/browser.h | 5 +- atom/browser/relauncher.cc | 55 ++++++++++++++-------- atom/browser/relauncher.h | 36 +++++++++++---- atom/browser/relauncher_linux.cc | 1 - atom/browser/relauncher_win.cc | 78 ++++++++++++++++++++++++++++++++ atom/common/atom_command_line.cc | 14 ++++++ atom/common/atom_command_line.h | 9 ++++ filenames.gypi | 1 + 10 files changed, 179 insertions(+), 40 deletions(-) create mode 100644 atom/browser/relauncher_win.cc diff --git a/atom/app/atom_main.cc b/atom/app/atom_main.cc index 1e69ba4ba83..a3e70270026 100644 --- a/atom/app/atom_main.cc +++ b/atom/app/atom_main.cc @@ -111,6 +111,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { params.instance = instance; params.sandbox_info = &sandbox_info; atom::AtomCommandLine::Init(argc, argv); + atom::AtomCommandLine::InitW(argc, wargv); return content::ContentMain(params); } diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 92da10bc5a6..88eeaab986c 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -8,7 +8,6 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" -#include "atom/browser/relauncher.h" #include "atom/browser/window_list.h" #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" @@ -34,15 +33,15 @@ Browser* Browser::Get() { return AtomBrowserMainParts::Get()->browser(); } -void Browser::Relaunch(const std::vector& args, - const std::string& app) { - base::FilePath exe_path; - PathService::Get(base::FILE_EXE, &exe_path); - - std::vector args_with_app(args); - args_with_app.insert(args_with_app.begin(), - app.empty() ? exe_path.value() : app); - relauncher::RelaunchApp(args_with_app); +bool Browser::Relaunch(const base::FilePath& app, + const relauncher::StringVector& args) { + if (app.empty()) { + base::FilePath exe_path; + PathService::Get(base::FILE_EXE, &exe_path); + return relauncher::RelaunchApp(exe_path, args); + } else { + return relauncher::RelaunchApp(app, args); + } } void Browser::Quit() { diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 2b446d621fd..018709ff404 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -13,6 +13,7 @@ #include "base/observer_list.h" #include "base/strings/string16.h" #include "atom/browser/browser_observer.h" +#include "atom/browser/relauncher.h" #include "atom/browser/window_list_observer.h" #include "native_mate/arguments.h" @@ -54,8 +55,8 @@ class Browser : public WindowListObserver { void Shutdown(); // Restart the app. - void Relaunch(const std::vector& args, - const std::string& app); + bool Relaunch(const base::FilePath& app, + const relauncher::StringVector& args); // Focus the application. void Focus(); diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 58c4d57df80..557725e6af7 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -12,7 +12,7 @@ #include "base/logging.h" #include "base/path_service.h" #include "base/process/launch.h" -#include "base/strings/stringprintf.h" +#include "base/strings/string_util.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" @@ -29,12 +29,13 @@ namespace internal { const int kRelauncherSyncFD = STDERR_FILENO + 1; #endif -const char* kRelauncherTypeArg = "--type=relauncher"; -const char* kRelauncherArgSeparator = "---"; +const CharType* kRelauncherTypeArg = FILE_PATH_LITERAL("--type=relauncher"); +const CharType* kRelauncherArgSeparator = FILE_PATH_LITERAL("---"); } // namespace internal -bool RelaunchApp(const std::vector& args) { +bool RelaunchApp(const base::FilePath& app, + const StringVector& args) { // Use the currently-running application's helper process. The automatic // update feature is careful to leave the currently-running version alone, // so this is safe even if the relaunch is the result of an update having @@ -47,15 +48,16 @@ bool RelaunchApp(const std::vector& args) { return false; } - std::vector relauncher_args; - return RelaunchAppWithHelper(child_path.value(), relauncher_args, args); + StringVector relauncher_args; + return RelaunchAppWithHelper(app, child_path, relauncher_args, args); } -bool RelaunchAppWithHelper(const std::string& helper, - const std::vector& relauncher_args, - const std::vector& args) { - std::vector relaunch_args; - relaunch_args.push_back(helper); +bool RelaunchAppWithHelper(const base::FilePath& app, + const base::FilePath& helper, + const StringVector& relauncher_args, + const StringVector& args) { + StringVector relaunch_args; + relaunch_args.push_back(helper.value()); relaunch_args.push_back(internal::kRelauncherTypeArg); relaunch_args.insert(relaunch_args.end(), @@ -63,6 +65,7 @@ bool RelaunchAppWithHelper(const std::string& helper, relaunch_args.push_back(internal::kRelauncherArgSeparator); + relaunch_args.push_back(app.value()); relaunch_args.insert(relaunch_args.end(), args.begin(), args.end()); #if defined(OS_POSIX) @@ -97,8 +100,12 @@ bool RelaunchAppWithHelper(const std::string& helper, base::LaunchOptions options; #if defined(OS_POSIX) options.fds_to_remap = &fd_map; + base::Process process = base::LaunchProcess(relaunch_args, options); +#elif defined(OS_WIN) + base::Process process = base::LaunchProcess( + base::JoinString(relaunch_args, L" "), options); #endif - if (!base::LaunchProcess(relaunch_args, options).IsValid()) { + if (!process.IsValid()) { LOG(ERROR) << "base::LaunchProcess failed"; return false; } @@ -106,7 +113,15 @@ bool RelaunchAppWithHelper(const std::string& helper, // The relauncher process is now starting up, or has started up. The // original parent process continues. -#if defined(OS_POSIX) +#if defined(OS_WIN) + // Synchronize with the relauncher process. + StringType name = internal::GetWaitEventName(process.Pid()); + HANDLE wait_event = ::CreateEventW(NULL, TRUE, FALSE, name.c_str()); + if (wait_event != NULL) { + WaitForSingleObject(wait_event, 1000); + CloseHandle(wait_event); + } +#elif defined(OS_POSIX) pipe_write_fd.reset(); // close(pipe_fds[1]); // Synchronize with the relauncher process. @@ -129,7 +144,11 @@ bool RelaunchAppWithHelper(const std::string& helper, } int RelauncherMain(const content::MainFunctionParams& main_parameters) { - const std::vector& argv = atom::AtomCommandLine::argv(); +#if defined(OS_WIN) + const StringVector& argv = atom::AtomCommandLine::wargv(); +#else + const StringVector& argv = atom::AtomCommandLine::argv(); +#endif if (argv.size() < 4 || argv[1] != internal::kRelauncherTypeArg) { LOG(ERROR) << "relauncher process invoked with unexpected arguments"; @@ -142,11 +161,11 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // start it in the background. bool in_relaunch_args = false; bool seen_relaunch_executable = false; - std::string relaunch_executable; - std::vector relauncher_args; - std::vector launch_args; + StringType relaunch_executable; + StringVector relauncher_args; + StringVector launch_args; for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { - const std::string& arg(argv[argv_index]); + const StringType& arg(argv[argv_index]); if (!in_relaunch_args) { if (arg == internal::kRelauncherArgSeparator) { in_relaunch_args = true; diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index 624a68eaf24..6b725263f8b 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -32,12 +32,22 @@ #include #include +#include "base/command_line.h" + +#if defined(OS_WIN) +#include "base/process/process_handle.h" +#endif + namespace content { struct MainFunctionParams; } namespace relauncher { +using CharType = base::CommandLine::CharType; +using StringType = base::CommandLine::StringType; +using StringVector = base::CommandLine::StringVector; + // Relaunches the application using the helper application associated with the // currently running instance of Chrome in the parent browser process as the // executable for the relauncher process. |args| is an argv-style vector of @@ -49,7 +59,8 @@ namespace relauncher { // successfully. Returns true on success, although some failures can occur // after this function returns true if, for example, they occur within the // relauncher process. Returns false when the relaunch definitely failed. -bool RelaunchApp(const std::vector& args); +bool RelaunchApp(const base::FilePath& app, + const StringVector& args); // Identical to RelaunchApp, but uses |helper| as the path to the relauncher // process, and allows additional arguments to be supplied to the relauncher @@ -60,22 +71,25 @@ bool RelaunchApp(const std::vector& args); // able to communicate with one another. This variant can be useful to // relaunch the same version of Chrome from another location, using that // location's helper. -bool RelaunchAppWithHelper(const std::string& helper, - const std::vector& relauncher_args, - const std::vector& args); +bool RelaunchAppWithHelper(const base::FilePath& app, + const base::FilePath& helper, + const StringVector& relauncher_args, + const StringVector& args); // The entry point from ChromeMain into the relauncher process. int RelauncherMain(const content::MainFunctionParams& main_parameters); namespace internal { +#if defined(OS_POSIX) // The "magic" file descriptor that the relauncher process' write side of the // pipe shows up on. Chosen to avoid conflicting with stdin, stdout, and // stderr. extern const int kRelauncherSyncFD; +#endif // The "type" argument identifying a relauncher process ("--type=relauncher"). -extern const char* kRelauncherTypeArg; +extern const CharType* kRelauncherTypeArg; // The argument separating arguments intended for the relauncher process from // those intended for the relaunched process. "---" is chosen instead of "--" @@ -84,7 +98,11 @@ extern const char* kRelauncherTypeArg; // arguments intended for the relaunched process, to get the correct settings // for such things as logging and the user-data-dir in case it affects crash // reporting. -extern const char* kRelauncherArgSeparator; +extern const CharType* kRelauncherArgSeparator; + +#if defined(OS_WIN) +StringType GetWaitEventName(base::ProcessId pid); +#endif // In the relauncher process, performs the necessary synchronization steps // with the parent by setting up a kqueue to watch for it to exit, writing a @@ -94,9 +112,9 @@ extern const char* kRelauncherArgSeparator; // process and the best recovery approach is to attempt relaunch anyway. void RelauncherSynchronizeWithParent(); -int LaunchProgram(const std::vector& relauncher_args, - const std::string& program, - const std::vector& argv); +int LaunchProgram(const StringVector& relauncher_args, + const StringType& program, + const StringVector& argv); } // namespace internal diff --git a/atom/browser/relauncher_linux.cc b/atom/browser/relauncher_linux.cc index 7ad0c03cbd0..8a3c3050df5 100644 --- a/atom/browser/relauncher_linux.cc +++ b/atom/browser/relauncher_linux.cc @@ -8,7 +8,6 @@ #include #include -#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/posix/eintr_wrapper.h" diff --git a/atom/browser/relauncher_win.cc b/atom/browser/relauncher_win.cc new file mode 100644 index 00000000000..4c31466eb69 --- /dev/null +++ b/atom/browser/relauncher_win.cc @@ -0,0 +1,78 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/relauncher.h" + +#include + +#include "base/process/launch.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/win/scoped_handle.h" +#include "sandbox/win/src/nt_internals.h" +#include "sandbox/win/src/win_utils.h" +#include "ui/base/win/shell.h" + +namespace relauncher { + +namespace internal { + +namespace { + +const CharType* kWaitEventName = L"ElectronRelauncherWaitEvent"; + +HANDLE GetParentProcessHandle(base::ProcessHandle handle) { + NtQueryInformationProcessFunction NtQueryInformationProcess = nullptr; + ResolveNTFunctionPtr("NtQueryInformationProcess", &NtQueryInformationProcess); + if (!NtQueryInformationProcess) { + LOG(ERROR) << "Unable to get NtQueryInformationProcess"; + return NULL; + } + + PROCESS_BASIC_INFORMATION pbi; + LONG status = NtQueryInformationProcess( + handle, ProcessBasicInformation, + &pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL); + if (!NT_SUCCESS(status)) { + LOG(ERROR) << "NtQueryInformationProcess failed"; + return NULL; + } + + return ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, + pbi.InheritedFromUniqueProcessId); +} + +} // namespace + +StringType GetWaitEventName(base::ProcessId pid) { + return base::StringPrintf(L"%s-%d", kWaitEventName, static_cast(pid)); +} + +void RelauncherSynchronizeWithParent() { + base::Process process = base::Process::Current(); + base::win::ScopedHandle parent_process( + GetParentProcessHandle(process.Handle())); + + // Notify the parent process that it can quit now. + StringType name = internal::GetWaitEventName(process.Pid()); + base::win::ScopedHandle wait_event( + ::CreateEventW(NULL, TRUE, FALSE, name.c_str())); + ::SetEvent(wait_event.Get()); + + // Wait for parent process to quit. + WaitForSingleObject(parent_process.Get(), INFINITE); +} + +int LaunchProgram(const StringVector& relauncher_args, + const StringType& program, + const StringVector& args) { + base::LaunchOptions options; + base::Process process = base::LaunchProcess( + program + L" " + base::JoinString(args, L" "), options); + return process.IsValid() ? 0 : 1; +} + +} // namespace internal + +} // namespace relauncher diff --git a/atom/common/atom_command_line.cc b/atom/common/atom_command_line.cc index 2ac62385aea..08880ffe4a3 100644 --- a/atom/common/atom_command_line.cc +++ b/atom/common/atom_command_line.cc @@ -12,6 +12,11 @@ namespace atom { // static std::vector AtomCommandLine::argv_; +#if defined(OS_WIN) +// static +std::vector AtomCommandLine::wargv_; +#endif + // static void AtomCommandLine::Init(int argc, const char* const* argv) { // Hack around with the argv pointer. Used for process.title = "blah" @@ -21,6 +26,15 @@ void AtomCommandLine::Init(int argc, const char* const* argv) { } } +#if defined(OS_WIN) +// static +void AtomCommandLine::InitW(int argc, const wchar_t* const* argv) { + for (int i = 0; i < argc; ++i) { + wargv_.push_back(argv[i]); + } +} +#endif + #if defined(OS_LINUX) // static void AtomCommandLine::InitializeFromCommandLine() { diff --git a/atom/common/atom_command_line.h b/atom/common/atom_command_line.h index b5915533a41..a834ce92566 100644 --- a/atom/common/atom_command_line.h +++ b/atom/common/atom_command_line.h @@ -19,6 +19,11 @@ class AtomCommandLine { static void Init(int argc, const char* const* argv); static std::vector argv() { return argv_; } +#if defined(OS_WIN) + static void InitW(int argc, const wchar_t* const* argv); + static std::vector wargv() { return wargv_; } +#endif + #if defined(OS_LINUX) // On Linux the command line has to be read from base::CommandLine since // it is using zygote. @@ -28,6 +33,10 @@ class AtomCommandLine { private: static std::vector argv_; +#if defined(OS_WIN) + static std::vector wargv_; +#endif + DISALLOW_IMPLICIT_CONSTRUCTORS(AtomCommandLine); }; diff --git a/filenames.gypi b/filenames.gypi index 0317aef6b10..5f1fdc3b141 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -227,6 +227,7 @@ 'atom/browser/node_debugger.h', 'atom/browser/relauncher_linux.cc', 'atom/browser/relauncher_mac.cc', + 'atom/browser/relauncher_win.cc', 'atom/browser/relauncher.cc', 'atom/browser/relauncher.h', 'atom/browser/render_process_preferences.cc', From 0d066de53e5a256422c575e762788667db441f86 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 20:32:29 +0900 Subject: [PATCH 1251/1265] Make sure the new instance inherite cwd on mac --- atom/browser/relauncher.cc | 22 +++------- atom/browser/relauncher.h | 4 +- atom/browser/relauncher_linux.cc | 10 +---- atom/browser/relauncher_mac.cc | 71 ++++---------------------------- atom/browser/relauncher_win.cc | 7 ++-- 5 files changed, 18 insertions(+), 96 deletions(-) diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 557725e6af7..dce4f46b9a7 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -34,8 +34,7 @@ const CharType* kRelauncherArgSeparator = FILE_PATH_LITERAL("---"); } // namespace internal -bool RelaunchApp(const base::FilePath& app, - const StringVector& args) { +bool RelaunchApp(const base::FilePath& app, const StringVector& args) { // Use the currently-running application's helper process. The automatic // update feature is careful to leave the currently-running version alone, // so this is safe even if the relaunch is the result of an update having @@ -160,10 +159,9 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // Figure out what to execute, what arguments to pass it, and whether to // start it in the background. bool in_relaunch_args = false; - bool seen_relaunch_executable = false; StringType relaunch_executable; StringVector relauncher_args; - StringVector launch_args; + StringVector launch_argv; for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { const StringType& arg(argv[argv_index]); if (!in_relaunch_args) { @@ -173,26 +171,16 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { relauncher_args.push_back(arg); } } else { - if (!seen_relaunch_executable) { - // The first argument after kRelauncherBackgroundArg is the path to - // the executable file or .app bundle directory. The Launch Services - // interface wants this separate from the rest of the arguments. In - // the relaunched process, this path will still be visible at argv[0]. - relaunch_executable.assign(arg); - seen_relaunch_executable = true; - } else { - launch_args.push_back(arg); - } + launch_argv.push_back(arg); } } - if (!seen_relaunch_executable) { + if (launch_argv.empty()) { LOG(ERROR) << "nothing to relaunch"; return 1; } - if (internal::LaunchProgram(relauncher_args, relaunch_executable, - launch_args) != 0) { + if (internal::LaunchProgram(relauncher_args, launch_argv) != 0) { LOG(ERROR) << "failed to launch program"; return 1; } diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index 6b725263f8b..f6722f946d2 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -59,8 +59,7 @@ using StringVector = base::CommandLine::StringVector; // successfully. Returns true on success, although some failures can occur // after this function returns true if, for example, they occur within the // relauncher process. Returns false when the relaunch definitely failed. -bool RelaunchApp(const base::FilePath& app, - const StringVector& args); +bool RelaunchApp(const base::FilePath& app, const StringVector& args); // Identical to RelaunchApp, but uses |helper| as the path to the relauncher // process, and allows additional arguments to be supplied to the relauncher @@ -113,7 +112,6 @@ StringType GetWaitEventName(base::ProcessId pid); void RelauncherSynchronizeWithParent(); int LaunchProgram(const StringVector& relauncher_args, - const StringType& program, const StringVector& argv); } // namespace internal diff --git a/atom/browser/relauncher_linux.cc b/atom/browser/relauncher_linux.cc index 8a3c3050df5..2fbbd47faf0 100644 --- a/atom/browser/relauncher_linux.cc +++ b/atom/browser/relauncher_linux.cc @@ -53,14 +53,8 @@ void RelauncherSynchronizeWithParent() { HANDLE_EINTR(read(usr2_fd, &si, sizeof(si))); } -int LaunchProgram(const std::vector& relauncher_args, - const std::string& program, - const std::vector& args) { - std::vector argv; - argv.reserve(1 + args.size()); - argv.push_back(program); - argv.insert(argv.end(), args.begin(), args.end()); - +int LaunchProgram(const StringVector& relauncher_args, + const StringVector& argv) { base::LaunchOptions options; options.allow_new_privs = true; options.new_process_group = true; // detach diff --git a/atom/browser/relauncher_mac.cc b/atom/browser/relauncher_mac.cc index a537e311ce1..ef26f8441df 100644 --- a/atom/browser/relauncher_mac.cc +++ b/atom/browser/relauncher_mac.cc @@ -4,8 +4,6 @@ #include "atom/browser/relauncher.h" -#include - #include #include #include @@ -13,9 +11,8 @@ #include "base/files/file_util.h" #include "base/logging.h" +#include "base/process/launch.h" #include "base/mac/mac_logging.h" -#include "base/mac/mac_util.h" -#include "base/mac/scoped_cftyperef.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/sys_string_conversions.h" @@ -23,16 +20,6 @@ namespace relauncher { namespace internal { -namespace { - -// The beginning of the "process serial number" argument that Launch Services -// sometimes inserts into command lines. A process serial number is only valid -// for a single process, so any PSN arguments will be stripped from command -// lines during relaunch to avoid confusion. -const char kPSNArg[] = "-psn_"; - -} // namespace - void RelauncherSynchronizeWithParent() { base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD); @@ -90,56 +77,12 @@ void RelauncherSynchronizeWithParent() { } } -int LaunchProgram(const std::vector& relauncher_args, - const std::string& program, - const std::vector& argv) { - // The capacity for relaunch_args is 4 less than argc, because it - // won't contain the argv[0] of the relauncher process, the - // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the - // executable path of the process to be launched. - base::ScopedCFTypeRef relaunch_args( - CFArrayCreateMutable(NULL, argv.size() - 4, &kCFTypeArrayCallBacks)); - if (!relaunch_args) { - LOG(ERROR) << "CFArrayCreateMutable"; - return 1; - } - - for (const std::string& arg : argv) { - // Strip any -psn_ arguments, as they apply to a specific process. - if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) - continue; - - base::ScopedCFTypeRef arg_cf(base::SysUTF8ToCFStringRef(arg)); - if (!arg_cf) { - LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg; - return 1; - } - CFArrayAppendValue(relaunch_args, arg_cf); - } - - FSRef app_fsref; - if (!base::mac::FSRefFromPath(program, &app_fsref)) { - LOG(ERROR) << "base::mac::FSRefFromPath failed for " << program; - return 1; - } - - LSApplicationParameters ls_parameters = { - 0, // version - kLSLaunchDefaults | kLSLaunchAndDisplayErrors | kLSLaunchNewInstance, - &app_fsref, - NULL, // asyncLaunchRefCon - NULL, // environment - relaunch_args, - NULL // initialEvent - }; - - OSStatus status = LSOpenApplication(&ls_parameters, NULL); - if (status != noErr) { - OSSTATUS_LOG(ERROR, status) << "LSOpenApplication"; - return 1; - } - - return 0; +int LaunchProgram(const StringVector& relauncher_args, + const StringVector& argv) { + base::LaunchOptions options; + options.new_process_group = true; // detach + base::Process process = base::LaunchProcess(argv, options); + return process.IsValid() ? 0 : 1; } } // namespace internal diff --git a/atom/browser/relauncher_win.cc b/atom/browser/relauncher_win.cc index 4c31466eb69..bb7617f29cb 100644 --- a/atom/browser/relauncher_win.cc +++ b/atom/browser/relauncher_win.cc @@ -65,11 +65,10 @@ void RelauncherSynchronizeWithParent() { } int LaunchProgram(const StringVector& relauncher_args, - const StringType& program, - const StringVector& args) { + const StringVector& argv) { base::LaunchOptions options; - base::Process process = base::LaunchProcess( - program + L" " + base::JoinString(args, L" "), options); + base::Process process = + base::LaunchProcess(base::JoinString(args, L" "), options); return process.IsValid() ? 0 : 1; } From 9a08cbce274a0b08062a8cc1a81b4e07f4bffe81 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 20:41:59 +0900 Subject: [PATCH 1252/1265] Uniform when to use args or argv --- atom/browser/browser.cc | 8 ++++++-- atom/browser/relauncher.cc | 32 +++++++++++++++----------------- atom/browser/relauncher.h | 5 ++--- atom/browser/relauncher_win.cc | 2 +- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 88eeaab986c..41d4ae5754d 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -9,6 +9,7 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" +#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" @@ -35,13 +36,16 @@ Browser* Browser::Get() { bool Browser::Relaunch(const base::FilePath& app, const relauncher::StringVector& args) { + relauncher::StringVector argv; if (app.empty()) { base::FilePath exe_path; PathService::Get(base::FILE_EXE, &exe_path); - return relauncher::RelaunchApp(exe_path, args); + argv.push_back(exe_path.value()); } else { - return relauncher::RelaunchApp(app, args); + argv.push_back(app.value()); } + + return relauncher::RelaunchApp(argv); } void Browser::Quit() { diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index dce4f46b9a7..5362a7b78ae 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -34,7 +34,7 @@ const CharType* kRelauncherArgSeparator = FILE_PATH_LITERAL("---"); } // namespace internal -bool RelaunchApp(const base::FilePath& app, const StringVector& args) { +bool RelaunchApp(const StringVector& argv) { // Use the currently-running application's helper process. The automatic // update feature is careful to leave the currently-running version alone, // so this is safe even if the relaunch is the result of an update having @@ -48,24 +48,22 @@ bool RelaunchApp(const base::FilePath& app, const StringVector& args) { } StringVector relauncher_args; - return RelaunchAppWithHelper(app, child_path, relauncher_args, args); + return RelaunchAppWithHelper(child_path, relauncher_args, argv); } -bool RelaunchAppWithHelper(const base::FilePath& app, - const base::FilePath& helper, +bool RelaunchAppWithHelper(const base::FilePath& helper, const StringVector& relauncher_args, - const StringVector& args) { - StringVector relaunch_args; - relaunch_args.push_back(helper.value()); - relaunch_args.push_back(internal::kRelauncherTypeArg); + const StringVector& argv) { + StringVector relaunch_argv; + relaunch_argv.push_back(helper.value()); + relaunch_argv.push_back(internal::kRelauncherTypeArg); - relaunch_args.insert(relaunch_args.end(), + relaunch_argv.insert(relaunch_argv.end(), relauncher_args.begin(), relauncher_args.end()); - relaunch_args.push_back(internal::kRelauncherArgSeparator); + relaunch_argv.push_back(internal::kRelauncherArgSeparator); - relaunch_args.push_back(app.value()); - relaunch_args.insert(relaunch_args.end(), args.begin(), args.end()); + relaunch_argv.insert(relaunch_argv.end(), argv.begin(), argv.end()); #if defined(OS_POSIX) int pipe_fds[2]; @@ -99,10 +97,10 @@ bool RelaunchAppWithHelper(const base::FilePath& app, base::LaunchOptions options; #if defined(OS_POSIX) options.fds_to_remap = &fd_map; - base::Process process = base::LaunchProcess(relaunch_args, options); + base::Process process = base::LaunchProcess(relaunch_argv, options); #elif defined(OS_WIN) base::Process process = base::LaunchProcess( - base::JoinString(relaunch_args, L" "), options); + base::JoinString(relaunch_argv, L" "), options); #endif if (!process.IsValid()) { LOG(ERROR) << "base::LaunchProcess failed"; @@ -158,15 +156,15 @@ int RelauncherMain(const content::MainFunctionParams& main_parameters) { // Figure out what to execute, what arguments to pass it, and whether to // start it in the background. - bool in_relaunch_args = false; + bool in_relauncher_args = false; StringType relaunch_executable; StringVector relauncher_args; StringVector launch_argv; for (size_t argv_index = 2; argv_index < argv.size(); ++argv_index) { const StringType& arg(argv[argv_index]); - if (!in_relaunch_args) { + if (!in_relauncher_args) { if (arg == internal::kRelauncherArgSeparator) { - in_relaunch_args = true; + in_relauncher_args = true; } else { relauncher_args.push_back(arg); } diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index f6722f946d2..c19557b330c 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -59,7 +59,7 @@ using StringVector = base::CommandLine::StringVector; // successfully. Returns true on success, although some failures can occur // after this function returns true if, for example, they occur within the // relauncher process. Returns false when the relaunch definitely failed. -bool RelaunchApp(const base::FilePath& app, const StringVector& args); +bool RelaunchApp(const StringVector& argv); // Identical to RelaunchApp, but uses |helper| as the path to the relauncher // process, and allows additional arguments to be supplied to the relauncher @@ -70,8 +70,7 @@ bool RelaunchApp(const base::FilePath& app, const StringVector& args); // able to communicate with one another. This variant can be useful to // relaunch the same version of Chrome from another location, using that // location's helper. -bool RelaunchAppWithHelper(const base::FilePath& app, - const base::FilePath& helper, +bool RelaunchAppWithHelper(const base::FilePath& helper, const StringVector& relauncher_args, const StringVector& args); diff --git a/atom/browser/relauncher_win.cc b/atom/browser/relauncher_win.cc index bb7617f29cb..a759e7c2fff 100644 --- a/atom/browser/relauncher_win.cc +++ b/atom/browser/relauncher_win.cc @@ -68,7 +68,7 @@ int LaunchProgram(const StringVector& relauncher_args, const StringVector& argv) { base::LaunchOptions options; base::Process process = - base::LaunchProcess(base::JoinString(args, L" "), options); + base::LaunchProcess(base::JoinString(argv, L" "), options); return process.IsValid() ? 0 : 1; } From 8435f1c900bb482b2daa9e995d7f91db16b69053 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 20:47:47 +0900 Subject: [PATCH 1253/1265] Allow using current argv for relaunch --- atom/browser/browser.cc | 16 +++++++++++++++- atom/browser/browser.h | 3 ++- atom/browser/relauncher_win.cc | 2 +- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 41d4ae5754d..14aebf3db58 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -34,9 +34,21 @@ Browser* Browser::Get() { return AtomBrowserMainParts::Get()->browser(); } -bool Browser::Relaunch(const base::FilePath& app, +bool Browser::Relaunch(bool override_argv, + const base::FilePath& app, const relauncher::StringVector& args) { + if (!override_argv) { +#if defined(OS_WIN) + const relauncher::StringVector& argv = atom::AtomCommandLine::wargv(); +#else + const relauncher::StringVector& argv = atom::AtomCommandLine::argv(); +#endif + return relauncher::RelaunchApp(argv); + } + relauncher::StringVector argv; + argv.reserve(1 + args.size()); + if (app.empty()) { base::FilePath exe_path; PathService::Get(base::FILE_EXE, &exe_path); @@ -45,6 +57,8 @@ bool Browser::Relaunch(const base::FilePath& app, argv.push_back(app.value()); } + argv.insert(argv.end(), args.begin(), args.end()); + return relauncher::RelaunchApp(argv); } diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 018709ff404..05248a1e943 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -55,7 +55,8 @@ class Browser : public WindowListObserver { void Shutdown(); // Restart the app. - bool Relaunch(const base::FilePath& app, + bool Relaunch(bool override_argv, + const base::FilePath& app, const relauncher::StringVector& args); // Focus the application. diff --git a/atom/browser/relauncher_win.cc b/atom/browser/relauncher_win.cc index a759e7c2fff..1a122782a24 100644 --- a/atom/browser/relauncher_win.cc +++ b/atom/browser/relauncher_win.cc @@ -31,7 +31,7 @@ HANDLE GetParentProcessHandle(base::ProcessHandle handle) { } PROCESS_BASIC_INFORMATION pbi; - LONG status = NtQueryInformationProcess( + LONG status = NtQueryInformationProcess( handle, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL); if (!NT_SUCCESS(status)) { From 3de41fb22d7c93063162fb1595716274ce4eb25e Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 21:10:39 +0900 Subject: [PATCH 1254/1265] Correctly quotes the argv on Windows --- atom/browser/relauncher.cc | 3 +- atom/browser/relauncher.h | 2 ++ atom/browser/relauncher_win.cc | 55 ++++++++++++++++++++++++++++++++-- 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/atom/browser/relauncher.cc b/atom/browser/relauncher.cc index 5362a7b78ae..9610d80693b 100644 --- a/atom/browser/relauncher.cc +++ b/atom/browser/relauncher.cc @@ -12,7 +12,6 @@ #include "base/logging.h" #include "base/path_service.h" #include "base/process/launch.h" -#include "base/strings/string_util.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" @@ -100,7 +99,7 @@ bool RelaunchAppWithHelper(const base::FilePath& helper, base::Process process = base::LaunchProcess(relaunch_argv, options); #elif defined(OS_WIN) base::Process process = base::LaunchProcess( - base::JoinString(relaunch_argv, L" "), options); + internal::ArgvToCommandLineString(relaunch_argv), options); #endif if (!process.IsValid()) { LOG(ERROR) << "base::LaunchProcess failed"; diff --git a/atom/browser/relauncher.h b/atom/browser/relauncher.h index c19557b330c..10f2e512879 100644 --- a/atom/browser/relauncher.h +++ b/atom/browser/relauncher.h @@ -100,6 +100,8 @@ extern const CharType* kRelauncherArgSeparator; #if defined(OS_WIN) StringType GetWaitEventName(base::ProcessId pid); + +StringType ArgvToCommandLineString(const StringVector& argv); #endif // In the relauncher process, performs the necessary synchronization steps diff --git a/atom/browser/relauncher_win.cc b/atom/browser/relauncher_win.cc index 1a122782a24..1aebb515ecf 100644 --- a/atom/browser/relauncher_win.cc +++ b/atom/browser/relauncher_win.cc @@ -7,7 +7,6 @@ #include #include "base/process/launch.h" -#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/win/scoped_handle.h" #include "sandbox/win/src/nt_internals.h" @@ -43,12 +42,64 @@ HANDLE GetParentProcessHandle(base::ProcessHandle handle) { pbi.InheritedFromUniqueProcessId); } +StringType AddQuoteForArg(const StringType& arg) { + // We follow the quoting rules of CommandLineToArgvW. + // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx + std::wstring quotable_chars(L" \\\""); + if (arg.find_first_of(quotable_chars) == std::wstring::npos) { + // No quoting necessary. + return arg; + } + + std::wstring out; + out.push_back(L'"'); + for (size_t i = 0; i < arg.size(); ++i) { + if (arg[i] == '\\') { + // Find the extent of this run of backslashes. + size_t start = i, end = start + 1; + for (; end < arg.size() && arg[end] == '\\'; ++end) {} + size_t backslash_count = end - start; + + // Backslashes are escapes only if the run is followed by a double quote. + // Since we also will end the string with a double quote, we escape for + // either a double quote or the end of the string. + if (end == arg.size() || arg[end] == '"') { + // To quote, we need to output 2x as many backslashes. + backslash_count *= 2; + } + for (size_t j = 0; j < backslash_count; ++j) + out.push_back('\\'); + + // Advance i to one before the end to balance i++ in loop. + i = end - 1; + } else if (arg[i] == '"') { + out.push_back('\\'); + out.push_back('"'); + } else { + out.push_back(arg[i]); + } + } + out.push_back('"'); + + return out; +} + } // namespace StringType GetWaitEventName(base::ProcessId pid) { return base::StringPrintf(L"%s-%d", kWaitEventName, static_cast(pid)); } +StringType ArgvToCommandLineString(const StringVector& argv) { + StringType command_line; + for (const StringType& arg : argv) { + if (!command_line.empty()) + command_line += L' '; + command_line += AddQuoteForArg(arg); + } + return command_line; +} + void RelauncherSynchronizeWithParent() { base::Process process = base::Process::Current(); base::win::ScopedHandle parent_process( @@ -68,7 +119,7 @@ int LaunchProgram(const StringVector& relauncher_args, const StringVector& argv) { base::LaunchOptions options; base::Process process = - base::LaunchProcess(base::JoinString(argv, L" "), options); + base::LaunchProcess(ArgvToCommandLineString(argv), options); return process.IsValid() ? 0 : 1; } From 91a9e67dcaf740db59f7f763c80c0170058b14fc Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 21:49:29 +0900 Subject: [PATCH 1255/1265] Provide a flexible API for app.relaunch --- atom/browser/api/atom_api_app.cc | 43 ++++++++++++++++++++++++++++++-- atom/browser/api/atom_api_app.h | 3 ++- atom/browser/browser.cc | 29 --------------------- atom/browser/browser.h | 6 ----- 4 files changed, 43 insertions(+), 38 deletions(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index c5bce573ddf..76fbdb1859b 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -14,6 +14,8 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/browser.h" #include "atom/browser/login_handler.h" +#include "atom/browser/relauncher.h" +#include "atom/common/atom_command_line.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" @@ -408,6 +410,43 @@ void App::ReleaseSingleInstance() { } } +bool App::Relaunch(mate::Arguments* js_args) { + // Parse parameters. + bool override_argv = false; + base::FilePath exec_path; + relauncher::StringVector args; + + mate::Dictionary options; + if (js_args->GetNext(&options)) { + if (options.Get("execPath", &exec_path) || options.Get("args", &args)) + override_argv = true; + } + + if (!override_argv) { +#if defined(OS_WIN) + const relauncher::StringVector& argv = atom::AtomCommandLine::wargv(); +#else + const relauncher::StringVector& argv = atom::AtomCommandLine::argv(); +#endif + return relauncher::RelaunchApp(argv); + } + + relauncher::StringVector argv; + argv.reserve(1 + args.size()); + + if (exec_path.empty()) { + base::FilePath current_exe_path; + PathService::Get(base::FILE_EXE, ¤t_exe_path); + argv.push_back(current_exe_path.value()); + } else { + argv.push_back(exec_path.value()); + } + + argv.insert(argv.end(), args.begin(), args.end()); + + return relauncher::RelaunchApp(argv); +} + #if defined(USE_NSS_CERTS) void App::ImportCertificate( const base::DictionaryValue& options, @@ -450,7 +489,6 @@ void App::BuildPrototype( mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("quit", base::Bind(&Browser::Quit, browser)) .SetMethod("exit", base::Bind(&Browser::Exit, browser)) - .SetMethod("relaunch", base::Bind(&Browser::Relaunch, browser)) .SetMethod("focus", base::Bind(&Browser::Focus, browser)) .SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser)) .SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser)) @@ -489,7 +527,8 @@ void App::BuildPrototype( .SetMethod("importCertificate", &App::ImportCertificate) #endif .SetMethod("makeSingleInstance", &App::MakeSingleInstance) - .SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance); + .SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance) + .SetMethod("relaunch", &App::Relaunch); } } // namespace api diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index 979f61f0d21..e2bcb4583dd 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -106,10 +106,11 @@ class App : public AtomBrowserClient::Delegate, const base::FilePath& path); void SetDesktopName(const std::string& desktop_name); + std::string GetLocale(); bool MakeSingleInstance( const ProcessSingleton::NotificationCallback& callback); void ReleaseSingleInstance(); - std::string GetLocale(); + bool Relaunch(mate::Arguments* args); #if defined(USE_NSS_CERTS) void ImportCertificate(const base::DictionaryValue& options, diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 14aebf3db58..093209ef7c4 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -9,7 +9,6 @@ #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" -#include "atom/common/atom_command_line.h" #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" @@ -34,34 +33,6 @@ Browser* Browser::Get() { return AtomBrowserMainParts::Get()->browser(); } -bool Browser::Relaunch(bool override_argv, - const base::FilePath& app, - const relauncher::StringVector& args) { - if (!override_argv) { -#if defined(OS_WIN) - const relauncher::StringVector& argv = atom::AtomCommandLine::wargv(); -#else - const relauncher::StringVector& argv = atom::AtomCommandLine::argv(); -#endif - return relauncher::RelaunchApp(argv); - } - - relauncher::StringVector argv; - argv.reserve(1 + args.size()); - - if (app.empty()) { - base::FilePath exe_path; - PathService::Get(base::FILE_EXE, &exe_path); - argv.push_back(exe_path.value()); - } else { - argv.push_back(app.value()); - } - - argv.insert(argv.end(), args.begin(), args.end()); - - return relauncher::RelaunchApp(argv); -} - void Browser::Quit() { if (is_quiting_) return; diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 05248a1e943..18d0c97c93a 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -13,7 +13,6 @@ #include "base/observer_list.h" #include "base/strings/string16.h" #include "atom/browser/browser_observer.h" -#include "atom/browser/relauncher.h" #include "atom/browser/window_list_observer.h" #include "native_mate/arguments.h" @@ -54,11 +53,6 @@ class Browser : public WindowListObserver { // Cleanup everything and shutdown the application gracefully. void Shutdown(); - // Restart the app. - bool Relaunch(bool override_argv, - const base::FilePath& app, - const relauncher::StringVector& args); - // Focus the application. void Focus(); From d3fe80991c153856a8103389f7b3e69fa4a4f290 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Thu, 2 Jun 2016 22:06:27 +0900 Subject: [PATCH 1256/1265] docs: app.relaunch --- docs/api/app.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/api/app.md b/docs/api/app.md index 265f328eb9d..becd6039c75 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -276,6 +276,33 @@ Exits immediately with `exitCode`. All windows will be closed immediately without asking user and the `before-quit` and `will-quit` events will not be emitted. +### `app.relaunch([options])` + +* `options` Object (optional) + * `args` Array (optional) + * `execPath` String (optional) + +Relaunches the app when current instance exits. + +By default the new instance will use the same working directory and command line +arguments with current instance. When `args` is specified, the `args` will be +passed as command line arguments instead. When `execPath` is specified, the +`execPath` will be executed for relaunch instead of current app. + +Note that this method does not quit the app when executed, you have to call +`app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. + +When `app.relaunch` is called for multiple times, multiple instances will be +started after current instance exited. + +An example of restarting current instance immediately and adding a new command +line argument to the new instance: + +```javascript +app.relaunch({args: process.argv.slice(1) + ['--relaunch']}) +app.exit(0) +``` + ### `app.focus()` On Linux, focuses on the first visible window. On OS X, makes the application From 2ef2c1af02d3927cb91544ca00da11855aaf261f Mon Sep 17 00:00:00 2001 From: sqrthree Date: Thu, 2 Jun 2016 22:35:40 +0800 Subject: [PATCH 1257/1265] Correct wrong words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正错别字 --- docs-translations/zh-CN/api/browser-window.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-translations/zh-CN/api/browser-window.md b/docs-translations/zh-CN/api/browser-window.md index 867cd3e9b42..0d720c42591 100644 --- a/docs-translations/zh-CN/api/browser-window.md +++ b/docs-translations/zh-CN/api/browser-window.md @@ -49,7 +49,7 @@ win.show(); * `alwaysOnTop` Boolean - 窗口是否总是显示在其他窗口之前. 在 Linux 上无效. 默认为 `false`. * `fullscreen` Boolean - 窗口是否可以全屏幕. 当明确设置值为When `false` ,全屏化按钮将会隐藏,在 OS X 将禁用. 默认 `false`. * `fullscreenable` Boolean - 在 OS X 上,全屏化按钮是否可用,默认为 `true`. - * `skipTaskbar` Boolean - 是否在人物栏中显示窗口. 默认是`false`. + * `skipTaskbar` Boolean - 是否在任务栏中显示窗口. 默认是`false`. * `kiosk` Boolean - kiosk 方式. 默认为 `false`. * `title` String - 窗口默认title. 默认 `"Electron"`. * `icon` [NativeImage](native-image.md) - 窗口图标, 如果不设置,窗口将使用可用的默认图标. From d234467682c28de4972c16e33882f575adea6be9 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Thu, 2 Jun 2016 23:50:50 +0900 Subject: [PATCH 1258/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/browser-window.md | 18 ++++--- docs-translations/ko-KR/api/native-image.md | 8 ++- docs-translations/ko-KR/api/tray.md | 2 + docs-translations/ko-KR/api/web-contents.md | 5 +- .../source-code-directory-structure.md | 54 +++++++++---------- .../mac-app-store-submission-guide.md | 35 ++++++------ 6 files changed, 70 insertions(+), 52 deletions(-) diff --git a/docs-translations/ko-KR/api/browser-window.md b/docs-translations/ko-KR/api/browser-window.md index dfebf541fa8..df098cde877 100644 --- a/docs-translations/ko-KR/api/browser-window.md +++ b/docs-translations/ko-KR/api/browser-window.md @@ -72,6 +72,12 @@ win.show(); * `title` String - 기본 윈도우 제목. 기본값은 `"Electron"`입니다. * `icon` [NativeImage](native-image.md) - 윈도우 아이콘, 생략하면 실행 파일의 아이콘이 대신 사용됩니다. +* `icon` [NativeImage](native-image.md) - 윈도우 아이콘. Windows에선 가장 좋은 + 시각적 효과를 얻기 위해 `ICO`를 사용하는 것을 권장하며, 또한 undefined로 남겨두면 + 실행 파일의 아이콘이 대신 사용됩니다. +On Windows it is + recommended to use `ICO` icons to get best visual effects, you can also + leave it undefined so the executable's icon will be used. * `show` Boolean - 윈도우가 생성되면 보여줄지 여부. 기본값은 `true`입니다. * `frame` Boolean - `false`로 지정하면 창을 [Frameless Window](frameless-window.md) 형태로 생성합니다. 기본값은 `true`입니다. @@ -212,19 +218,17 @@ Returns: 보통 창을 닫아야 할지 결정하기 위해 `beforeunload` 이벤트를 사용하려고 할 것입니다. 이 이벤트는 윈도우 콘텐츠를 새로고칠 때도 발생합니다. -Electron에선 빈 문자열 또는 `false`를 전달할 경우 윈도우 종료를 취소합니다. - +Electron에선 `undefined`가 아닌 이외의 값을 전달할 경우 윈도우 종료를 취소합니다. 예시는 다음과 같습니다: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed'); - // 반드시 문자열을 반환해야 하고 사용자에게 페이지 언로드에 대한 확인 창을 보여주는 - // 보통의 브라우저와는 달리 Electron은 개발자에게 더 많은 옵션을 제공합니다. - // 빈 문자열을 반환하거나 false를 반환하면 페이지 언로드를 방지합니다. - // 또한 dialog API를 통해 사용자에게 어플리케이션을 종료할지에 대한 확인 창을 - // 보여줄 수도 있습니다. + // 일반적인 브라우저와는 달리 사용자에게 확인 창을 보여주지 않고, non-void 값을 반환하면 + // 조용히 닫기를 취소합니다. + // Dialog API를 통해 사용자가 어플리케이션을 종료할지 정할 수 있도록 확인 창을 표시하는 것을 + // 추천합니다. e.returnValue = false; }; ``` diff --git a/docs-translations/ko-KR/api/native-image.md b/docs-translations/ko-KR/api/native-image.md index 8fdb1ccc194..8c03b78e114 100644 --- a/docs-translations/ko-KR/api/native-image.md +++ b/docs-translations/ko-KR/api/native-image.md @@ -25,7 +25,13 @@ const appIcon = new Tray(image); 현재 `PNG` 와 `JPEG` 이미지 포맷을 지원하고 있습니다. 손실 없는 이미지 압축과 투명도 지원을 위해 `PNG` 사용을 권장합니다. -그리고 Windows에서는 `ICO` 포맷도 사용할 수 있습니다. +Windows에서는 파일 경로로부터 `ICO` 포맷도 사용할 수 있으며, 가장 좋은 시각적 효과를 +얻기 위해 최소한 아이콘에 다음 사이즈를 포함하는 것을 권장합니다: + +* 16x16 +* 32x32 +* 64x64 +* 256x256 ## 고해상도 이미지 diff --git a/docs-translations/ko-KR/api/tray.md b/docs-translations/ko-KR/api/tray.md index d208de25020..9d5d8a81bc9 100644 --- a/docs-translations/ko-KR/api/tray.md +++ b/docs-translations/ko-KR/api/tray.md @@ -27,6 +27,8 @@ __플랫폼별 한계:__ 트레이 아이콘이 작동하도록 만들 수 있습니다. * 앱 알림 표시기는 컨텍스트 메뉴를 가지고 있을 때만 보입니다. * Linux에서 앱 표시기가 사용될 경우, `click` 이벤트는 무시됩니다. +* Windows에선 가장 좋은 시각적 효과를 얻기 위해 `ICO` 아이콘을 사용하는 것을 + 권장합니다. * Linux에서 각각 개별 `MenuItem`의 변경을 적용하려면 `setContextMenu`를 다시 호출해야 합니다. 예를 들면: diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index 0510f0bd578..b1b4a4ee902 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -634,7 +634,8 @@ print기능을 사용하지 않는 경우 전체 바이너리 크기를 줄이 * `marginsType` Integer - 사용할 마진의 종류를 지정합니다. 0 부터 2 사이 값을 사용할 수 있고 각각 기본 마진, 마진 없음, 최소 마진입니다. * `pageSize` String - 생성되는 PDF의 페이지 크기를 지정합니다. 값은 `A3`, `A4`, - `A5`, `Legal`, `Letter` 와 `Tabloid`가 사용될 수 있습니다. + `A5`, `Legal`, `Letter`, `Tabloid` 또는 마이크론 단위의 `height` & `width`가 + 포함된 객체를 사용할 수 있습니다. * `printBackground` Boolean - CSS 배경을 프린트할지 여부를 정합니다. * `printSelectionOnly` Boolean - 선택된 영역만 프린트할지 여부를 정합니다. * `landscape` Boolean - landscape을 위해선 `true`를, portrait를 위해선 `false`를 @@ -658,6 +659,8 @@ Chromium의 미리보기 프린팅 커스텀 설정을 이용하여 윈도우의 } ``` +다음은 `webContents.printToPDF`의 예시입니다: + ```javascript const {BrowserWindow} = require('electron'); const fs = require('fs'); diff --git a/docs-translations/ko-KR/development/source-code-directory-structure.md b/docs-translations/ko-KR/development/source-code-directory-structure.md index 860072ac8ad..aa6d2612df5 100644 --- a/docs-translations/ko-KR/development/source-code-directory-structure.md +++ b/docs-translations/ko-KR/development/source-code-directory-structure.md @@ -10,35 +10,35 @@ Electron의 소스 코드는 몇 개의 파트로 분리되어 있습니다. 그 ``` Electron -├── atom - C++ 소스 코드. -| ├── app - 시스템 엔트리 코드. -| ├── browser - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 +├── atom/ - C++ 소스 코드. +| ├── app/ - 시스템 엔트리 코드. +| ├── browser/ - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 | | 코드와 렌더러 및 웹 페이지 관리 관련 코드. -| | ├── ui - 서로 다른 플랫폼에 대한 UI 관련 구현 코드. -| | | ├── cocoa - Cocoa 특정 소스 코드. -| | | ├── gtk - GTK+ 특정 소스 코드. -| | | └── win - Windows GUI 특정 소스 코드. -| | ├── api - 메인 프로세스 API의 구현. -| | ├── net - 네트워킹 관련 코드. -| | ├── mac - Mac 특정 Objective-C 소스 코드. -| | └── resources - 아이콘들, 플랫폼 종속성 파일들, 기타 등등.. -| ├── renderer - 렌더러 프로세스에서 작동하는 코드. -| | └── api - 렌더러 프로세스 API의 구현. -| └── common - 메인과 렌더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 +| | ├── ui/ - 서로 다른 플랫폼에 대한 UI 관련 구현 코드. +| | | ├── cocoa/ - Cocoa 특정 소스 코드. +| | | ├── win/ - Windows GUI 특정 소스 코드. +| | | └── x/ - X11 특정 소스 코드. +| | ├── api/ - 메인 프로세스 API의 구현. +| | ├── net/ - 네트워킹 관련 코드. +| | ├── mac/ - Mac 특정 Objective-C 소스 코드. +| | └── resources/ - 아이콘들, 플랫폼 종속성 파일들, 기타 등등.. +| ├── renderer/ - 렌더러 프로세스에서 작동하는 코드. +| | └── api/ - 렌더러 프로세스 API의 구현. +| └── common/ - 메인과 렌더러 프로세스에서 모두 사용하는 코드, 몇가지 유틸리티 | 함수들이 포함되어 있고 node의 메시지 루프와 Chromium의 메시지 루프를 통합. -| └── api - 공통 API 구현들, 기초 Electron 빌트-인 모듈들. -├── chromium_src - Chromium에서 복사하여 가져온 소스 코드. -├── default_app - Electron에 앱이 제공되지 않았을 때 보여지는 기본 페이지. -├── docs - 참조 문서. -├── lib - JavaScript 소스 코드. -| ├── browser - Javascript 메인 프로세스 초기화 코드. -| | └── api - Javascript API 구현 코드. -| ├── common - 메인과 렌더러 프로세스에서 모두 사용하는 JavaScript -| | └── api - Javascript API 구현 코드. -| └── renderer - Javascript 렌더러 프로세스 초기화 코드. -| └── api - Javascript API 구현 코드. -├── spec - 자동화 테스트. -├── atom.gyp - Electron의 빌드 규칙. +| └── api/ - 공통 API 구현들, 기초 Electron 빌트-인 모듈들. +├── chromium_src/ - Chromium에서 복사하여 가져온 소스 코드. +├── default_app/ - Electron에 앱이 제공되지 않았을 때 보여지는 기본 페이지. +├── docs/ - 참조 문서. +├── lib/ - JavaScript 소스 코드. +| ├── browser/ - Javascript 메인 프로세스 초기화 코드. +| | └── api/ - Javascript API 구현 코드. +| ├── common/ - 메인과 렌더러 프로세스에서 모두 사용하는 JavaScript +| | └── api/ - Javascript API 구현 코드. +| └── renderer/ - Javascript 렌더러 프로세스 초기화 코드. +| └── api/ - Javascript API 구현 코드. +├── spec/ - 자동화 테스트. +├── electron.gyp - Electron의 빌드 규칙. └── common.gypi - 컴파일러 설정 및 `node` 와 `breakpad` 등의 구성요소를 위한 빌드 규칙. ``` diff --git a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md index c4dd2ca0423..d163cb5e5c7 100644 --- a/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md +++ b/docs-translations/ko-KR/tutorial/mac-app-store-submission-guide.md @@ -85,30 +85,33 @@ ID로 치환해야 합니다. ```bash #!/bin/bash -# 어플리케이션의 이름 +# 어플리케이션의 이름. APP="YourApp" -# 서명할 어플리케이션의 경로 +# 서명할 어플리케이션의 경로. APP_PATH="/path/to/YourApp.app" -# 서명된 패키지의 출력 경로 +# 서명된 패키지의 출력 경로. RESULT_PATH="~/Desktop/$APP.pkg" -# 요청한 인증서의 이름 +# 요청한 인증서의 이름. APP_KEY="3rd Party Mac Developer Application: Company Name (APPIDENTITY)" INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)" +# plist 파일의 경로. +CHILD_PLIST="/path/to/child.plist" +PARENT_PLIST="/path/to/parent.plist" FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/Electron Framework.framework" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper EH.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" -codesign -s "$APP_KEY" -f --entitlements child.plist "$FRAMEWORKS_PATH/$APP Helper NP.app/" -codesign -s "$APP_KEY" -f --entitlements child.plist "$APP_PATH/Contents/MacOS/$APP" -codesign -s "$APP_KEY" -f --entitlements parent.plist "$APP_PATH" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/" +codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$APP_PATH/Contents/MacOS/$APP" +codesign -s "$APP_KEY" -f --entitlements "$PARENT_PLIST" "$APP_PATH" productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH" ``` From 96ca8edbb488214a615ffd1b7c7a2d55aad2abcb Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Thu, 2 Jun 2016 09:38:21 -0700 Subject: [PATCH 1259/1265] javascript -> javascript --- docs/api/web-contents.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 03d573c59c6..c3f1f82366c 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -391,7 +391,7 @@ first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. -```javacript +```javascript app.commandLine.appendSwitch('enable-web-bluetooth') app.on('ready', () => { From 020da553ffa35c8a9fbeed4c2329b5bef4779f76 Mon Sep 17 00:00:00 2001 From: Jordon Bedwell Date: Thu, 2 Jun 2016 20:12:58 -0500 Subject: [PATCH 1260/1265] List all the possible folders for Linux. Linux has several folders, depending on who is using the Linux install. On our systems it could be any one of those depending on the user and what software they prefer to use, they all have the React plugin however, each one sits in a different folder. I prefer Chrome because of Netflix, she prefers Chromium and we also have Chrome Beta available. --- docs/tutorial/devtools-extension.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/tutorial/devtools-extension.md b/docs/tutorial/devtools-extension.md index f004b1f3112..94f5ac13bf6 100644 --- a/docs/tutorial/devtools-extension.md +++ b/docs/tutorial/devtools-extension.md @@ -16,7 +16,11 @@ Using the [React Developer Tools][react-devtools] as example: string like `fmkadmapgofadopljbjfkapdkoienihi`. 1. Find out filesystem location used by Chrome for storing extensions: * on Windows it is `%LOCALAPPDATA%\Google\Chrome\User Data\Default\Extensions`; - * on Linux it is `~/.config/google-chrome/Default/Extensions/`; + * on Linux it could be: + * `~/.config/google-chrome/Default/Extensions/` + * `~/.config/google-chrome-beta/Default/Extensions/` + * `~/.config/google-chrome-canary/Default/Extensions/` + * `~/.config/chromium/Default/Extensions/` * on OS X it is `~/Library/Application Support/Google/Chrome/Default/Extensions`. 1. Pass the location of the extension to `BrowserWindow.addDevToolsExtension` API, for the React Developer Tools, it is something like: From be6ed84ff2ac3aa4d5580a383531b4780b134de6 Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 3 Jun 2016 12:08:45 +0900 Subject: [PATCH 1261/1265] args should always be checked --- atom/browser/api/atom_api_app.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index 76fbdb1859b..5d4aafca699 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -418,7 +418,7 @@ bool App::Relaunch(mate::Arguments* js_args) { mate::Dictionary options; if (js_args->GetNext(&options)) { - if (options.Get("execPath", &exec_path) || options.Get("args", &args)) + if (options.Get("execPath", &exec_path) | options.Get("args", &args)) override_argv = true; } From 707d68f719a209f7ced9b08108a4892372ebb79d Mon Sep 17 00:00:00 2001 From: Cheng Zhao Date: Fri, 3 Jun 2016 12:12:20 +0900 Subject: [PATCH 1262/1265] spec: Add test case for app.relaunch --- spec/api-app-spec.js | 50 +++++++++++++++++++++++++ spec/fixtures/api/quit-app/package.json | 2 +- spec/fixtures/api/relaunch/main.js | 25 +++++++++++++ spec/fixtures/api/relaunch/package.json | 5 +++ spec/package.json | 2 +- 5 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 spec/fixtures/api/relaunch/main.js create mode 100644 spec/fixtures/api/relaunch/package.json diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index df356ecb905..260bdd31545 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -1,6 +1,7 @@ const assert = require('assert') const ChildProcess = require('child_process') const https = require('https') +const net = require('net') const fs = require('fs') const path = require('path') const {remote} = require('electron') @@ -108,6 +109,55 @@ describe('app module', function () { }) }) + describe('app.relaunch', function () { + let server = null + const socketPath = process.platform === 'win32' ? + '\\\\.\\pipe\\electron-app-relaunch' : + '/tmp/electron-app-relaunch' + + beforeEach(function (done) { + fs.unlink(socketPath, (error) => { + server = net.createServer() + server.listen(socketPath) + done() + }) + }) + + afterEach(function (done) { + server.close(() => { + if (process.platform === 'win32') { + done() + } else { + fs.unlink(socketPath, (error) => { + done() + }) + } + }) + }) + + it('relaunches the app', function (done) { + this.timeout(100000) + let state = 'none' + server.once('error', (error) => { + done(error) + }) + server.on('connection', (client) => { + client.once('data', function (data) { + if (String(data) === 'false' && state === 'none') { + state = 'first-launch' + } else if (String(data) === 'true' && state === 'first-launch') { + done() + } else { + done(`Unexpected state: ${state}`) + } + }) + }) + + const appPath = path.join(__dirname, 'fixtures', 'api', 'relaunch') + ChildProcess.spawn(remote.process.execPath, [appPath]) + }) + }) + describe('app.setUserActivity(type, userInfo)', function () { if (process.platform !== 'darwin') { return diff --git a/spec/fixtures/api/quit-app/package.json b/spec/fixtures/api/quit-app/package.json index ea5bb1643b9..fbdee7f90f9 100644 --- a/spec/fixtures/api/quit-app/package.json +++ b/spec/fixtures/api/quit-app/package.json @@ -1,4 +1,4 @@ { - "name": "quit-app", + "name": "electron-quit-app", "main": "main.js" } diff --git a/spec/fixtures/api/relaunch/main.js b/spec/fixtures/api/relaunch/main.js new file mode 100644 index 00000000000..74cafc6f0d5 --- /dev/null +++ b/spec/fixtures/api/relaunch/main.js @@ -0,0 +1,25 @@ +const {app, dialog} = require('electron') +const net = require('net') + +const socketPath = process.platform === 'win32' ? + '\\\\.\\pipe\\electron-app-relaunch' : + '/tmp/electron-app-relaunch' + +process.on('uncaughtException', () => { + app.exit(1) +}) + +app.once('ready', () => { + let lastArg = process.argv[process.argv.length - 1] + const client = net.connect(socketPath) + client.once('connect', () => { + client.end(String(lastArg === '--second')) + }) + client.once('end', () => { + app.exit(0) + }) + + if (lastArg !== '--second') { + app.relaunch({args: process.argv.slice(1).concat('--second')}) + } +}) diff --git a/spec/fixtures/api/relaunch/package.json b/spec/fixtures/api/relaunch/package.json new file mode 100644 index 00000000000..dbaabc84896 --- /dev/null +++ b/spec/fixtures/api/relaunch/package.json @@ -0,0 +1,5 @@ +{ + "name": "electron-app-relaunch", + "main": "main.js" +} + diff --git a/spec/package.json b/spec/package.json index 0439f4b0ec0..5abf89f57e7 100644 --- a/spec/package.json +++ b/spec/package.json @@ -13,7 +13,7 @@ "temp": "0.8.1", "walkdir": "0.0.7", "ws": "0.7.2", - "yargs": "^3.31.0" + "yargs": "^4.7.1" }, "optionalDependencies": { "ffi": "2.0.0", From 41f99187e76c587ff20463736f234084f3f9ae8d Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 3 Jun 2016 17:47:21 +0900 Subject: [PATCH 1263/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/app.md | 36 +++++--- docs-translations/ko-KR/api/auto-updater.md | 3 + .../ko-KR/api/chrome-command-line-switches.md | 18 ++++ docs-translations/ko-KR/api/session.md | 16 ++++ .../ko-KR/tutorial/devtools-extension.md | 88 +++++++++---------- 5 files changed, 105 insertions(+), 56 deletions(-) diff --git a/docs-translations/ko-KR/api/app.md b/docs-translations/ko-KR/api/app.md index 4150b4d69a9..096cee0a364 100644 --- a/docs-translations/ko-KR/api/app.md +++ b/docs-translations/ko-KR/api/app.md @@ -280,6 +280,32 @@ GPU가 작동하던 중 크래시가 일어났을 때 발생하는 이벤트입 모든 윈도우는 사용자의 동의 여부에 상관없이 즉시 종료되며 `before-quit` 이벤트와 `will-quit` 이벤트가 발생하지 않습니다. +### `app.relaunch([options])` + +* `options` Object (optional) + * `args` Array (optional) + * `execPath` String (optional) + +현재 인스턴스가 종료되면 어플리케이션을 재시작합니다. + +기본적으로 새 인스턴스는 같은 작업 디렉토리의 것과 함께 현재 인스턴스의 명령줄 인수를 +사용합니다. 만약 `args`가 지정되면, `args`가 기본 명령줄 인수 대신에 전달됩니다. +`execPath`가 지정되면, 현재 어플리케이션 대신 `execPath`가 실행됩니다. + +참고로 이 메서드는 어플리케이션을 종료하지 않으며, 어플리케이션을 다시 시작시키려면 +`app.relaunch`를 호출한 후 `app.quit` 또는 `app.exit`를 실행해주어야 합니다. + +`app.relaunch`가 여러 번 호출되면, 현재 인스턴스가 종료된 후 여러 인스턴스가 +시작됩니다. + +다음은 현재 인스턴스를 즉시 종료시킨 후 새로운 명령줄 인수를 추가하여 새 +인스턴스의 어플리케이션을 실행하는 예시입니다: + +```javascript +app.relaunch({args: process.argv.slice(1) + ['--relaunch']}) +app.exit(0) +``` + ### `app.focus()` Linux에선, 첫 번째로 보여지는 윈도우가 포커스됩니다. OS X에선, 어플리케이션을 활성화 @@ -445,16 +471,6 @@ Windows에서 사용할 수 있는 JumpList의 [Tasks][tasks] 카테고리에 `t 아이콘을 가지고 있을 경우, 사용할 아이콘의 인덱스를 이 옵션으로 지정해 주어야 합니다. 단, 아이콘을 하나만 포함하고 있는 경우 0을 지정하면 됩니다. -### `app.allowNTLMCredentialsForAllDomains()` - -항상 동적으로 HTTP NTLM 또는 Negotiate 인증에 자격 증명을 보낼 것인지 설정합니다. - -기본적으로 Electron은 "로컬 인터넷" 사이트 URL에서 NTLM/Kerberos 자격 증명만을 -보냅니다. (같은 도메인 내에서) 그러나 기업 네트워크가 잘못 구성된 경우 종종 작업에 -실패할 수 있습니다. 이때 이 메서드를 통해 모든 URL을 허용할 수 있습니다. - -**참고:** 이 메서드는 `ready` 이벤트가 발생하기 전에 호출해야 합니다. - ### `app.makeSingleInstance(callback)` * `callback` Function diff --git a/docs-translations/ko-KR/api/auto-updater.md b/docs-translations/ko-KR/api/auto-updater.md index d7dc9c18a46..e7fd24aa658 100644 --- a/docs-translations/ko-KR/api/auto-updater.md +++ b/docs-translations/ko-KR/api/auto-updater.md @@ -8,6 +8,8 @@ 다음 프로젝트 중 하나를 선택하여, 어플리케이션을 배포하기 위한 멀티-플랫폼 릴리즈 서버를 손쉽게 구축할 수 있습니다: +- [nuts][nuts]: *어플리케이션을 위한 똑똑한 릴리즈 서버이며 GitHub를 백엔드로 + 사용합니다. Squirrel을 통해 자동 업데이트를 지원합니다. (Mac & Windows)* - [electron-release-server][electron-release-server]: *완벽하게 모든 기능을 지원하는 electron 어플리케이션을 위한 자가 호스트 릴리즈 서버입니다. auto-updater와 호환됩니다* @@ -117,3 +119,4 @@ Returns: [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-release-server]: https://github.com/ArekSredzki/electron-release-server [squirrel-updates-server]: https://github.com/Aluxian/squirrel-updates-server +[nuts]: https://github.com/GitbookIO/nuts diff --git a/docs-translations/ko-KR/api/chrome-command-line-switches.md b/docs-translations/ko-KR/api/chrome-command-line-switches.md index 64d7a1d792e..930d7511183 100644 --- a/docs-translations/ko-KR/api/chrome-command-line-switches.md +++ b/docs-translations/ko-KR/api/chrome-command-line-switches.md @@ -95,6 +95,24 @@ resolver, http 프록시 연결의 `CONNECT`, `SOCKS` 프록시 연결의 endpoi `--host-rules` 플래그와 비슷하지만 이 플래그는 host resolver에만 적용됩니다. +## --auth-server-whitelist=`url` + +통합 인증을 사용하도록 설정할 쉼표로 구분된 서버의 리스트. + +예를 들어: + +``` +--auth-server-whitelist='*example.com, *foobar.com, *baz' +``` + +그리고 모든 `example.com`, `foobar.com`, `baz`로 끝나는 `url`은 통합 인증을 +사용하도록 설정됩니다. `*` 접두어가 없다면 url은 정확히 일치해야 합니다. + +## --auth-negotiate-delegate-whitelist=`url` + +필수적인 사용자 자격 증명을 보내야 할 쉼표로 구분된 서버의 리스트. +`*` 접두어가 없다면 url은 정확히 일치해야 합니다. + ## --ignore-certificate-errors 인증서 에러를 무시합니다. diff --git a/docs-translations/ko-KR/api/session.md b/docs-translations/ko-KR/api/session.md index be0eafb6ed3..e21fa3b75bd 100644 --- a/docs-translations/ko-KR/api/session.md +++ b/docs-translations/ko-KR/api/session.md @@ -323,6 +323,22 @@ session.fromPartition(partition).setPermissionRequestHandler((webContents, permi 호스트 리소버(resolver) 캐시를 지웁니다. +#### `ses.allowNTLMCredentialsForDomains(domains)` + +* `domains` String - 통합 인증을 사용하도록 설정할 쉼표로 구분된 서버의 리스트. + +동적으로 HTTP NTML 또는 Negotiate 인증을 위해 언제나 자격 증명을 보낼지 여부를 +설정합니다. + +```javascript +// 통합 인증을 위해 `example.com`, `foobar.com`, `baz`로 끝나는 +// 모든 url을 지정합니다. +session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') + +// 통합 인증을 위해 모든 url을 지정합니다. +session.defaultSession.allowNTLMCredentialsForDomains('*') +``` + #### `ses.webRequest` `webRequest` API는 생명주기의 다양한 단계에 맞춰 요청 콘텐츠를 가로채거나 변경할 수 diff --git a/docs-translations/ko-KR/tutorial/devtools-extension.md b/docs-translations/ko-KR/tutorial/devtools-extension.md index b9aa2edd946..633e23d8268 100644 --- a/docs-translations/ko-KR/tutorial/devtools-extension.md +++ b/docs-translations/ko-KR/tutorial/devtools-extension.md @@ -1,63 +1,59 @@ -# 개발자 도구 확장 기능 +# 개발자 도구 확장 기능 어플리케이션의 디버깅을 쉽게 하기 위해 Electron은 기본적으로 [Chrome DevTools Extension][devtools-extension]을 지원합니다. -개발자 도구 확장 기능은 간단하게 사용할 확장 기능 플러그인의 소스 코드를 다운로드한 후 -`BrowserWindow.addDevToolsExtension` API를 통해 어플리케이션 내에 로드할 수 있습니다. -한가지 주의할 점은 확장 기능 사용시 창이 생성될 때 마다 일일이 해당 API를 호출할 필요는 -없습니다. +Electron은 유명한 웹 프레임워크를 디버깅하기 위해 사용할 수 있는 개발자 도구 확장 +기능을 사용할 수 있도록 [Chrome 개발자 도구 확장 기능][devtools-extension]을 +지원합니다. -**주의: 현재 React DevTools은 작동하지 않습니다. https://github.com/electron/electron/issues/915 이슈를 참고하세요!** +## 개발자 도구는 어떻게 로드하나요 -다음 예시는 [React DevTools Extension](https://github.com/facebook/react-devtools)을 -사용합니다. +Electron에 확장 기능을 로드하려면, Chrome 브라우저에서 다운로드 해야 하며, 파일 시스템 경로를 지정해야 합니다. 그리고 `BrowserWindow.addDevToolsExtension(extension)`를 호출함으로써 기능을 로드할 수 있습니다. -먼저 소스 코드를 다운로드 받습니다: +예시로 [React Developer Tools][react-devtools]를 사용한다면: -```bash -$ cd /some-directory -$ git clone --recursive https://github.com/facebook/react-devtools.git -``` +1. Chrome 브라우저를 설치합니다. +2. `chrome://extensions`로 이동한 후 해시된 `fmkadmapgofadopljbjfkapdkoienihi` + 같이 생긴 확장 기능의 ID를 찾습니다. +3. Chrome에서 사용하는 확장 기능을 저장해둔 파일 시스템 경로를 찾습니다: + * Windows에선 `%LOCALAPPDATA%\Google\Chrome\User Data\Default\Extensions`; + * Linux에선: + * `~/.config/google-chrome/Default/Extensions/` + * `~/.config/google-chrome-beta/Default/Extensions/` + * `~/.config/google-chrome-canary/Default/Extensions/` + * `~/.config/chromium/Default/Extensions/` + * OS X에선 `~/Library/Application Support/Google/Chrome/Default/Extensions`. +4. 확장 기능의 경로를 `BrowserWindow.addDevToolsExtension` API로 전달합니다. + React Developer Tools의 경우 다음과 비슷해야 합니다: + `~/Library/Application Support/Google/Chrome/Default/Extensions/fmkadmapgofadopljbjfkapdkoienihi/0.14.10_0` -[`react-devtools/shells/chrome/Readme.md`](https://github.com/facebook/react-devtools/blob/master/shells/chrome/Readme.md)를 -통해 확장 기능을 개발하는 방법을 알아볼 수 있습니다. +확장 기능의 이름은 `BrowserWindow.addDevToolsExtension`에서 반환되며, 이 이름을 +`BrowserWindow.removeDevToolsExtension` API로 전달함으로써 해당하는 확장 기능을 +언로드할 수 있습니다. -그리고 개발자 도구에서 다음 코드를 입력하면 확장 기능을 로드할 수 있습니다: +## 지원하는 개발자 도구 확장 기능 -```javascript -const BrowserWindow = require('electron').remote.BrowserWindow; -BrowserWindow.addDevToolsExtension('/some-directory/react-devtools/shells/chrome'); -``` +Electron은 아주 제한적인 `chrome.*` API만을 지원하므로 확장 기능이 지원하지 않는 +`chrome.*` API를 사용한다면 해당 기능은 작동하지 않을 것입니다. 다음 개발자 도구들은 +Electron에서 정상적으로 작동하는 것을 확인했으며 작동 여부를 보장할 수 있는 확장 +기능입니다: -확장 기능을 언로드 하고 콘솔을 다시 열 때 해당 확장 기능이 로드되지 않도록 하려면 -`BrowserWindow.removeDevToolsExtension` API를 사용하면 됩니다: +* [Ember Inspector](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi) +* [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi) +* [Backbone Debugger](https://chrome.google.com/webstore/detail/backbone-debugger/bhljhndlimiafopmmhjlgfpnnchjjbhd) +* [jQuery Debugger](https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi) +* [AngularJS Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) +* [Vue.js devtools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd) -```javascript -BrowserWindow.removeDevToolsExtension('React Developer Tools'); -``` +### 개발자 도구가 작동하지 않을 때 어떻게 해야 하나요? -## 개발자 도구 확장 기능의 구성 형식 +먼저 해당 확장 기능이 확실히 계속 유지되고 있는지를 확인하세요. 몇몇 확장 기능들은 +최신 버전의 Chrome 브라우저에서도 작동하지 않습니다. 그리고 이러한 확장 기능에 대해선 +Electron 개발팀에 해줄 수 있는 것이 아무것도 없습니다. -모든 개발자 도구 확장은 완벽히 Chrome 브라우저를 위해 작성되었기 때문에 Electron에서도 -로드할 수 있습니다. 하지만 반드시 확장 기능은 소스 코드 디렉터리(폴더) 형태여야 합니다. -그래서 `crx` 등의 포맷으로 패키징된 확장 기능의 경우 사용자가 직접 해당 패키지의 압축을 -풀어서 로드하지 않는 이상 Electron에서 해당 확장 기능의 압축을 풀 방법이 없습니다. - -## 백그라운드 페이지 - -현재 Electron은 Chrome에서 지원하는 백그라운드 페이지(background pages)를 지원하지 -않습니다. 몇몇 확장 기능은 이 기능에 의존하는 경우가 있는데, 이 때 해당 확장 기능은 -Electron에서 작동하지 않을 수 있습니다. - -## `chrome.*` API - -몇몇 Chrome 확장 기능은 특정 기능을 사용하기 위해 `chrome.*` API를 사용하는데, 이 -API들을 구현하기 위해 노력했지만 안타깝게도 아직 모든 API가 구현되지는 않았습니다. - -아직 모든 API가 구현되지 않았기 때문에 확장 기능에서 `chrome.devtools.*` 대신 -`chrome.*` API를 사용할 경우 확장 기능이 제대로 작동하지 않을 수 있음을 감안해야 합니다. -만약 문제가 발생할 경우 Electron의 GitHub 저장소에 관련 이슈를 올리면 해당 API를 -추가하는데 많은 도움이 됩니다. +위와 같은 상황이 아니라면 Electron의 이슈 리스트에 버그 보고를 추가한 후 예상한 것과 +달리 확장 기능의 어떤 부분의 정상적으로 작동하지 않았는지 설명하세요. [devtools-extension]: https://developer.chrome.com/extensions/devtools +[react-devtools]: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi From d4ab4bee93a428700b7bd0448c955f73bac05097 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 3 Jun 2016 18:37:46 +0900 Subject: [PATCH 1264/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/web-contents.md | 35 ++++++++++++++ .../tutorial/application-distribution.md | 47 +++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/docs-translations/ko-KR/api/web-contents.md b/docs-translations/ko-KR/api/web-contents.md index b1b4a4ee902..41592011613 100644 --- a/docs-translations/ko-KR/api/web-contents.md +++ b/docs-translations/ko-KR/api/web-contents.md @@ -360,6 +360,41 @@ Returns: 새로운 컨텍스트 메뉴의 제어가 필요할 때 발생하는 이벤트입니다. +### Event: 'select-bluetooth-device' + +Returns: + +* `event` Event +* `devices` [Objects] + * `deviceName` String + * `deviceId` String +* `callback` Function + * `deviceId` String + +`navigator.bluetooth.requestDevice`의 호출에 의해 블루투스 기기가 선택되어야 할 때 +발생하는 이벤트입니다. `navigator.bluetooth` API를 사용하려면 `webBluetooth`가 +활성화되어 있어야 합니다. 만약 `event.preventDefault`이 호출되지 않으면, 첫 번째로 +사용 가능한 기기가 선택됩니다. `callback`은 반드시 선택될 `deviceId`와 함께 +호출되어야 하며, 빈 문자열을 `callback`에 보내면 요청이 취소됩니다. + +```javascript +app.commandLine.appendSwitch('enable-web-bluetooth') + +app.on('ready', () => { + webContents.on('select-bluetooth-device', (event, deviceList, callback) => { + event.preventDefault() + let result = deviceList.find((device) => { + return device.deviceName === 'test' + }) + if (!result) { + callback('') + } else { + callback(result.deviceId) + } + }) +}) +``` + ## Instance Methods `webContents`객체는 다음과 같은 인스턴스 메서드들을 가지고 있습니다. diff --git a/docs-translations/ko-KR/tutorial/application-distribution.md b/docs-translations/ko-KR/tutorial/application-distribution.md index 501de4da93f..fedd613c0f1 100644 --- a/docs-translations/ko-KR/tutorial/application-distribution.md +++ b/docs-translations/ko-KR/tutorial/application-distribution.md @@ -145,3 +145,50 @@ Electron의 소스 코드를 수정하고 다시 빌드하는 작업은 상당 이 툴을 사용하면 자동으로 `.gyp`파일을 수정하고 다시 빌드합니다. 그리고 어플리케이션의 네이티브 Node 모듈 또한 새로운 실행파일 이름으로 일치시킵니다. + +### Electron 커스텀 포크 만들기 + +Electron의 커스텀 포크를 만드는 것은 거의 확실히 앱을 만드는데 있어서 필요한 작업이 +아닐 수 있으며, 심지어 "제품 등급"의 어플리케이션이라도 필요하지 않습니다. +`electron-packager` 또는 `electron-builder`와 같은 도구를 사용하면 다른 특별한 +과정 없이 Electron을 "Rebrand" 할 수 있습니다. + +업스트림 단에서 추가될 수 없는 기능이나 이미 공식 버전에서 거부된 기능을 Electron에 +직접적으로 패치하기 위해 커스텀 C++를 추가해야 한다면 Electron을 포크해야 합니다. +Electron의 개발자로써, Electron을 매우 많은 시나리오에서도 작동하도록 만들려고 +합니다. 따라서 가능한한 변경 사항을 공식 버전의 Electron에 추가할 수 있도록 시도해 +주길 바라며, 당신에겐 아주 아주 쉬운 작업일 것이고 이러한 당신의 도움에 대해 감사하게 +생각합니다. + +#### surf-build와 함께 커스텀 릴리즈 만들기 + +1. npm을 통해 [Surf](https://github.com/surf-build/surf)를 설치합니다: + `npm install -g surf-build@latest` + +2. 새로운 S3 bucket을 만들고 다음과 같은 빈 디렉토리 구조를 만듭니다: + +``` +- atom-shell/ + - symbols/ + - dist/ +``` + +3. 다음의 환경 변수들을 설정합니다: + +* `ELECTRON_GITHUB_TOKEN` - GitHub에 릴리즈를 만들 수 있는 토큰. +* `ELECTRON_S3_ACCESS_KEY`, `ELECTRON_S3_BUCKET`, `ELECTRON_S3_SECRET_KEY` - + node.js 헤더 뿐만 아니라 심볼을 업로드할 장소. +* `ELECTRON_RELEASE` - `true`로 지정하고 업로드 부분이 실행되면, 설정되지 않은 + 부분을 남기고 `surf-build`가 CI-type 확인을 실행합니다. 모든 pull request를 + 실행할 때 적합합니다. +* `CI` - `true` 또는 다른 것을 지정하면 실패합니다. +* `GITHUB_TOKEN` - `ELECTRON_GITHUB_TOKEN`와 같게 설정 +* `SURF_TEMP` - Windows에선 `C:\Temp`로 설정하면 긴 경로 문제를 해결할 수 있습니다. +* `TARGET_ARCH` - `ia32` 또는 `x64`를 지정. + +4. Electron에 기여를 하는 기여자라면, _반드시_ `script/upload.py`에서 포크를 위해 + `ELECTRON_REPO`를 설정해야 합니다. (`MYORG/electron`) + +5. `surf-build -r https://github.com/MYORG/electron -s YOUR_COMMIT -n 'surf-PLATFORM-ARCH'` + +6. 빌드가 완료될 때까지 아주 아주 긴 시간을 기다립니다. From 6f8ebee3e852b205716290cbe5aea1df1cf07123 Mon Sep 17 00:00:00 2001 From: Plusb Preco Date: Fri, 3 Jun 2016 18:41:47 +0900 Subject: [PATCH 1265/1265] :memo: Update Korean docs as upstream [ci skip] --- docs-translations/ko-KR/api/system-preferences.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs-translations/ko-KR/api/system-preferences.md b/docs-translations/ko-KR/api/system-preferences.md index 8a98dd1d543..9b53baee35b 100644 --- a/docs-translations/ko-KR/api/system-preferences.md +++ b/docs-translations/ko-KR/api/system-preferences.md @@ -37,8 +37,8 @@ OS X의 네이티브 알림을 구독하며, 해당하는 `event`가 발생하 ### `systemPreferences.getUserDefault(key, type)` _OS X_ * `key` String -* `type` String - `string`, `boolean`, `integer`, `float`, `double`, `url` 값이 - 될 수 있습니다. +* `type` String - `string`, `boolean`, `integer`, `float`, `double`, `url`, + `array`, `dictionary` 값이 될 수 있습니다. 시스템 설정에서 `key`에 해당하는 값을 가져옵니다. @@ -49,6 +49,9 @@ OS X에선 API가 `NSUserDefaults`를 읽어들입니다. 유명한 `key`와 `ty * `AppleAquaColorVariant: integer` * `AppleHighlightColor: string` * `AppleShowScrollBars: string` +* `NSNavRecentPlaces: array` +* `NSPreferredWebServices: dictionary` +* `NSUserDictionaryReplacementItems: array` ### `systemPreferences.isAeroGlassEnabled()` _Windows_