diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-10-24 11:30:15 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-10-30 12:56:19 +0000 |
commit | 6036726eb981b6c4b42047513b9d3f4ac865daac (patch) | |
tree | 673593e70678e7789766d1f732eb51f613a2703b /chromium/third_party/blink/renderer/modules/background_fetch | |
parent | 466052c4e7c052268fd931888cd58961da94c586 (diff) | |
download | qtwebengine-chromium-6036726eb981b6c4b42047513b9d3f4ac865daac.tar.gz |
BASELINE: Update Chromium to 70.0.3538.78
Change-Id: Ie634710bf039e26c1957f4ae45e101bd4c434ae7
Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/third_party/blink/renderer/modules/background_fetch')
50 files changed, 988 insertions, 1299 deletions
diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn b/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn index 831d97f4fff..9b7f031e89c 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn +++ b/chromium/third_party/blink/renderer/modules/background_fetch/BUILD.gn @@ -8,32 +8,24 @@ blink_modules_sources("background_fetch") { sources = [ "background_fetch_bridge.cc", "background_fetch_bridge.h", - "background_fetch_click_event.cc", - "background_fetch_click_event.h", "background_fetch_event.cc", "background_fetch_event.h", - "background_fetch_fail_event.cc", - "background_fetch_fail_event.h", "background_fetch_fetch.cc", "background_fetch_fetch.h", "background_fetch_icon_loader.cc", "background_fetch_icon_loader.h", "background_fetch_manager.cc", "background_fetch_manager.h", + "background_fetch_record.cc", + "background_fetch_record.h", "background_fetch_registration.cc", "background_fetch_registration.h", - "background_fetch_settled_event.cc", - "background_fetch_settled_event.h", "background_fetch_settled_fetch.cc", "background_fetch_settled_fetch.h", - "background_fetch_settled_fetches.cc", - "background_fetch_settled_fetches.h", "background_fetch_type_converters.cc", "background_fetch_type_converters.h", - "background_fetch_update_event.cc", - "background_fetch_update_event.h", - "background_fetched_event.cc", - "background_fetched_event.h", + "background_fetch_update_ui_event.cc", + "background_fetch_update_ui_event.h", "service_worker_global_scope_background_fetch.h", "service_worker_registration_background_fetch.cc", "service_worker_registration_background_fetch.h", diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc index 2ed7682ebcf..e5bc03686bc 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.cc @@ -46,6 +46,19 @@ void BackgroundFetchBridge::GetIconDisplaySize( GetService()->GetIconDisplaySize(std::move(callback)); } +void BackgroundFetchBridge::MatchRequests( + const String& developer_id, + const String& unique_id, + base::Optional<WebServiceWorkerRequest> request_to_match, + mojom::blink::QueryParamsPtr cache_query_params, + bool match_all, + mojom::blink::BackgroundFetchService::MatchRequestsCallback callback) { + GetService()->MatchRequests( + GetSupplementable()->WebRegistration()->RegistrationId(), developer_id, + unique_id, std::move(request_to_match), std::move(cache_query_params), + match_all, std::move(callback)); +} + void BackgroundFetchBridge::Fetch( const String& developer_id, Vector<WebServiceWorkerRequest> requests, @@ -69,10 +82,17 @@ void BackgroundFetchBridge::Abort(const String& developer_id, void BackgroundFetchBridge::UpdateUI(const String& developer_id, const String& unique_id, const String& title, + const SkBitmap& icon, UpdateUICallback callback) { + if (title.IsNull() && icon.isNull()) { + std::move(callback).Run( + mojom::blink::BackgroundFetchError::INVALID_ARGUMENT); + return; + } + GetService()->UpdateUI( GetSupplementable()->WebRegistration()->RegistrationId(), developer_id, - unique_id, title, std::move(callback)); + unique_id, title, icon, std::move(callback)); } void BackgroundFetchBridge::GetRegistration(const String& developer_id, @@ -92,6 +112,7 @@ void BackgroundFetchBridge::DidGetRegistration( if (registration) { DCHECK_EQ(error, mojom::blink::BackgroundFetchError::NONE); + DCHECK_EQ(registration->state(), "pending"); registration->Initialize(GetSupplementable()); } diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h index 652f8ff66bb..b6dba87ebab 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h @@ -59,12 +59,27 @@ class BackgroundFetchBridge final // Gets the size of the icon to be displayed in Background Fetch UI. void GetIconDisplaySize(GetIconDisplaySizeCallback callback); + // Matches completed requests for the fetch associated with the |developer_id| + // and |unique_id| and returns the {request, response} pairs based on the rest + // of the arguments. If |filter_by_request| is true, only response(s) for + // |request_to_match| are returned. |cache_query_params| are options for the + // query to the cache storage. |match_all|, when true, returns all responses + // from the result set, and when false, returns only the first one. + void MatchRequests( + const String& developer_id, + const String& unique_id, + base::Optional<WebServiceWorkerRequest> request_to_match, + mojom::blink::QueryParamsPtr cache_query_params, + bool match_all, + mojom::blink::BackgroundFetchService::MatchRequestsCallback callback); + // Updates the user interface for the Background Fetch identified by - // |unique_id| with the updated |title|. Will invoke the |callback| when the - // interface has been requested to update. + // |unique_id| with the updated |title| or |icon|. Will invoke the |callback| + // when the interface has been requested to update. void UpdateUI(const String& developer_id, const String& unique_id, const String& title, + const SkBitmap& icon, UpdateUICallback callback); // Aborts the active Background Fetch for |unique_id|. Will invoke the diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.cc deleted file mode 100644 index 3d8d773ec08..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.cc +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2017 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.h" - -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_click_event_init.h" -#include "third_party/blink/renderer/modules/event_modules_names.h" - -namespace blink { - -BackgroundFetchClickEvent::BackgroundFetchClickEvent( - const AtomicString& type, - const BackgroundFetchClickEventInit& initializer, - WaitUntilObserver* observer) - : BackgroundFetchEvent(type, initializer, observer), - state_(initializer.state()) {} - -BackgroundFetchClickEvent::~BackgroundFetchClickEvent() = default; - -AtomicString BackgroundFetchClickEvent::state() const { - return state_; -} - -const AtomicString& BackgroundFetchClickEvent::InterfaceName() const { - return EventNames::BackgroundFetchClickEvent; -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.h deleted file mode 100644 index b4a2327079a..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_CLICK_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_CLICK_EVENT_H_ - -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" - -namespace blink { - -class BackgroundFetchClickEventInit; -class WaitUntilObserver; - -class MODULES_EXPORT BackgroundFetchClickEvent final - : public BackgroundFetchEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchClickEvent* Create( - const AtomicString& type, - const BackgroundFetchClickEventInit& initializer) { - return new BackgroundFetchClickEvent(type, initializer, - nullptr /* observer */); - } - - static BackgroundFetchClickEvent* Create( - const AtomicString& type, - const BackgroundFetchClickEventInit& initializer, - WaitUntilObserver* observer) { - return new BackgroundFetchClickEvent(type, initializer, observer); - } - - ~BackgroundFetchClickEvent() override; - - // Web Exposed attribute defined in the IDL file. - AtomicString state() const; - - // ExtendableEvent interface. - const AtomicString& InterfaceName() const override; - - private: - BackgroundFetchClickEvent(const AtomicString& type, - const BackgroundFetchClickEventInit& initializer, - WaitUntilObserver* observer); - - AtomicString state_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_CLICK_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.idl deleted file mode 100644 index 08591605e3f..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event.idl +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017 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. - -// https://wicg.github.io/background-fetch/#background-fetch-click-event - -enum BackgroundFetchState { "pending", "succeeded", "failed" }; - -[ - Constructor(DOMString type, BackgroundFetchClickEventInit init), - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] interface BackgroundFetchClickEvent : BackgroundFetchEvent { - readonly attribute BackgroundFetchState state; -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event_init.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event_init.idl deleted file mode 100644 index cf1cb863239..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_click_event_init.idl +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017 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. - -// https://wicg.github.io/background-fetch/#background-fetch-click-event - -dictionary BackgroundFetchClickEventInit : BackgroundFetchEventInit { - required BackgroundFetchState state; -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc index 5033231c78b..0dfa3935bd9 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.cc @@ -5,6 +5,7 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" #include "third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h" #include "third_party/blink/renderer/modules/event_modules_names.h" namespace blink { @@ -14,16 +15,21 @@ BackgroundFetchEvent::BackgroundFetchEvent( const BackgroundFetchEventInit& initializer, WaitUntilObserver* observer) : ExtendableEvent(type, initializer, observer), - developer_id_(initializer.id()) {} + registration_(initializer.registration()) {} BackgroundFetchEvent::~BackgroundFetchEvent() = default; -String BackgroundFetchEvent::id() const { - return developer_id_; +BackgroundFetchRegistration* BackgroundFetchEvent::registration() const { + return registration_; } const AtomicString& BackgroundFetchEvent::InterfaceName() const { return EventNames::BackgroundFetchEvent; } +void BackgroundFetchEvent::Trace(blink::Visitor* visitor) { + visitor->Trace(registration_); + ExtendableEvent::Trace(visitor); +} + } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h index 19d07114b9b..9656152cdd4 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.h @@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_EVENT_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_EVENT_H_ +#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/service_worker/extendable_event.h" #include "third_party/blink/renderer/platform/heap/handle.h" @@ -13,6 +14,7 @@ namespace blink { class BackgroundFetchEventInit; +class BackgroundFetchRegistration; class WaitUntilObserver; class MODULES_EXPORT BackgroundFetchEvent : public ExtendableEvent { @@ -34,21 +36,21 @@ class MODULES_EXPORT BackgroundFetchEvent : public ExtendableEvent { ~BackgroundFetchEvent() override; - // Web Exposed attribute defined in the IDL file. Corresponds to the - // |developer_id| used elsewhere in the codebase. - String id() const; + // Web Exposed attribute defined in the IDL file. + BackgroundFetchRegistration* registration() const; // ExtendableEvent interface. const AtomicString& InterfaceName() const override; + void Trace(blink::Visitor* visitor) override; + protected: BackgroundFetchEvent(const AtomicString& type, const BackgroundFetchEventInit& initializer, WaitUntilObserver* observer); - // Corresponds to IDL 'id' attribute. Not unique - an active registration can - // have the same |developer_id_| as one or more inactive registrations. - String developer_id_; + // Corresponds to the 'registration' attribute in the idl. + Member<BackgroundFetchRegistration> registration_; }; } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.idl index 632db60111f..e4c633e4e3c 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.idl +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event.idl @@ -9,5 +9,5 @@ Exposed=ServiceWorker, RuntimeEnabled=BackgroundFetch ] interface BackgroundFetchEvent : ExtendableEvent { - readonly attribute DOMString id; + readonly attribute BackgroundFetchRegistration registration; }; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.idl index 24194f4e808..191ccd15b8c 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.idl +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.idl @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://wicg.github.io/background-fetch/#background-fetch-event +// https://wicg.github.io/background-fetch/#dictdef-backgroundfetcheventinit dictionary BackgroundFetchEventInit : ExtendableEventInit { - required DOMString id; -}; + required BackgroundFetchRegistration registration; +};
\ No newline at end of file diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.cc deleted file mode 100644 index 50e51d50dd3..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.cc +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.h" - -#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/core/fetch/request.h" -#include "third_party/blink/renderer/core/fetch/response.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event_init.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/modules/event_modules_names.h" - -namespace blink { - -BackgroundFetchFailEvent::BackgroundFetchFailEvent( - const AtomicString& type, - const BackgroundFetchFailEventInit& initializer) - : BackgroundFetchEvent(type, initializer, nullptr /* observer */), - fetches_(initializer.fetches()) {} - -BackgroundFetchFailEvent::BackgroundFetchFailEvent( - const AtomicString& type, - const BackgroundFetchFailEventInit& initializer, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer) - : BackgroundFetchEvent(type, initializer, observer) { - fetches_.ReserveInitialCapacity(fetches.size()); - for (const WebBackgroundFetchSettledFetch& fetch : fetches) { - auto* settled_fetch = BackgroundFetchSettledFetch::Create( - Request::Create(script_state, fetch.request), - Response::Create(script_state, fetch.response)); - - fetches_.push_back(settled_fetch); - } -} - -BackgroundFetchFailEvent::~BackgroundFetchFailEvent() = default; - -HeapVector<Member<BackgroundFetchSettledFetch>> -BackgroundFetchFailEvent::fetches() const { - return fetches_; -} - -const AtomicString& BackgroundFetchFailEvent::InterfaceName() const { - return EventNames::BackgroundFetchFailEvent; -} - -void BackgroundFetchFailEvent::Trace(blink::Visitor* visitor) { - visitor->Trace(fetches_); - BackgroundFetchEvent::Trace(visitor); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.h deleted file mode 100644 index d8a6e91668f..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_FAIL_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_FAIL_EVENT_H_ - -#include "third_party/blink/public/platform/web_vector.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" - -namespace blink { - -class BackgroundFetchFailEventInit; -class BackgroundFetchSettledFetch; -class ScriptState; -struct WebBackgroundFetchSettledFetch; - -class MODULES_EXPORT BackgroundFetchFailEvent final - : public BackgroundFetchEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchFailEvent* Create( - const AtomicString& type, - const BackgroundFetchFailEventInit& initializer) { - return new BackgroundFetchFailEvent(type, initializer); - } - - static BackgroundFetchFailEvent* Create( - const AtomicString& type, - const BackgroundFetchFailEventInit& initializer, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer) { - return new BackgroundFetchFailEvent(type, initializer, fetches, - script_state, observer); - } - - ~BackgroundFetchFailEvent() override; - - // Web Exposed attribute defined in the IDL file. - HeapVector<Member<BackgroundFetchSettledFetch>> fetches() const; - - // ExtendableEvent interface. - const AtomicString& InterfaceName() const override; - - void Trace(blink::Visitor* visitor) override; - - private: - BackgroundFetchFailEvent(const AtomicString& type, - const BackgroundFetchFailEventInit& initializer); - BackgroundFetchFailEvent( - const AtomicString& type, - const BackgroundFetchFailEventInit& initializer, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer); - - HeapVector<Member<BackgroundFetchSettledFetch>> fetches_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_FAIL_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.idl deleted file mode 100644 index 1f86f8e7918..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_fail_event.idl +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017 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. - -// https://wicg.github.io/background-fetch/#background-fetch-fail-event - -[ - Constructor(DOMString type, BackgroundFetchFailEventInit init), - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] interface BackgroundFetchFailEvent : BackgroundFetchEvent { - readonly attribute FrozenArray<BackgroundFetchSettledFetch> fetches; -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc index 3c346b726be..419441d0ecb 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc @@ -5,30 +5,39 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h" #include "skia/ext/image_operations.h" +#include "third_party/blink/public/common/manifest/manifest_icon_selector.h" #include "third_party/blink/public/platform/web_size.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/loader/threadable_loader.h" #include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h" #include "third_party/blink/renderer/modules/manifest/image_resource.h" +#include "third_party/blink/renderer/modules/manifest/image_resource_type_converters.h" +#include "third_party/blink/renderer/platform/cross_thread_functional.h" #include "third_party/blink/renderer/platform/graphics/color_behavior.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" #include "third_party/blink/renderer/platform/image-decoders/image_decoder.h" #include "third_party/blink/renderer/platform/image-decoders/image_frame.h" +#include "third_party/blink/renderer/platform/image-decoders/segment_reader.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" +#include "third_party/blink/renderer/platform/scheduler/public/background_scheduler.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/threading.h" namespace blink { namespace { -const unsigned long kIconFetchTimeoutInMs = 30000; -const int kMinimumIconSizeInPx = 16; -const double kAnySizeScore = 0.8; -const double kUnspecifiedSizeScore = 0.4; +constexpr unsigned long kIconFetchTimeoutInMs = 30000; +constexpr int kMinimumIconSizeInPx = 0; + +// Because including base::ClampToRange would be a dependency violation. +int ClampToRange(const int value, const int min, const int max) { + return std::min(std::max(value, min), max); +} } // namespace @@ -57,24 +66,23 @@ void BackgroundFetchIconLoader::DidGetIconDisplaySizeIfSoLoadIcon( ExecutionContext* execution_context, IconCallback icon_callback, const WebSize& icon_display_size_pixels) { - if (icon_display_size_pixels.IsEmpty()) { + icon_display_size_pixels_ = icon_display_size_pixels; + + // If |icon_display_size_pixels_| is empty then no image will be displayed by + // the UI powering Background Fetch. Bail out immediately. + if (icon_display_size_pixels_.IsEmpty()) { std::move(icon_callback).Run(SkBitmap()); return; } - int best_icon_index = - PickBestIconForDisplay(execution_context, icon_display_size_pixels); - if (best_icon_index < 0) { + KURL best_icon_url = PickBestIconForDisplay(execution_context); + if (best_icon_url.IsEmpty()) { // None of the icons provided was suitable. std::move(icon_callback).Run(SkBitmap()); return; } - KURL best_icon_url = - execution_context->CompleteURL(icons_[best_icon_index].src()); - icon_callback_ = std::move(icon_callback); - ThreadableLoaderOptions threadable_loader_options; - threadable_loader_options.timeout_milliseconds = kIconFetchTimeoutInMs; + icon_callback_ = std::move(icon_callback); ResourceLoaderOptions resource_loader_options; if (execution_context->IsWorkerGlobalScope()) @@ -85,101 +93,27 @@ void BackgroundFetchIconLoader::DidGetIconDisplaySizeIfSoLoadIcon( resource_request.SetPriority(ResourceLoadPriority::kMedium); resource_request.SetRequestorOrigin(execution_context->GetSecurityOrigin()); - threadable_loader_ = ThreadableLoader::Create(*execution_context, this, - threadable_loader_options, - resource_loader_options); - + threadable_loader_ = + new ThreadableLoader(*execution_context, this, resource_loader_options); + threadable_loader_->SetTimeout( + TimeDelta::FromMilliseconds(kIconFetchTimeoutInMs)); threadable_loader_->Start(resource_request); } -int BackgroundFetchIconLoader::PickBestIconForDisplay( - ExecutionContext* execution_context, - const WebSize& icon_display_size_pixels) { - int best_index = -1; - double best_score = 0.0; - for (size_t i = 0; i < icons_.size(); ++i) { - // If the icon has no or invalid src, move on. - if (!icons_[i].hasSrc()) - continue; - KURL icon_url = execution_context->CompleteURL(icons_[i].src()); - if (!icon_url.IsValid() || icon_url.IsEmpty()) - continue; - - double score = GetIconScore(icons_[i], icon_display_size_pixels.width); - if (!score) - continue; - // According to the spec, if two icons get the same score, we must use the - // one that's declared last. (https://w3c.github.io/manifest/#icons-member). - if (score >= best_score) { - best_score = score; - best_index = i; - } +KURL BackgroundFetchIconLoader::PickBestIconForDisplay( + ExecutionContext* execution_context) { + std::vector<Manifest::ImageResource> icons; + for (auto& icon : icons_) { + // Update the src of |icon| to include the base URL in case relative paths + // were used. + icon.setSrc(execution_context->CompleteURL(icon.src())); + icons.emplace_back(blink::ConvertManifestImageResource(icon)); } - return best_index; -} -// The scoring works as follows: -// When the size is "any", the icon size score is kAnySizeScore. -// If unspecified, use the unspecified size score, kUnspecifiedSizeScore as -// icon score. - -// For other sizes, the icon score lies in [0,1] and is computed by multiplying -// the dominant size score and aspect ratio score. -// -// The dominant size score lies in [0, 1] and is computed using -// dominant size and and |ideal_size|: -// - If dominant_size < kMinimumIconSizeInPx, the size score is 0.0. -// - For all other sizes, the score is calculated as -// 1/(1 + abs(dominant_size-ideal_size)) -// - If dominant_size < ideal_size, there is an upscaling penalty, which is -// dominant_size/ideal_size. -// -// The aspect ratio score lies in [0, 1] and is computed by dividing the short -// edge length by the long edge. (Bias towards square icons assumed). -// -// Note: If this is an ico file containing multiple sizes, return the best -// score. -double BackgroundFetchIconLoader::GetIconScore(ManifestImageResource icon, - const int ideal_size) { - // Extract sizes from the icon definition, expressed as "<width>x<height> - // <width>x<height> ...." - if (!icon.hasSizes() || icon.sizes().IsEmpty()) - return kUnspecifiedSizeScore; - - String sizes = icon.sizes(); - // if any size is set to "any" return kAnySizeScore; - if (sizes.LowerASCII() == "any") - return kAnySizeScore; - - Vector<String> sizes_str; - sizes.Split(" ", false /* allow_empty_entries*/, sizes_str); - - // Pick the first size. - // TODO(nator): Add support for multiple sizes (.ico files). - Vector<String> width_and_height_str; - sizes_str[0].Split("x", false /* allow_empty_entries */, - width_and_height_str); - // If sizes isn't in this format, consider it as 'unspecified'. - if (width_and_height_str.size() != 2) - return kUnspecifiedSizeScore; - double width = width_and_height_str[0].ToDouble(); - double height = width_and_height_str[1].ToDouble(); - - // Compute dominant size score - int dominant_size = std::max(width, height); - int short_size = std::min(width, height); - if (dominant_size < kMinimumIconSizeInPx) - return 0.0; - - double dominant_size_score = 1.0 / (1.0 + abs(dominant_size - ideal_size)); - if (dominant_size < ideal_size) - dominant_size_score = dominant_size_score * dominant_size / ideal_size; - // Compute aspect ratio score. If dominant_size is zero, we'd have returned - // by now. - double aspect_ratio_score = short_size / dominant_size; - - // Compute icon score. - return aspect_ratio_score * dominant_size_score; + // TODO(crbug.com/868875): Handle cases where `sizes` or `purpose` is empty. + return KURL(ManifestIconSelector::FindBestMatchingIcon( + std::move(icons), icon_display_size_pixels_.height, kMinimumIconSizeInPx, + Manifest::ImageResource::Purpose::ANY)); } void BackgroundFetchIconLoader::Stop() { @@ -204,22 +138,69 @@ void BackgroundFetchIconLoader::DidFinishLoading( unsigned long resource_identifier) { if (stopped_) return; - if (data_) { - // Decode data. - const bool data_complete = true; - std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create( - data_, data_complete, ImageDecoder::kAlphaPremultiplied, - ImageDecoder::kDefaultBitDepth, ColorBehavior::TransformToSRGB()); - if (decoder) { - // the |ImageFrame*| is owned by the decoder. - ImageFrame* image_frame = decoder->DecodeFrameBufferAtIndex(0); - if (image_frame) { - std::move(icon_callback_).Run(image_frame->Bitmap()); - return; + + if (!data_) { + RunCallbackWithEmptyBitmap(); + return; + } + + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + Platform::Current()->CurrentThread()->GetTaskRunner(); + + BackgroundScheduler::PostOnBackgroundThread( + FROM_HERE, + CrossThreadBind( + &BackgroundFetchIconLoader::DecodeAndResizeImageOnBackgroundThread, + WrapCrossThreadPersistent(this), std::move(task_runner), + SegmentReader::CreateFromSharedBuffer(std::move(data_)))); +} + +void BackgroundFetchIconLoader::DecodeAndResizeImageOnBackgroundThread( + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + scoped_refptr<SegmentReader> data) { + DCHECK(task_runner); + DCHECK(data); + + // Explicitly pass in the |icon_display_size_pixels_| to benefit from decoders + // that have optimizations for partial decoding. + std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create( + std::move(data), /* data_complete= */ true, + ImageDecoder::kAlphaPremultiplied, ImageDecoder::kDefaultBitDepth, + ColorBehavior::TransformToSRGB(), + {icon_display_size_pixels_.width, icon_display_size_pixels_.height}); + + if (decoder) { + ImageFrame* image_frame = decoder->DecodeFrameBufferAtIndex(0); + if (image_frame) { + decoded_icon_ = image_frame->Bitmap(); + + int width = decoded_icon_.width(); + int height = decoded_icon_.height(); + + // If the |decoded_icon_| is larger than |icon_display_size_pixels_| + // permits, we need to resize it as well. This can be done synchronously + // given that we're on a background thread already. + double scale = std::min( + static_cast<double>(icon_display_size_pixels_.width) / width, + static_cast<double>(icon_display_size_pixels_.height) / height); + + if (scale < 1) { + width = ClampToRange(scale * width, 1, icon_display_size_pixels_.width); + height = + ClampToRange(scale * height, 1, icon_display_size_pixels_.height); + + // Use the RESIZE_GOOD quality allowing the implementation to pick an + // appropriate method for the resize. Can be increased to RESIZE_BETTER + // or RESIZE_BEST if the quality looks poor. + decoded_icon_ = skia::ImageOperations::Resize( + decoded_icon_, skia::ImageOperations::RESIZE_GOOD, width, height); } } } - RunCallbackWithEmptyBitmap(); + + PostCrossThreadTask(*task_runner, FROM_HERE, + CrossThreadBind(&BackgroundFetchIconLoader::RunCallback, + WrapCrossThreadPersistent(this))); } void BackgroundFetchIconLoader::DidFail(const ResourceError& error) { @@ -230,13 +211,18 @@ void BackgroundFetchIconLoader::DidFailRedirectCheck() { RunCallbackWithEmptyBitmap(); } -void BackgroundFetchIconLoader::RunCallbackWithEmptyBitmap() { +void BackgroundFetchIconLoader::RunCallback() { // If this has been stopped it is not desirable to trigger further work, // there is a shutdown of some sort in progress. if (stopped_) return; - std::move(icon_callback_).Run(SkBitmap()); + std::move(icon_callback_).Run(decoded_icon_); +} + +void BackgroundFetchIconLoader::RunCallbackWithEmptyBitmap() { + DCHECK(decoded_icon_.isNull()); + RunCallback(); } } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h index 400dc73c7f2..2e7a2c83d66 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h @@ -10,7 +10,6 @@ #include "third_party/blink/renderer/core/loader/threadable_loader.h" #include "third_party/blink/renderer/core/loader/threadable_loader_client.h" #include "third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h" -#include "third_party/blink/renderer/modules/manifest/image_resource.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -18,6 +17,7 @@ namespace blink { class BackgroundFetchBridge; +class SegmentReader; struct WebSize; class MODULES_EXPORT BackgroundFetchIconLoader final @@ -31,16 +31,12 @@ class MODULES_EXPORT BackgroundFetchIconLoader final BackgroundFetchIconLoader(); ~BackgroundFetchIconLoader() override; - // Scales down |icon| and returns result. If it is already small enough, - // |icon| is returned unchanged. - static SkBitmap ScaleDownIfNeeded(const SkBitmap& icon); - // Asynchronously download an icon from the given url, decodes the loaded // data, and passes the bitmap to the given callback. void Start(BackgroundFetchBridge* bridge, ExecutionContext* execution_context, HeapVector<ManifestImageResource> icons, - IconCallback callback); + IconCallback icon_callback); // Cancels the pending load, if there is one. The |icon_callback_| will not // be run. @@ -59,6 +55,8 @@ class MODULES_EXPORT BackgroundFetchIconLoader final private: friend class BackgroundFetchIconLoaderTest; + + void RunCallback(); void RunCallbackWithEmptyBitmap(); // Callback for BackgroundFetchBridge::GetIconDisplaySize() @@ -68,20 +66,37 @@ class MODULES_EXPORT BackgroundFetchIconLoader final const WebSize& icon_display_size_pixels); // Picks the best icon from the list of developer provided icons, for current - // display, given the ideal |icon_display_size_pixels|, and returns its index - // in the icons_ array. - int PickBestIconForDisplay(ExecutionContext* execution_context, - const WebSize& icon_display_size_pixels); + // display, given the ideal |icon_display_size_pixels_|, and returns its KURL. + // If none of the icons is appropriate, this returns an empty URL. + KURL PickBestIconForDisplay(ExecutionContext* execution_context); - // Get a score for the given icon, based on ideal_size. The icon with the - // highest score is chosen. - double GetIconScore(ManifestImageResource icon, const int ideal_size); + // Decodes the |data| to a SkBitmap using the image decoders and resizes it to + // be no larger than |icon_display_size_pixels_|. + void DecodeAndResizeImageOnBackgroundThread( + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + scoped_refptr<SegmentReader> data); + + // Called when the image has been decoded and resized on a background thread. + void DidFinishDecoding(); - bool stopped_ = false; - scoped_refptr<SharedBuffer> data_; - IconCallback icon_callback_; HeapVector<ManifestImageResource> icons_; + IconCallback icon_callback_; + Member<ThreadableLoader> threadable_loader_; + + // Size at which the icon will be presented to the user. + WebSize icon_display_size_pixels_; + + // Data received from the ThreadableLoader. Will be invalidated when decoding + // of the image data starts. + scoped_refptr<SharedBuffer> data_; + + // Result of decoding the icon on the background thread. + SkBitmap decoded_icon_; + + // Whether the icon loading operation has been stopped. The process should + // be aborted then, and |icon_callback_| must not be invoked anymore. + bool stopped_ = false; }; } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc index df73355f7ad..f0b678602c2 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader_test.cc @@ -28,10 +28,11 @@ enum class BackgroundFetchLoadState { constexpr char kBackgroundFetchImageLoaderBaseUrl[] = "http://test.com/"; constexpr char kBackgroundFetchImageLoaderBaseDir[] = "notifications/"; +constexpr char kBackgroundFetchImageLoaderIcon500x500FullPath[] = + "http://test.com/500x500.png"; constexpr char kBackgroundFetchImageLoaderIcon500x500[] = "500x500.png"; constexpr char kBackgroundFetchImageLoaderIcon48x48[] = "48x48.png"; constexpr char kBackgroundFetchImageLoaderIcon3000x2000[] = "3000x2000.png"; -constexpr char kBackgroundFetchImageLoaderIcon[] = "3000x2000.png"; } // namespace @@ -44,7 +45,13 @@ class BackgroundFetchIconLoaderTest : public PageTestBase { ->UnregisterAllURLsAndClearMemoryCache(); } - void SetUp() override { PageTestBase::SetUp(IntSize()); } + void SetUp() override { + PageTestBase::SetUp(IntSize()); + GetDocument().SetBaseURLOverride(KURL(kBackgroundFetchImageLoaderBaseUrl)); + RegisterMockedURL(kBackgroundFetchImageLoaderIcon500x500); + RegisterMockedURL(kBackgroundFetchImageLoaderIcon48x48); + RegisterMockedURL(kBackgroundFetchImageLoaderIcon3000x2000); + } // Registers a mocked URL. WebURL RegisterMockedURL(const String& file_name) { @@ -57,40 +64,50 @@ class BackgroundFetchIconLoaderTest : public PageTestBase { // Callback for BackgroundFetchIconLoader. This will set up the state of the // load as either success or failed based on whether the bitmap is empty. - void IconLoaded(const SkBitmap& bitmap) { - if (!bitmap.empty()) + void IconLoaded(base::OnceClosure quit_closure, const SkBitmap& bitmap) { + bitmap_ = bitmap; + + if (!bitmap_.isNull()) loaded_ = BackgroundFetchLoadState::kLoadSuccessful; else loaded_ = BackgroundFetchLoadState::kLoadFailed; + + std::move(quit_closure).Run(); } ManifestImageResource CreateTestIcon(const String& url_str, const String& size) { - KURL url = RegisterMockedURL(url_str); ManifestImageResource icon; - icon.setSrc(url.GetString()); + icon.setSrc(url_str); icon.setType("image/png"); icon.setSizes(size); + icon.setPurpose("any"); return icon; } - int PickRightIcon(HeapVector<ManifestImageResource> icons, - const WebSize& ideal_display_size) { + KURL PickRightIcon(HeapVector<ManifestImageResource> icons, + const WebSize& ideal_display_size) { loader_->icons_ = std::move(icons); - return loader_->PickBestIconForDisplay(GetContext(), ideal_display_size); + loader_->icon_display_size_pixels_ = ideal_display_size; + + return loader_->PickBestIconForDisplay(GetContext()); } - void LoadIcon(const KURL& url) { + void LoadIcon(const KURL& url, + const WebSize& maximum_size, + base::OnceClosure quit_closure) { ManifestImageResource icon; icon.setSrc(url.GetString()); icon.setType("image/png"); icon.setSizes("500x500"); + icon.setPurpose("ANY"); HeapVector<ManifestImageResource> icons(1, icon); loader_->icons_ = std::move(icons); loader_->DidGetIconDisplaySizeIfSoLoadIcon( GetContext(), - Bind(&BackgroundFetchIconLoaderTest::IconLoaded, WTF::Unretained(this)), - WebSize(192, 192)); + WTF::Bind(&BackgroundFetchIconLoaderTest::IconLoaded, + WTF::Unretained(this), WTF::Passed(std::move(quit_closure))), + maximum_size); } ExecutionContext* GetContext() const { return &GetDocument(); } @@ -98,67 +115,70 @@ class BackgroundFetchIconLoaderTest : public PageTestBase { protected: ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; BackgroundFetchLoadState loaded_ = BackgroundFetchLoadState::kNotLoaded; + SkBitmap bitmap_; private: Persistent<BackgroundFetchIconLoader> loader_; }; TEST_F(BackgroundFetchIconLoaderTest, SuccessTest) { - KURL url = RegisterMockedURL(kBackgroundFetchImageLoaderIcon500x500); - LoadIcon(url); + base::RunLoop run_loop; + + WebSize maximum_size{192, 168}; + LoadIcon(KURL(kBackgroundFetchImageLoaderIcon500x500FullPath), maximum_size, + run_loop.QuitClosure()); + platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); - EXPECT_EQ(BackgroundFetchLoadState::kLoadSuccessful, loaded_); -} -TEST_F(BackgroundFetchIconLoaderTest, PickRightIconTest) { - ManifestImageResource icon0 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500"); - ManifestImageResource icon1 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon48x48, "48x48"); - ManifestImageResource icon2 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon3000x2000, "3000x2000"); + run_loop.Run(); - HeapVector<ManifestImageResource> icons; - icons.push_back(icon0); - icons.push_back(icon1); - icons.push_back(icon2); + ASSERT_EQ(BackgroundFetchLoadState::kLoadSuccessful, loaded_); + ASSERT_FALSE(bitmap_.drawsNothing()); - int index = PickRightIcon(std::move(icons), WebSize(50, 50)); - EXPECT_EQ(index, 1); + // Resizing a 500x500 image to fit on a canvas of 192x168 pixels should yield + // a decoded image size of 168x168, avoiding image data to get lost. + EXPECT_EQ(bitmap_.width(), 168); + EXPECT_EQ(bitmap_.height(), 168); } -TEST_F(BackgroundFetchIconLoaderTest, PickRightIconGivenAnyTest) { - ManifestImageResource icon0 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500"); - ManifestImageResource icon1 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon48x48, "48x48"); - ManifestImageResource icon2 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon, "any"); +TEST_F(BackgroundFetchIconLoaderTest, PickIconRelativePath) { + HeapVector<ManifestImageResource> icons; + icons.push_back( + CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500")); + KURL best_icon = PickRightIcon(std::move(icons), WebSize(500, 500)); + ASSERT_TRUE(best_icon.IsValid()); + EXPECT_EQ(best_icon, KURL(kBackgroundFetchImageLoaderIcon500x500FullPath)); +} + +TEST_F(BackgroundFetchIconLoaderTest, PickIconFullPath) { HeapVector<ManifestImageResource> icons; - icons.push_back(icon0); - icons.push_back(icon1); - icons.push_back(icon2); + icons.push_back(CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500FullPath, + "500x500")); - int index = PickRightIcon(std::move(icons), WebSize(50, 50)); - EXPECT_EQ(index, 2); + KURL best_icon = PickRightIcon(std::move(icons), WebSize(500, 500)); + ASSERT_TRUE(best_icon.IsValid()); + EXPECT_EQ(best_icon, KURL(kBackgroundFetchImageLoaderIcon500x500FullPath)); } -TEST_F(BackgroundFetchIconLoaderTest, PickRightIconWithTieBreakTest) { - // Test that if two icons get the same score, the one declared last gets - // picked. +TEST_F(BackgroundFetchIconLoaderTest, PickRightIcon) { ManifestImageResource icon0 = CreateTestIcon(kBackgroundFetchImageLoaderIcon500x500, "500x500"); ManifestImageResource icon1 = CreateTestIcon(kBackgroundFetchImageLoaderIcon48x48, "48x48"); ManifestImageResource icon2 = - CreateTestIcon(kBackgroundFetchImageLoaderIcon3000x2000, "48x48"); + CreateTestIcon(kBackgroundFetchImageLoaderIcon3000x2000, "3000x2000"); + HeapVector<ManifestImageResource> icons; icons.push_back(icon0); icons.push_back(icon1); icons.push_back(icon2); - int index = PickRightIcon(std::move(icons), WebSize(50, 50)); - EXPECT_EQ(index, 2); + + KURL best_icon = PickRightIcon(std::move(icons), WebSize(42, 42)); + ASSERT_TRUE(best_icon.IsValid()); + // We expect the smallest Icon larger than the ideal display size. + EXPECT_EQ(best_icon, KURL(KURL(kBackgroundFetchImageLoaderBaseUrl), + kBackgroundFetchImageLoaderIcon48x48)); } } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc index 04edc0b08dc..dbe549d7100 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.cc @@ -4,11 +4,15 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h" +#include "base/memory/scoped_refptr.h" +#include "base/metrics/histogram_macros.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_request.h" #include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/request_or_usv_string_or_request_or_usv_string_sequence.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/core/fetch/body.h" +#include "third_party/blink/renderer/core/fetch/body_stream_buffer.h" #include "third_party/blink/renderer/core/fetch/request.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" #include "third_party/blink/renderer/core/frame/deprecation.h" @@ -20,8 +24,10 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h" #include "third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.h" #include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h" +#include "third_party/blink/renderer/platform/bindings/exception_code.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" +#include "third_party/blink/renderer/platform/blob/blob_data.h" #include "third_party/blink/renderer/platform/loader/cors/cors.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h" #include "third_party/blink/renderer/platform/network/network_utils.h" @@ -29,7 +35,6 @@ #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/skia/include/core/SkBitmap.h" - namespace blink { namespace { @@ -85,22 +90,8 @@ bool ShouldBlockMixedContent(ExecutionContext* execution_context, const KURL& request_url) { // TODO(crbug.com/757441): Using MixedContentChecker::ShouldBlockFetch would // log better metrics. - if (MixedContentChecker::IsMixedContent( - execution_context->GetSecurityOrigin(), request_url)) { - return true; - } - - // Normally requests from e.g. http://127.0.0.1 aren't subject to Mixed - // Content checks even though that is a secure context. Since this is a new - // API only exposed on secure contexts, be strict pending the discussion in - // https://groups.google.com/a/chromium.org/d/topic/security-dev/29Ftfgn-w0I/discussion - // https://w3c.github.io/webappsec-mixed-content/#a-priori-authenticated-url - if (!SecurityOrigin::Create(request_url)->IsPotentiallyTrustworthy() && - !request_url.ProtocolIsData()) { - return true; - } - - return false; + return MixedContentChecker::IsMixedContent( + execution_context->GetSecurityOrigin(), request_url); } bool ShouldBlockDanglingMarkup(const KURL& request_url) { @@ -156,6 +147,31 @@ bool ShouldBlockCORSPreflight(ExecutionContext* execution_context, return false; } +scoped_refptr<BlobDataHandle> ExtractBlobHandle( + Request* request, + ExceptionState& exception_state) { + DCHECK(request); + + if (request->IsBodyLocked(exception_state) == Body::BodyLocked::kLocked || + request->IsBodyUsed(exception_state) == Body::BodyUsed::kUsed) { + DCHECK(!exception_state.HadException()); + exception_state.ThrowTypeError("Request body is already used"); + return nullptr; + } + + BodyStreamBuffer* buffer = request->BodyBuffer(); + if (!buffer) + return nullptr; + + auto blob_handle = buffer->DrainAsBlobDataHandle( + BytesConsumer::BlobSizePolicy::kDisallowBlobWithInvalidSize, + exception_state); + if (exception_state.HadException()) + return nullptr; + + return blob_handle; +} + } // namespace BackgroundFetchManager::BackgroundFetchManager( @@ -209,6 +225,14 @@ ScriptPromise BackgroundFetchManager::fetch( "that URL is invalid"); } + // https://wicg.github.io/background-fetch/#dom-backgroundfetchmanager-fetch + // ""If |internalRequest|’s mode is "no-cors", then return a promise + // rejected with a TypeError."" + if (web_request.Mode() == network::mojom::FetchRequestMode::kNoCORS) { + return RejectWithTypeError(script_state, request_url, + "the request mode must not be no-cors"); + } + // Check this before mixed content, so that if mixed content is blocked by // CSP they get a CSP warning rather than a mixed content warning. if (ShouldBlockDueToCSP(execution_context, request_url)) { @@ -267,8 +291,8 @@ ScriptPromise BackgroundFetchManager::fetch( return promise; } - DidLoadIcons(id, std::move(web_requests), std::move(options_ptr), - WrapPersistent(resolver), SkBitmap()); + DidLoadIcons(id, std::move(web_requests), std::move(options_ptr), resolver, + SkBitmap()); return promise; } @@ -278,15 +302,23 @@ void BackgroundFetchManager::DidLoadIcons( mojom::blink::BackgroundFetchOptionsPtr options, ScriptPromiseResolver* resolver, const SkBitmap& icon) { - bridge_->Fetch(id, std::move(web_requests), std::move(options), icon, - WTF::Bind(&BackgroundFetchManager::DidFetch, - WrapPersistent(this), WrapPersistent(resolver))); + bridge_->Fetch( + id, std::move(web_requests), std::move(options), icon, + WTF::Bind(&BackgroundFetchManager::DidFetch, WrapPersistent(this), + WrapPersistent(resolver), base::Time::Now())); } void BackgroundFetchManager::DidFetch( ScriptPromiseResolver* resolver, + base::Time time_started, mojom::blink::BackgroundFetchError error, BackgroundFetchRegistration* registration) { + UMA_HISTOGRAM_TIMES("BackgroundFetch.Manager.FetchDuration", + base::Time::Now() - time_started); + + ScriptState* script_state = resolver->GetScriptState(); + ScriptState::Scope scope(script_state); + switch (error) { case mojom::blink::BackgroundFetchError::NONE: DCHECK(registration); @@ -294,21 +326,30 @@ void BackgroundFetchManager::DidFetch( return; case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: DCHECK(!registration); - resolver->Reject(DOMException::Create( - DOMExceptionCode::kInvalidStateError, + resolver->Reject(V8ThrowException::CreateTypeError( + script_state->GetIsolate(), "There already is a registration for the given id.")); return; + case mojom::blink::BackgroundFetchError::PERMISSION_DENIED: + resolver->Reject(V8ThrowException::CreateTypeError( + script_state->GetIsolate(), + "This origin does not have permission to start a fetch.")); + return; case mojom::blink::BackgroundFetchError::STORAGE_ERROR: DCHECK(!registration); - resolver->Reject(DOMException::Create( - DOMExceptionCode::kAbortError, + resolver->Reject(V8ThrowException::CreateTypeError( + script_state->GetIsolate(), "Failed to store registration due to I/O error.")); return; case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: - resolver->Reject(DOMException::Create( - DOMExceptionCode::kInvalidStateError, + resolver->Reject(V8ThrowException::CreateTypeError( + script_state->GetIsolate(), "There is no service worker available to service the fetch.")); return; + case mojom::blink::BackgroundFetchError::QUOTA_EXCEEDED: + resolver->Reject(DOMException::Create( + DOMExceptionCode::kQuotaExceededError, "Quota exceeded.")); + return; case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: case mojom::blink::BackgroundFetchError::INVALID_ID: // Not applicable for this callback. @@ -320,20 +361,18 @@ void BackgroundFetchManager::DidFetch( ScriptPromise BackgroundFetchManager::get(ScriptState* script_state, const String& id) { - if (!registration_->active()) { - return ScriptPromise::Reject( - script_state, - V8ThrowException::CreateTypeError(script_state->GetIsolate(), - "No active registration available on " - "the ServiceWorkerRegistration.")); - } + // Creating a Background Fetch registration requires an activated worker, so + // if |registration_| has not been activated we can skip the Mojo roundtrip. + if (!registration_->active()) + return ScriptPromise::CastUndefined(script_state); ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); bridge_->GetRegistration( id, WTF::Bind(&BackgroundFetchManager::DidGetRegistration, - WrapPersistent(this), WrapPersistent(resolver))); + WrapPersistent(this), WrapPersistent(resolver), + base::Time::Now())); return promise; } @@ -375,11 +414,15 @@ Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector( DCHECK(request); request->PopulateWebServiceWorkerRequest(web_requests[i]); + web_requests[i].SetBlobDataHandle( + ExtractBlobHandle(request, exception_state)); } } else if (requests.IsRequest()) { DCHECK(requests.GetAsRequest()); web_requests.resize(1); requests.GetAsRequest()->PopulateWebServiceWorkerRequest(web_requests[0]); + web_requests[0].SetBlobDataHandle( + ExtractBlobHandle(requests.GetAsRequest(), exception_state)); } else if (requests.IsUSVString()) { Request* request = Request::Create(script_state, requests.GetAsUSVString(), exception_state); @@ -399,13 +442,24 @@ Vector<WebServiceWorkerRequest> BackgroundFetchManager::CreateWebRequestVector( void BackgroundFetchManager::DidGetRegistration( ScriptPromiseResolver* resolver, + base::Time time_started, mojom::blink::BackgroundFetchError error, BackgroundFetchRegistration* registration) { + UMA_HISTOGRAM_TIMES("BackgroundFetch.Manager.GetDuration", + base::Time::Now() - time_started); + + ScriptState* script_state = resolver->GetScriptState(); + ScriptState::Scope scope(script_state); + switch (error) { case mojom::blink::BackgroundFetchError::NONE: - case mojom::blink::BackgroundFetchError::INVALID_ID: + DCHECK(registration); resolver->Resolve(registration); return; + case mojom::blink::BackgroundFetchError::INVALID_ID: + DCHECK(!registration); + resolver->Resolve(v8::Undefined(script_state->GetIsolate())); + return; case mojom::blink::BackgroundFetchError::STORAGE_ERROR: DCHECK(!registration); resolver->Reject( @@ -419,6 +473,8 @@ void BackgroundFetchManager::DidGetRegistration( return; case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: + case mojom::blink::BackgroundFetchError::PERMISSION_DENIED: + case mojom::blink::BackgroundFetchError::QUOTA_EXCEEDED: // Not applicable for this callback. break; } @@ -427,28 +483,33 @@ void BackgroundFetchManager::DidGetRegistration( } ScriptPromise BackgroundFetchManager::getIds(ScriptState* script_state) { + // Creating a Background Fetch registration requires an activated worker, so + // if |registration_| has not been activated we can skip the Mojo roundtrip. if (!registration_->active()) { - return ScriptPromise::Reject( - script_state, - V8ThrowException::CreateTypeError(script_state->GetIsolate(), - "No active registration available on " - "the ServiceWorkerRegistration.")); + return ScriptPromise::Cast(script_state, + v8::Array::New(script_state->GetIsolate())); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); - bridge_->GetDeveloperIds( - WTF::Bind(&BackgroundFetchManager::DidGetDeveloperIds, - WrapPersistent(this), WrapPersistent(resolver))); + bridge_->GetDeveloperIds(WTF::Bind( + &BackgroundFetchManager::DidGetDeveloperIds, WrapPersistent(this), + WrapPersistent(resolver), base::Time::Now())); return promise; } void BackgroundFetchManager::DidGetDeveloperIds( ScriptPromiseResolver* resolver, + base::Time time_started, mojom::blink::BackgroundFetchError error, const Vector<String>& developer_ids) { + UMA_HISTOGRAM_TIMES("BackgroundFetch.Manager.GetIdsDuration", + base::Time::Now() - time_started); + + ScriptState::Scope scope(resolver->GetScriptState()); + switch (error) { case mojom::blink::BackgroundFetchError::NONE: resolver->Resolve(developer_ids); @@ -462,7 +523,9 @@ void BackgroundFetchManager::DidGetDeveloperIds( case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: case mojom::blink::BackgroundFetchError::INVALID_ID: + case mojom::blink::BackgroundFetchError::PERMISSION_DENIED: case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: + case mojom::blink::BackgroundFetchError::QUOTA_EXCEEDED: // Not applicable for this callback. break; } diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h index 0c543914025..ac445e7d1d0 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager.h @@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_MANAGER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_MANAGER_H_ +#include "base/time/time.h" #include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h" @@ -77,12 +78,15 @@ class MODULES_EXPORT BackgroundFetchManager final ScriptPromiseResolver* resolver, const SkBitmap& icon); void DidFetch(ScriptPromiseResolver* resolver, + base::Time time_started, mojom::blink::BackgroundFetchError error, BackgroundFetchRegistration* registration); void DidGetRegistration(ScriptPromiseResolver* script_state, + base::Time time_started, mojom::blink::BackgroundFetchError error, BackgroundFetchRegistration* registration); void DidGetDeveloperIds(ScriptPromiseResolver* script_state, + base::Time time_started, mojom::blink::BackgroundFetchError error, const Vector<String>& developer_ids); diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc index c962f63da35..063d42f25d4 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_manager_test.cc @@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/fetch/request_init.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/blob/blob_data.h" namespace blink { @@ -175,4 +176,48 @@ TEST_F(BackgroundFetchManagerTest, SequenceWithNullValue) { ESErrorType::kTypeError); } +TEST_F(BackgroundFetchManagerTest, BlobsExtracted) { + V8TestingScope scope; + + KURL image_url("https://www.example.com/my_image.png"); + KURL icon_url("https://www.example.com/my_icon.jpg"); + + // Create first request with a body. + String body_text = "cat_pic"; + RequestInit request_init; + request_init.setMethod("POST"); + request_init.setBody(blink::ScriptValue( + scope.GetScriptState(), ToV8(body_text, scope.GetScriptState()))); + Request* image_request = + Request::Create(scope.GetScriptState(), image_url.GetString(), + request_init, scope.GetExceptionState()); + ASSERT_FALSE(scope.GetExceptionState().HadException()); + ASSERT_TRUE(image_request); + ASSERT_TRUE(image_request->HasBody()); + + // Create second request without a body. + RequestOrUSVString icon_request = + RequestOrUSVString::FromUSVString(icon_url.GetString()); + + // Create a request sequence with both requests. + HeapVector<RequestOrUSVString> request_sequence; + request_sequence.push_back(RequestOrUSVString::FromRequest(image_request)); + request_sequence.push_back(icon_request); + + RequestOrUSVStringOrRequestOrUSVStringSequence requests = + RequestOrUSVStringOrRequestOrUSVStringSequence:: + FromRequestOrUSVStringSequence(request_sequence); + + // Extract the blobs. + auto web_requests = CreateWebRequestVector(scope, requests); + ASSERT_FALSE(scope.GetExceptionState().HadException()); + + ASSERT_EQ(web_requests.size(), 2u); + + ASSERT_TRUE(web_requests[0].GetBlobDataHandle()); + EXPECT_EQ(web_requests[0].GetBlobDataHandle()->size(), body_text.length()); + + EXPECT_FALSE(web_requests[1].GetBlobDataHandle()); +} + } // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_options.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_options.idl index c80d491e1ce..c30c3686396 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_options.idl +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_options.idl @@ -2,11 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://wicg.github.io/background-fetch/#background-fetch-manager +// https://wicg.github.io/background-fetch/#dictdef-backgroundfetchoptions -dictionary BackgroundFetchOptions { - sequence<ImageResource> icons = []; - DOMString title = ""; - [ImplementedAs=downloadTotal] unsigned long long totalDownloadSize = 0; +dictionary BackgroundFetchOptions : BackgroundFetchUIOptions { unsigned long long downloadTotal = 0; }; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc new file mode 100644 index 00000000000..a7dd3a6581b --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.cc @@ -0,0 +1,46 @@ +// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_record.h" + +#include "third_party/blink/renderer/core/fetch/request.h" +#include "third_party/blink/renderer/core/fetch/response.h" + +namespace blink { + +BackgroundFetchRecord::BackgroundFetchRecord(Request* request, + Response* response) + : request_(request), response_(response) { + DCHECK(request_); +} + +BackgroundFetchRecord::~BackgroundFetchRecord() = default; + +ScriptPromise BackgroundFetchRecord::responseReady(ScriptState* script_state) { + if (!response_ready_property_) { + response_ready_property_ = + new ResponseReadyProperty(ExecutionContext::From(script_state), this, + ResponseReadyProperty::kResponseReady); + } + if (!response_) { + response_ = Response::Create(ExecutionContext::From(script_state), + nullptr /* FetchResponseData */); + } + DCHECK(response_); + response_ready_property_->Resolve(response_); + return response_ready_property_->Promise(script_state->World()); +} + +Request* BackgroundFetchRecord::request() const { + return request_; +} + +void BackgroundFetchRecord::Trace(blink::Visitor* visitor) { + visitor->Trace(request_); + visitor->Trace(response_); + visitor->Trace(response_ready_property_); + ScriptWrappable::Trace(visitor); +} + +} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h new file mode 100644 index 00000000000..4ff0a63b6cf --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.h @@ -0,0 +1,45 @@ +// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_RECORD_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_RECORD_H_ + +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h" +#include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/heap/handle.h" + +namespace blink { + +class Request; +class Response; + +class MODULES_EXPORT BackgroundFetchRecord final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + explicit BackgroundFetchRecord(Request* request, + Response* response = nullptr); + ~BackgroundFetchRecord() override; + + Request* request() const; + ScriptPromise responseReady(ScriptState* script_state); + + void Trace(blink::Visitor* visitor) override; + + private: + using ResponseReadyProperty = + ScriptPromiseProperty<Member<BackgroundFetchRecord>, + Member<Response>, + Member<DOMException>>; + Member<Request> request_; + Member<Response> response_; + Member<ResponseReadyProperty> response_ready_property_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_RECORD_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.idl new file mode 100644 index 00000000000..a3e4080f498 --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_record.idl @@ -0,0 +1,13 @@ +// Copyright 2018 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. + +// https://wicg.github.io/background-fetch/#background-fetch-record + +[ + Exposed=(ServiceWorker), + RuntimeEnabled=BackgroundFetch +] interface BackgroundFetchRecord { + readonly attribute Request request; + [CallWith=ScriptState] readonly attribute Promise<Response> responseReady; +};
\ No newline at end of file diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc index 15567ad0284..bf5b6d9e84c 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.cc @@ -4,9 +4,18 @@ #include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h" +#include "base/optional.h" +#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_registration.h" +#include "third_party/blink/public/platform/modules/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/fetch/request.h" +#include "third_party/blink/renderer/core/fetch/response.h" #include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_record.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" +#include "third_party/blink/renderer/modules/cache_storage/cache.h" +#include "third_party/blink/renderer/modules/cache_storage/cache_query_options.h" #include "third_party/blink/renderer/modules/event_target_modules_names.h" #include "third_party/blink/renderer/modules/manifest/image_resource.h" #include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h" @@ -20,15 +29,35 @@ BackgroundFetchRegistration::BackgroundFetchRegistration( unsigned long long upload_total, unsigned long long uploaded, unsigned long long download_total, - unsigned long long downloaded) + unsigned long long downloaded, + mojom::BackgroundFetchState state, + mojom::BackgroundFetchFailureReason failure_reason) : developer_id_(developer_id), unique_id_(unique_id), upload_total_(upload_total), uploaded_(uploaded), download_total_(download_total), downloaded_(downloaded), + state_(state), + failure_reason_(failure_reason), observer_binding_(this) {} +BackgroundFetchRegistration::BackgroundFetchRegistration( + ServiceWorkerRegistration* registration, + const WebBackgroundFetchRegistration& web_registration) + : developer_id_(web_registration.developer_id), + unique_id_(web_registration.unique_id), + upload_total_(web_registration.upload_total), + uploaded_(web_registration.uploaded), + download_total_(web_registration.download_total), + downloaded_(web_registration.downloaded), + state_(web_registration.state), + failure_reason_(web_registration.failure_reason), + observer_binding_(this) { + DCHECK(registration); + Initialize(registration); +} + BackgroundFetchRegistration::~BackgroundFetchRegistration() = default; void BackgroundFetchRegistration::Initialize( @@ -59,7 +88,7 @@ void BackgroundFetchRegistration::OnProgress(uint64_t upload_total, return; DCHECK(context->IsContextThread()); - DispatchEvent(Event::Create(EventTypeNames::progress)); + DispatchEvent(*Event::Create(EventTypeNames::progress)); } String BackgroundFetchRegistration::id() const { @@ -104,15 +133,109 @@ ScriptPromise BackgroundFetchRegistration::abort(ScriptState* script_state) { return promise; } +ScriptPromise BackgroundFetchRegistration::match( + ScriptState* script_state, + const RequestOrUSVString& request, + const CacheQueryOptions& options, + ExceptionState& exception_state) { + return MatchImpl( + script_state, base::make_optional<RequestOrUSVString>(request), + Cache::ToQueryParams(options), exception_state, /* match_all = */ false); +} + +ScriptPromise BackgroundFetchRegistration::matchAll( + ScriptState* script_state, + ExceptionState& exception_state) { + return MatchImpl(script_state, /* request = */ base::nullopt, + /* cache_query_options = */ nullptr, exception_state, + /* match_all = */ true); +} + +ScriptPromise BackgroundFetchRegistration::matchAll( + ScriptState* script_state, + const RequestOrUSVString& request, + const CacheQueryOptions& options, + ExceptionState& exception_state) { + return MatchImpl( + script_state, base::make_optional<RequestOrUSVString>(request), + Cache::ToQueryParams(options), exception_state, /* match_all = */ true); +} + +ScriptPromise BackgroundFetchRegistration::MatchImpl( + ScriptState* script_state, + base::Optional<RequestOrUSVString> request, + mojom::blink::QueryParamsPtr cache_query_params, + ExceptionState& exception_state, + bool match_all) { + ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); + ScriptPromise promise = resolver->Promise(); + + // Convert |request| to WebServiceWorkerRequest. + base::Optional<WebServiceWorkerRequest> request_to_match; + if (request.has_value()) { + if (request->IsRequest()) { + request->GetAsRequest()->PopulateWebServiceWorkerRequest( + request_to_match.value()); + } else { + Request* new_request = Request::Create( + script_state, request->GetAsUSVString(), exception_state); + if (exception_state.HadException()) + return ScriptPromise(); + new_request->PopulateWebServiceWorkerRequest(request_to_match.value()); + } + } + + DCHECK(registration_); + + BackgroundFetchBridge::From(registration_) + ->MatchRequests( + developer_id_, unique_id_, request_to_match, + std::move(cache_query_params), match_all, + WTF::Bind(&BackgroundFetchRegistration::DidGetMatchingRequests, + WrapPersistent(this), WrapPersistent(resolver), match_all)); + return promise; +} + +void BackgroundFetchRegistration::DidGetMatchingRequests( + ScriptPromiseResolver* resolver, + bool return_all, + Vector<mojom::blink::BackgroundFetchSettledFetchPtr> settled_fetches) { + ScriptState* script_state = resolver->GetScriptState(); + // Do not remove this, |scope| is needed for calling ToV8() + ScriptState::Scope scope(script_state); + HeapVector<Member<BackgroundFetchRecord>> to_return; + to_return.ReserveInitialCapacity(settled_fetches.size()); + for (const auto& fetch : settled_fetches) { + if (fetch->response->response_type == + network::mojom::FetchResponseType::kError) { + // Resolve with undefined. + resolver->Resolve(); + return; + } + BackgroundFetchRecord* record = new BackgroundFetchRecord( + Request::Create(script_state, fetch->request), + Response::Create(script_state, *fetch->response)); + to_return.push_back(record); + } + + if (!return_all) { + DCHECK_EQ(settled_fetches.size(), 1u); + DCHECK_EQ(to_return.size(), 1u); + resolver->Resolve(to_return[0]); + return; + } + resolver->Resolve(to_return); +} + void BackgroundFetchRegistration::DidAbort( ScriptPromiseResolver* resolver, mojom::blink::BackgroundFetchError error) { switch (error) { case mojom::blink::BackgroundFetchError::NONE: - resolver->Resolve(true /* success */); + resolver->Resolve(/* success = */ true); return; case mojom::blink::BackgroundFetchError::INVALID_ID: - resolver->Resolve(false /* success */); + resolver->Resolve(/* success = */ false); return; case mojom::blink::BackgroundFetchError::STORAGE_ERROR: resolver->Reject(DOMException::Create( @@ -122,6 +245,8 @@ void BackgroundFetchRegistration::DidAbort( case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: + case mojom::blink::BackgroundFetchError::PERMISSION_DENIED: + case mojom::blink::BackgroundFetchError::QUOTA_EXCEEDED: // Not applicable for this callback. break; } @@ -129,11 +254,43 @@ void BackgroundFetchRegistration::DidAbort( NOTREACHED(); } +const String BackgroundFetchRegistration::state() const { + switch (state_) { + case mojom::BackgroundFetchState::SUCCESS: + return "success"; + case mojom::BackgroundFetchState::FAILURE: + return "failure"; + case mojom::BackgroundFetchState::PENDING: + return "pending"; + } + NOTREACHED(); +} + +const String BackgroundFetchRegistration::failureReason() const { + switch (failure_reason_) { + case mojom::BackgroundFetchFailureReason::NONE: + return ""; + case mojom::BackgroundFetchFailureReason::CANCELLED_FROM_UI: + case mojom::BackgroundFetchFailureReason::CANCELLED_BY_DEVELOPER: + return "aborted"; + case mojom::BackgroundFetchFailureReason::BAD_STATUS: + return "bad-status"; + case mojom::BackgroundFetchFailureReason::SERVICE_WORKER_UNAVAILABLE: + case mojom::BackgroundFetchFailureReason::FETCH_ERROR: + return "fetch-error"; + case mojom::BackgroundFetchFailureReason::QUOTA_EXCEEDED: + return "quota-exceeded"; + case mojom::BackgroundFetchFailureReason::TOTAL_DOWNLOAD_SIZE_EXCEEDED: + return "total-download-exceeded"; + } + NOTREACHED(); +} + void BackgroundFetchRegistration::Dispose() { observer_binding_.Close(); } -void BackgroundFetchRegistration::Trace(blink::Visitor* visitor) { +void BackgroundFetchRegistration::Trace(Visitor* visitor) { visitor->Trace(registration_); EventTargetWithInlineData::Trace(visitor); } diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h index 9a53882be32..4d94efee4b5 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h @@ -16,9 +16,12 @@ namespace blink { +class CacheQueryOptions; class ScriptPromiseResolver; class ScriptState; class ServiceWorkerRegistration; +class RequestOrUSVString; +struct WebBackgroundFetchRegistration; // Represents an individual Background Fetch registration. Gives developers // access to its properties, options, and enables them to abort the fetch. @@ -29,12 +32,20 @@ class BackgroundFetchRegistration final USING_PRE_FINALIZER(BackgroundFetchRegistration, Dispose); public: - BackgroundFetchRegistration(const String& developer_id, - const String& unique_id, - unsigned long long upload_total, - unsigned long long uploaded, - unsigned long long download_total, - unsigned long long downloaded); + BackgroundFetchRegistration( + const String& developer_id, + const String& unique_id, + unsigned long long upload_total, + unsigned long long uploaded, + unsigned long long download_total, + unsigned long long downloaded, + mojom::BackgroundFetchState state, + mojom::BackgroundFetchFailureReason failure_reason); + + BackgroundFetchRegistration( + ServiceWorkerRegistration* registration, + const WebBackgroundFetchRegistration& web_registration); + ~BackgroundFetchRegistration() override; // Initializes the BackgroundFetchRegistration to be associated with the given @@ -51,11 +62,25 @@ class BackgroundFetchRegistration final // Web Exposed attribute defined in the IDL file. Corresponds to the // |developer_id| used elsewhere in the codebase. String id() const; + ScriptPromise match(ScriptState* script_state, + const RequestOrUSVString& request, + const CacheQueryOptions& options, + ExceptionState& exception_state); + ScriptPromise matchAll(ScriptState* scrip_state, + ExceptionState& exception_state); + ScriptPromise matchAll(ScriptState* script_state, + const RequestOrUSVString& request, + const CacheQueryOptions& options, + ExceptionState& exception_state); unsigned long long uploadTotal() const; unsigned long long uploaded() const; unsigned long long downloadTotal() const; unsigned long long downloaded() const; + const String state() const; + const String failureReason() const; + + const String& unique_id() const { return unique_id_; } DEFINE_ATTRIBUTE_EVENT_LISTENER(progress); @@ -72,6 +97,15 @@ class BackgroundFetchRegistration final private: void DidAbort(ScriptPromiseResolver* resolver, mojom::blink::BackgroundFetchError error); + ScriptPromise MatchImpl(ScriptState* script_state, + base::Optional<RequestOrUSVString> request, + mojom::blink::QueryParamsPtr cache_query_params, + ExceptionState& exception_state, + bool match_all); + void DidGetMatchingRequests( + ScriptPromiseResolver* resolver, + bool return_all, + Vector<mojom::blink::BackgroundFetchSettledFetchPtr> settled_fetches); Member<ServiceWorkerRegistration> registration_; @@ -88,6 +122,8 @@ class BackgroundFetchRegistration final unsigned long long uploaded_; unsigned long long download_total_; unsigned long long downloaded_; + mojom::BackgroundFetchState state_; + mojom::BackgroundFetchFailureReason failure_reason_; mojo::Binding<blink::mojom::blink::BackgroundFetchRegistrationObserver> observer_binding_; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.idl index e7d73a6749f..bb5a4c5bbd6 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.idl +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_registration.idl @@ -3,6 +3,22 @@ // found in the LICENSE file. // https://wicg.github.io/background-fetch/#background-fetch-registration +enum BackgroundFetchState { "pending", "success", "failure" }; + +enum BackgroundFetchFailureReason { + "", + // The operation was aborted by the user, or abort() was called. + "aborted", + // A response had a not-ok-status. + "bad-status", + // A fetch failed for other reasons, e.g. CORS, MIX, an invalid partial response, + // or a general network failure for a fetch that cannot be retried. + "fetch-error", + // Storage quota was reached during the operation. + "quota-exceeded", + // The provided downloadTotal was exceeded. + "total-download-exceeded" +}; [ Exposed=(Window,Worker), @@ -13,9 +29,15 @@ readonly attribute unsigned long long uploaded; readonly attribute unsigned long long downloadTotal; readonly attribute unsigned long long downloaded; - // TODO(crbug.com/699957): Implement the `activeFetches` attribute. + readonly attribute BackgroundFetchState state; + readonly attribute BackgroundFetchFailureReason failureReason; attribute EventHandler onprogress; [CallWith=ScriptState] Promise<boolean> abort(); + + // TODO(crbug.com/875201): Change to (Window,Worker) once we support + // match() and matchAll() for active fetches. + [CallWith=ScriptState, Exposed=ServiceWorker, RaisesException] Promise<BackgroundFetchRecord> match(RequestInfo request, optional CacheQueryOptions options); + [CallWith=ScriptState, Exposed=ServiceWorker, RaisesException] Promise<sequence<BackgroundFetchRecord>> matchAll(optional RequestInfo request, optional CacheQueryOptions options); }; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.cc deleted file mode 100644 index 68f65c9c871..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.h" - -namespace blink { - -BackgroundFetchSettledEvent::BackgroundFetchSettledEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer, - const String& unique_id, - WaitUntilObserver* observer) - : BackgroundFetchEvent(type, initializer, observer), - unique_id_(unique_id), - fetches_(*initializer.fetches()) {} - -BackgroundFetchSettledEvent::BackgroundFetchSettledEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer) - : BackgroundFetchEvent(type, initializer, nullptr), - fetches_(*initializer.fetches()) {} - -BackgroundFetchSettledEvent::~BackgroundFetchSettledEvent() = default; - -BackgroundFetchSettledFetches* BackgroundFetchSettledEvent::fetches() const { - return fetches_; -} - -void BackgroundFetchSettledEvent::Trace(blink::Visitor* visitor) { - visitor->Trace(fetches_); - BackgroundFetchEvent::Trace(visitor); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.h deleted file mode 100644 index ec39d90d81f..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_EVENT_H_ - -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event_init.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/heap/member.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" - -namespace blink { - -// Event for interacting with fetch requests that have completed. -class MODULES_EXPORT BackgroundFetchSettledEvent : public BackgroundFetchEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchSettledEvent* Create( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer) { - return new BackgroundFetchSettledEvent(type, initializer); - } - - static BackgroundFetchSettledEvent* Create( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer, - const String& unique_id, - WaitUntilObserver* observer = nullptr) { - return new BackgroundFetchSettledEvent(type, initializer, unique_id, - observer); - } - - ~BackgroundFetchSettledEvent() override; - - // Web Exposed attribute defined in the IDL file. - BackgroundFetchSettledFetches* fetches() const; - - void Trace(blink::Visitor* visitor) override; - - protected: - BackgroundFetchSettledEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer, - const String& unique_id, - WaitUntilObserver* observer = nullptr); - - BackgroundFetchSettledEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer); - - // Globally unique ID for the registration, generated in content/. Used to - // distinguish registrations in case a developer re-uses |developer_id_|s. Not - // exposed to JavaScript. - String unique_id_; - - private: - Member<BackgroundFetchSettledFetches> fetches_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.idl deleted file mode 100644 index cabb460b20a..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.idl +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2018 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. - -// https://wicg.github.io/background-fetch/#backgroundfetchsettledevent - -[ - Constructor(DOMString type, BackgroundFetchSettledEventInit init), - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] interface BackgroundFetchSettledEvent : BackgroundFetchEvent { - readonly attribute BackgroundFetchSettledFetches fetches; -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event_init.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event_init.idl deleted file mode 100644 index d65dc5198d5..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event_init.idl +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2018 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. - -// https://wicg.github.io/background-fetch/#backgroundfetchsettledevent - -dictionary BackgroundFetchSettledEventInit : BackgroundFetchEventInit { - required BackgroundFetchSettledFetches fetches; -};
\ No newline at end of file diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h index e82979af9f9..49831fedcb0 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h @@ -14,8 +14,8 @@ class Request; class Response; // Interface for providing developers access to the Request/Response pairs when -// a background fetch has settled, either through the `backgroundfetched` event -// in case of success, or `backgroundfetchfail` in case of failure. +// a background fetch has settled, either through the `backgroundfetchsuccess` +// event in case of success, or `backgroundfetchfail` in case of failure. class BackgroundFetchSettledFetch final : public BackgroundFetchFetch { DEFINE_WRAPPERTYPEINFO(); diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.cc deleted file mode 100644 index 0b8c0b22b73..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.cc +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h" - -#include "third_party/blink/renderer/core/fetch/request.h" -#include "third_party/blink/renderer/core/fetch/response.h" - -namespace blink { - -BackgroundFetchSettledFetches::BackgroundFetchSettledFetches( - ScriptState* script_state, - const WebVector<WebBackgroundFetchSettledFetch>& fetches) { - fetches_.ReserveInitialCapacity(fetches.size()); - for (const WebBackgroundFetchSettledFetch& fetch : fetches) { - auto* settled_fetch = BackgroundFetchSettledFetch::Create( - Request::Create(script_state, fetch.request), - Response::Create(script_state, fetch.response)); - fetches_.push_back(settled_fetch); - } -} - -ScriptPromise BackgroundFetchSettledFetches::match( - ScriptState* script_state, - const RequestOrUSVString& request) { - for (const auto& fetch : fetches_) { - if (request.IsNull()) - continue; - - String request_string = request.IsUSVString() - ? request.GetAsUSVString() - : request.GetAsRequest()->url().GetString(); - - // TODO(crbug.com/824765): Update the resolve condition once behavior of - // match is defined. - if (request_string == fetch->request()->url()) - return ScriptPromise::Cast(script_state, ToV8(fetch, script_state)); - } - return ScriptPromise::Cast(script_state, - v8::Null(script_state->GetIsolate())); -} - -ScriptPromise BackgroundFetchSettledFetches::values(ScriptState* script_state) { - return ScriptPromise::Cast(script_state, ToV8(fetches_, script_state)); -} - -void BackgroundFetchSettledFetches::Trace(blink::Visitor* visitor) { - visitor->Trace(fetches_); - ScriptWrappable::Trace(visitor); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h deleted file mode 100644 index bc3b679fa01..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCHES_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCHES_H_ - -#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h" -#include "third_party/blink/public/platform/web_vector.h" -#include "third_party/blink/renderer/bindings/core/v8/request_or_usv_string.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/bindings/script_state.h" -#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/handle.h" - -namespace blink { - -class MODULES_EXPORT BackgroundFetchSettledFetches final - : public ScriptWrappable { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchSettledFetches* Create( - ScriptState* script_state, - const WebVector<WebBackgroundFetchSettledFetch>& fetches) { - return new BackgroundFetchSettledFetches(script_state, fetches); - } - - ~BackgroundFetchSettledFetches() override = default; - - // Web Exposed functions defined in the IDL file. - ScriptPromise match(ScriptState* script_state, - const RequestOrUSVString& request); - ScriptPromise values(ScriptState* script_state); - - void Trace(blink::Visitor* visitor) override; - - private: - BackgroundFetchSettledFetches( - ScriptState* script_state, - const WebVector<WebBackgroundFetchSettledFetch>& fetches); - - HeapVector<Member<BackgroundFetchSettledFetch>> fetches_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_SETTLED_FETCHES_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.idl deleted file mode 100644 index adf377cf254..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.idl +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2018 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. - -// https://wicg.github.io/background-fetch/#backgroundfetchsettledevent - -[ - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] interface BackgroundFetchSettledFetches { - [CallWith=ScriptState] Promise<BackgroundFetchSettledFetch> match(RequestInfo request); - [CallWith=ScriptState] Promise<FrozenArray<BackgroundFetchSettledFetch>> values(); -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches_test.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches_test.cc deleted file mode 100644 index 03eca52773a..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches_test.cc +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetches.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/renderer/bindings/core/v8/script_function.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" -#include "third_party/blink/renderer/core/fetch/request.h" - -namespace blink { - -namespace { - -WebVector<WebBackgroundFetchSettledFetch> CreateSettledFetches( - const std::vector<String>& request_urls) { - WebVector<WebBackgroundFetchSettledFetch> settled_fetches; - settled_fetches.reserve(request_urls.size()); - for (const auto& request_url : request_urls) { - WebBackgroundFetchSettledFetch settled_fetch; - settled_fetch.request.SetURL(WebURL(KURL(request_url))); - settled_fetches.emplace_back(settled_fetch); - } - return settled_fetches; -} - -class TestScriptFunctionHandler { - // Stats filled by the functions executed by test promises. - struct CallStats { - size_t num_calls = 0; - ScriptValue value; - }; - - // ScriptFunction run by test promises. Extracts the resolved value. - class TestScriptFunction : public ScriptFunction { - public: - static v8::Local<v8::Function> CreateFunction(ScriptState* script_state, - CallStats* stats) { - return (new TestScriptFunction(script_state, stats))->BindToV8Function(); - } - - ScriptValue Call(ScriptValue value) override { - stats_->value = value; - stats_->num_calls++; - return ScriptValue(); - } - - private: - TestScriptFunction(ScriptState* script_state, CallStats* stats) - : ScriptFunction(script_state), stats_(stats) {} - // Pointer to the private CallStats member variable in - // TestScriptFunctionHandler. Whenever the associated function is called, - // the CallStats variable is updated. Internal values can be accessed via - // the public getters. - CallStats* stats_; - }; - - public: - TestScriptFunctionHandler() = default; - - v8::Local<v8::Function> GetFunction(ScriptState* script_state) { - return TestScriptFunction::CreateFunction(script_state, &stats_); - } - - size_t NumCalls() const { return stats_.num_calls; } - ScriptValue Value() const { return stats_.value; } - - private: - CallStats stats_; -}; - -ScriptValue ResolvePromise(ScriptState* script_state, ScriptPromise& promise) { - TestScriptFunctionHandler resolved; - TestScriptFunctionHandler rejected; - - promise.Then(resolved.GetFunction(script_state), - rejected.GetFunction(script_state)); - - v8::MicrotasksScope::PerformCheckpoint(promise.GetIsolate()); - - EXPECT_EQ(1ul, resolved.NumCalls()); - EXPECT_EQ(0ul, rejected.NumCalls()); - - return resolved.Value(); -} - -} // namespace - -TEST(BackgroundFetchSettledFetchesTest, MatchNullValue) { - V8TestingScope scope; - RequestOrUSVString null_request; - - auto settled_fetches = CreateSettledFetches({"foo.com"}); - auto* bgf_settled_fetches = BackgroundFetchSettledFetches::Create( - scope.GetScriptState(), settled_fetches); - - ScriptPromise promise = - bgf_settled_fetches->match(scope.GetScriptState(), null_request); - - ScriptValue value = ResolvePromise(scope.GetScriptState(), promise); - EXPECT_TRUE(value.IsNull()); -} - -TEST(BackgroundFetchSettledFetchesTest, MatchUSVString) { - V8TestingScope scope; - auto matched_request = RequestOrUSVString::FromUSVString("http://foo.com/"); - auto unmatched_request = RequestOrUSVString::FromUSVString("http://bar.com/"); - - auto settled_fetches = CreateSettledFetches( - {"http://t1.net/", "http://foo.com/", "http://t3.net/"}); - auto* bgf_settled_fetches = BackgroundFetchSettledFetches::Create( - scope.GetScriptState(), settled_fetches); - - ScriptPromise matched_promise = - bgf_settled_fetches->match(scope.GetScriptState(), matched_request); - ScriptPromise unmatched_promise = - bgf_settled_fetches->match(scope.GetScriptState(), unmatched_request); - - ScriptValue matched_value = - ResolvePromise(scope.GetScriptState(), matched_promise); - EXPECT_TRUE(matched_value.IsObject()); - - ScriptValue unmatched_value = - ResolvePromise(scope.GetScriptState(), unmatched_promise); - EXPECT_TRUE(unmatched_value.IsNull()); -} - -TEST(BackgroundFetchSettledFetchesTest, MatchRequest) { - V8TestingScope scope; - - auto matched_request = RequestOrUSVString::FromRequest(Request::Create( - scope.GetScriptState(), "http://foo.com/", scope.GetExceptionState())); - auto unmatched_request = RequestOrUSVString::FromRequest(Request::Create( - scope.GetScriptState(), "http://bar.com/", scope.GetExceptionState())); - - auto settled_fetches = CreateSettledFetches( - {"http://t1.net/", "http://foo.com/", "http://t3.net/"}); - auto* bgf_settled_fetches = BackgroundFetchSettledFetches::Create( - scope.GetScriptState(), settled_fetches); - - ScriptPromise matched_promise = - bgf_settled_fetches->match(scope.GetScriptState(), matched_request); - ScriptPromise unmatched_promise = - bgf_settled_fetches->match(scope.GetScriptState(), unmatched_request); - - ScriptValue matched_value = - ResolvePromise(scope.GetScriptState(), matched_promise); - EXPECT_TRUE(matched_value.IsObject()); - - ScriptValue unmatched_value = - ResolvePromise(scope.GetScriptState(), unmatched_promise); - EXPECT_TRUE(unmatched_value.IsNull()); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc index 719b38baa80..92b011daf5e 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_type_converters.cc @@ -22,7 +22,8 @@ TypeConverter<blink::BackgroundFetchRegistration*, return new blink::BackgroundFetchRegistration( mojo_registration->developer_id, mojo_registration->unique_id, mojo_registration->upload_total, mojo_registration->uploaded, - mojo_registration->download_total, mojo_registration->downloaded); + mojo_registration->download_total, mojo_registration->downloaded, + mojo_registration->state, mojo_registration->failure_reason); } blink::mojom::blink::BackgroundFetchOptionsPtr TypeConverter< @@ -42,7 +43,7 @@ blink::mojom::blink::BackgroundFetchOptionsPtr TypeConverter< mojo_options->icons = std::move(mojo_icons); mojo_options->download_total = options.downloadTotal(); - mojo_options->title = options.title(); + mojo_options->title = options.hasTitle() ? options.title() : ""; return mojo_options; } diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_ui_options.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_ui_options.idl new file mode 100644 index 00000000000..26c20e8c316 --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_ui_options.idl @@ -0,0 +1,10 @@ +// Copyright 2018 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. + +// https://wicg.github.io/background-fetch/#dictdef-backgroundfetchuioptions + +dictionary BackgroundFetchUIOptions { + sequence<ImageResource> icons = []; + DOMString? title; +}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.cc deleted file mode 100644 index c1aeb79d544..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.cc +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.h" - -#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" -#include "third_party/blink/renderer/core/dom/dom_exception.h" -#include "third_party/blink/renderer/core/fetch/request.h" -#include "third_party/blink/renderer/core/fetch/response.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetched_event_init.h" -#include "third_party/blink/renderer/modules/event_modules_names.h" -#include "third_party/blink/renderer/platform/bindings/script_state.h" - -namespace blink { - -BackgroundFetchUpdateEvent::BackgroundFetchUpdateEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer) - : BackgroundFetchSettledEvent(type, initializer) {} - -BackgroundFetchUpdateEvent::BackgroundFetchUpdateEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer, - const String& unique_id, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration) - : BackgroundFetchSettledEvent(type, initializer, unique_id, observer), - registration_(registration) {} - -BackgroundFetchUpdateEvent::~BackgroundFetchUpdateEvent() = default; - -void BackgroundFetchUpdateEvent::Trace(blink::Visitor* visitor) { - visitor->Trace(registration_); - BackgroundFetchSettledEvent::Trace(visitor); -} - -ScriptPromise BackgroundFetchUpdateEvent::updateUI(ScriptState* script_state, - const String& title) { - if (!registration_) { - // Return a Promise that will never settle when a developer calls this - // method on a BackgroundFetchedEvent instance they created themselves. - return ScriptPromise(); - } - DCHECK(!unique_id_.IsEmpty()); - - ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); - ScriptPromise promise = resolver->Promise(); - - BackgroundFetchBridge::From(registration_) - ->UpdateUI(id(), unique_id_, title, - WTF::Bind(&BackgroundFetchUpdateEvent::DidUpdateUI, - WrapPersistent(this), WrapPersistent(resolver))); - - return promise; -} - -void BackgroundFetchUpdateEvent::DidUpdateUI( - ScriptPromiseResolver* resolver, - mojom::blink::BackgroundFetchError error) { - switch (error) { - case mojom::blink::BackgroundFetchError::NONE: - case mojom::blink::BackgroundFetchError::INVALID_ID: - resolver->Resolve(); - return; - case mojom::blink::BackgroundFetchError::STORAGE_ERROR: - resolver->Reject( - DOMException::Create(DOMExceptionCode::kAbortError, - "Failed to update UI due to I/O error.")); - return; - case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: - case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: - case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: - // Not applicable for this callback. - break; - } - - NOTREACHED(); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.h deleted file mode 100644 index 56832347ef2..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_EVENT_H_ - -#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_event.h" -#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h" - -namespace blink { - -// Event for interacting with fetch requests that have completed. -class MODULES_EXPORT BackgroundFetchUpdateEvent final - : public BackgroundFetchSettledEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchUpdateEvent* Create( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer) { - return new BackgroundFetchUpdateEvent(type, initializer); - } - - static BackgroundFetchUpdateEvent* Create( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer, - const String& unique_id, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration) { - return new BackgroundFetchUpdateEvent(type, initializer, unique_id, - script_state, observer, registration); - } - - ~BackgroundFetchUpdateEvent() override; - - // Web Exposed method defined in the IDL file. - ScriptPromise updateUI(ScriptState* script_state, const String& title); - - void Trace(blink::Visitor* visitor) override; - - private: - BackgroundFetchUpdateEvent( - const AtomicString& type, - const BackgroundFetchSettledEventInit& initializer); - - BackgroundFetchUpdateEvent(const AtomicString& type, - const BackgroundFetchSettledEventInit&, - const String& unique_id, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration); - - void DidUpdateUI(ScriptPromiseResolver* resolver, - mojom::blink::BackgroundFetchError error); - - Member<ServiceWorkerRegistration> registration_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.idl deleted file mode 100644 index c9c79482c09..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_event.idl +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2018 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. - -// https://wicg.github.io/background-fetch/#backgroundfetchupdateevent - -[ - Constructor(DOMString type, BackgroundFetchSettledEventInit init), - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] -interface BackgroundFetchUpdateEvent : BackgroundFetchSettledEvent { - [CallWith=ScriptState] Promise<void> updateUI(DOMString title); -};
\ No newline at end of file diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc new file mode 100644 index 00000000000..20080f5a5c6 --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.cc @@ -0,0 +1,124 @@ +// Copyright 2018 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 "third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h" + +#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/core/dom/dom_exception.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/fetch/request.h" +#include "third_party/blink/renderer/core/fetch/response.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event_init.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_registration.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_ui_options.h" +#include "third_party/blink/renderer/modules/event_modules_names.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" + +namespace blink { + +BackgroundFetchUpdateUIEvent::BackgroundFetchUpdateUIEvent( + const AtomicString& type, + const BackgroundFetchEventInit& initializer) + : BackgroundFetchEvent(type, initializer, nullptr /* observer */) {} + +BackgroundFetchUpdateUIEvent::BackgroundFetchUpdateUIEvent( + const AtomicString& type, + const BackgroundFetchEventInit& initializer, + WaitUntilObserver* observer, + ServiceWorkerRegistration* registration) + : BackgroundFetchEvent(type, initializer, observer), + service_worker_registration_(registration) {} + +BackgroundFetchUpdateUIEvent::~BackgroundFetchUpdateUIEvent() = default; + +void BackgroundFetchUpdateUIEvent::Trace(blink::Visitor* visitor) { + visitor->Trace(service_worker_registration_); + visitor->Trace(loader_); + BackgroundFetchEvent::Trace(visitor); +} + +ScriptPromise BackgroundFetchUpdateUIEvent::updateUI( + ScriptState* script_state, + const BackgroundFetchUIOptions& ui_options) { + if (update_ui_called_) { + // Return a rejected promise as this method should only be called once. + return ScriptPromise::Reject( + script_state, + V8ThrowException::CreateTypeError(script_state->GetIsolate(), + "updateUI may only be called once.")); + } + + update_ui_called_ = true; + + if (!service_worker_registration_) { + // Return a Promise that will never settle when a developer calls this + // method on a BackgroundFetchSuccessEvent instance they created themselves. + // TODO(crbug.com/872768): Figure out if this is the right thing to do + // vs reacting eagerly. + return ScriptPromise(); + } + DCHECK(!registration_->unique_id().IsEmpty()); + + if (!ui_options.hasTitle() && ui_options.icons().IsEmpty()) { + // Nothing to update, just return a resolved promise. + return ScriptPromise::CastUndefined(script_state); + } + + ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); + ScriptPromise promise = resolver->Promise(); + + if (ui_options.icons().IsEmpty()) { + DidGetIcon(resolver, ui_options.title(), SkBitmap()); + } else { + DCHECK(!loader_); + loader_ = new BackgroundFetchIconLoader(); + DCHECK(loader_); + loader_->Start(BackgroundFetchBridge::From(service_worker_registration_), + ExecutionContext::From(script_state), ui_options.icons(), + WTF::Bind(&BackgroundFetchUpdateUIEvent::DidGetIcon, + WrapPersistent(this), WrapPersistent(resolver), + ui_options.title())); + } + + return promise; +} + +void BackgroundFetchUpdateUIEvent::DidGetIcon(ScriptPromiseResolver* resolver, + const String& title, + const SkBitmap& icon) { + BackgroundFetchBridge::From(service_worker_registration_) + ->UpdateUI(registration_->id(), registration_->unique_id(), title, icon, + WTF::Bind(&BackgroundFetchUpdateUIEvent::DidUpdateUI, + WrapPersistent(this), WrapPersistent(resolver))); +} + +void BackgroundFetchUpdateUIEvent::DidUpdateUI( + ScriptPromiseResolver* resolver, + mojom::blink::BackgroundFetchError error) { + switch (error) { + case mojom::blink::BackgroundFetchError::NONE: + case mojom::blink::BackgroundFetchError::INVALID_ID: + resolver->Resolve(); + return; + case mojom::blink::BackgroundFetchError::STORAGE_ERROR: + resolver->Reject( + DOMException::Create(DOMExceptionCode::kAbortError, + "Failed to update UI due to I/O error.")); + return; + case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: + case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: + case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: + case mojom::blink::BackgroundFetchError::PERMISSION_DENIED: + case mojom::blink::BackgroundFetchError::QUOTA_EXCEEDED: + // Not applicable for this callback. + break; + } + + NOTREACHED(); +} + +} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h new file mode 100644 index 00000000000..81d9e85d77c --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.h @@ -0,0 +1,77 @@ +// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_UI_EVENT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_UI_EVENT_H_ + +#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" +#include "third_party/blink/renderer/modules/service_worker/service_worker_registration.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" +#include "third_party/skia/include/core/SkBitmap.h" + +namespace blink { + +class BackgroundFetchEvent; +class BackgroundFetchIconLoader; +class BackgroundFetchUIOptions; +class ScriptPromiseResolver; +class WaitUntilObserver; + +// Event for interacting with fetch requests that have completed. +class MODULES_EXPORT BackgroundFetchUpdateUIEvent final + : public BackgroundFetchEvent { + DEFINE_WRAPPERTYPEINFO(); + + public: + static BackgroundFetchUpdateUIEvent* Create( + const AtomicString& type, + const BackgroundFetchEventInit& initializer) { + return new BackgroundFetchUpdateUIEvent(type, initializer); + } + + static BackgroundFetchUpdateUIEvent* Create( + const AtomicString& type, + const BackgroundFetchEventInit& initializer, + WaitUntilObserver* observer, + ServiceWorkerRegistration* registration) { + return new BackgroundFetchUpdateUIEvent(type, initializer, observer, + registration); + } + + ~BackgroundFetchUpdateUIEvent() override; + + // Web Exposed method defined in the IDL file. + ScriptPromise updateUI(ScriptState* script_state, + const BackgroundFetchUIOptions& ui_options); + + void Trace(blink::Visitor* visitor) override; + + private: + BackgroundFetchUpdateUIEvent(const AtomicString& type, + const BackgroundFetchEventInit& initializer); + + BackgroundFetchUpdateUIEvent(const AtomicString& type, + const BackgroundFetchEventInit& init, + WaitUntilObserver* observer, + ServiceWorkerRegistration* registration); + + void DidGetIcon(ScriptPromiseResolver* resolver, + const String& title, + const SkBitmap& icon); + + void DidUpdateUI(ScriptPromiseResolver* resolver, + mojom::blink::BackgroundFetchError error); + + bool update_ui_called_ = false; + + Member<ServiceWorkerRegistration> service_worker_registration_; + Member<BackgroundFetchIconLoader> loader_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCH_UPDATE_UI_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.idl new file mode 100644 index 00000000000..b494c006376 --- /dev/null +++ b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetch_update_ui_event.idl @@ -0,0 +1,13 @@ +// Copyright 2018 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. + +// https://wicg.github.io/background-fetch/#background-fetch-update-ui-event + +[ + Constructor(DOMString type, BackgroundFetchEventInit init), + Exposed=ServiceWorker, + RuntimeEnabled=BackgroundFetch +] interface BackgroundFetchUpdateUIEvent : BackgroundFetchEvent { + [CallWith=ScriptState] Promise<void> updateUI(BackgroundFetchUIOptions options); +};
\ No newline at end of file diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.cc b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.cc deleted file mode 100644 index 5416bd27470..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.cc +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2017 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 "third_party/blink/renderer/modules/background_fetch/background_fetched_event.h" - -#include "third_party/blink/public/platform/modules/background_fetch/web_background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" -#include "third_party/blink/renderer/core/dom/dom_exception.h" -#include "third_party/blink/renderer/core/fetch/request.h" -#include "third_party/blink/renderer/core/fetch/response.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_bridge.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_settled_fetch.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetched_event_init.h" -#include "third_party/blink/renderer/modules/event_modules_names.h" -#include "third_party/blink/renderer/platform/bindings/script_state.h" - -namespace blink { - -BackgroundFetchedEvent::BackgroundFetchedEvent( - const AtomicString& type, - const BackgroundFetchedEventInit& initializer) - : BackgroundFetchEvent(type, initializer, nullptr /* observer */), - fetches_(initializer.fetches()) {} - -BackgroundFetchedEvent::BackgroundFetchedEvent( - const AtomicString& type, - const BackgroundFetchedEventInit& initializer, - const String& unique_id, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration) - : BackgroundFetchEvent(type, initializer, observer), - unique_id_(unique_id), - registration_(registration) { - fetches_.ReserveInitialCapacity(fetches.size()); - for (const WebBackgroundFetchSettledFetch& fetch : fetches) { - auto* settled_fetch = BackgroundFetchSettledFetch::Create( - Request::Create(script_state, fetch.request), - Response::Create(script_state, fetch.response)); - - fetches_.push_back(settled_fetch); - } -} - -BackgroundFetchedEvent::~BackgroundFetchedEvent() = default; - -HeapVector<Member<BackgroundFetchSettledFetch>> -BackgroundFetchedEvent::fetches() const { - return fetches_; -} - -ScriptPromise BackgroundFetchedEvent::updateUI(ScriptState* script_state, - const String& title) { - if (!registration_) { - // Return a Promise that will never settle when a developer calls this - // method on a BackgroundFetchedEvent instance they created themselves. - return ScriptPromise(); - } - DCHECK(!unique_id_.IsEmpty()); - - ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); - ScriptPromise promise = resolver->Promise(); - - BackgroundFetchBridge::From(registration_) - ->UpdateUI(id(), unique_id_, title, - WTF::Bind(&BackgroundFetchedEvent::DidUpdateUI, - WrapPersistent(this), WrapPersistent(resolver))); - - return promise; -} - -void BackgroundFetchedEvent::DidUpdateUI( - ScriptPromiseResolver* resolver, - mojom::blink::BackgroundFetchError error) { - switch (error) { - case mojom::blink::BackgroundFetchError::NONE: - case mojom::blink::BackgroundFetchError::INVALID_ID: - resolver->Resolve(); - return; - case mojom::blink::BackgroundFetchError::STORAGE_ERROR: - resolver->Reject( - DOMException::Create(DOMExceptionCode::kAbortError, - "Failed to update UI due to I/O error.")); - return; - case mojom::blink::BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE: - case mojom::blink::BackgroundFetchError::DUPLICATED_DEVELOPER_ID: - case mojom::blink::BackgroundFetchError::INVALID_ARGUMENT: - // Not applicable for this callback. - break; - } - - NOTREACHED(); -} - -const AtomicString& BackgroundFetchedEvent::InterfaceName() const { - return EventNames::BackgroundFetchedEvent; -} - -void BackgroundFetchedEvent::Trace(blink::Visitor* visitor) { - visitor->Trace(fetches_); - visitor->Trace(registration_); - BackgroundFetchEvent::Trace(visitor); -} - -} // namespace blink diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.h b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.h deleted file mode 100644 index d86e7392196..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCHED_EVENT_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCHED_EVENT_H_ - -#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom-blink.h" -#include "third_party/blink/public/platform/web_vector.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" -#include "third_party/blink/renderer/modules/background_fetch/background_fetch_event.h" -#include "third_party/blink/renderer/modules/modules_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" - -namespace blink { - -class BackgroundFetchSettledFetch; -class BackgroundFetchedEventInit; -class ScriptPromiseResolver; -class ScriptState; -class ServiceWorkerRegistration; -struct WebBackgroundFetchSettledFetch; - -class MODULES_EXPORT BackgroundFetchedEvent final - : public BackgroundFetchEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static BackgroundFetchedEvent* Create( - const AtomicString& type, - const BackgroundFetchedEventInit& initializer) { - return new BackgroundFetchedEvent(type, initializer); - } - - static BackgroundFetchedEvent* Create( - const AtomicString& type, - const BackgroundFetchedEventInit& initializer, - const String& unique_id, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration) { - return new BackgroundFetchedEvent(type, initializer, unique_id, fetches, - script_state, observer, registration); - } - - ~BackgroundFetchedEvent() override; - - // Web Exposed attribute defined in the IDL file. - HeapVector<Member<BackgroundFetchSettledFetch>> fetches() const; - - // Web Exposed method defined in the IDL file. - ScriptPromise updateUI(ScriptState* script_state, const String& title); - - // ExtendableEvent interface. - const AtomicString& InterfaceName() const override; - - void Trace(blink::Visitor* visitor) override; - - private: - BackgroundFetchedEvent(const AtomicString& type, - const BackgroundFetchedEventInit& initializer); - BackgroundFetchedEvent( - const AtomicString& type, - const BackgroundFetchedEventInit& initializer, - const String& unique_id, - const WebVector<WebBackgroundFetchSettledFetch>& fetches, - ScriptState* script_state, - WaitUntilObserver* observer, - ServiceWorkerRegistration* registration); - - void DidUpdateUI(ScriptPromiseResolver* resolver, - mojom::blink::BackgroundFetchError error); - - // Globally unique ID for the registration, generated in content/. Used to - // distinguish registrations in case a developer re-uses |developer_id_|s. Not - // exposed to JavaScript. - String unique_id_; - - HeapVector<Member<BackgroundFetchSettledFetch>> fetches_; - Member<ServiceWorkerRegistration> registration_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BACKGROUND_FETCH_BACKGROUND_FETCHED_EVENT_H_ diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.idl deleted file mode 100644 index 22268218e32..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event.idl +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017 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. - -// https://wicg.github.io/background-fetch/#background-fetch-end-event - -[ - Constructor(DOMString type, BackgroundFetchedEventInit init), - Exposed=ServiceWorker, - RuntimeEnabled=BackgroundFetch -] interface BackgroundFetchedEvent : BackgroundFetchEvent { - readonly attribute FrozenArray<BackgroundFetchSettledFetch> fetches; - - [CallWith=ScriptState] Promise<void> updateUI(DOMString title); -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event_init.idl b/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event_init.idl deleted file mode 100644 index 68d6f6841cb..00000000000 --- a/chromium/third_party/blink/renderer/modules/background_fetch/background_fetched_event_init.idl +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2017 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. - -// https://wicg.github.io/background-fetch/#background-fetch-end-event - -dictionary BackgroundFetchedEventInit : BackgroundFetchEventInit { - required sequence<BackgroundFetchSettledFetch> fetches; -}; diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h index 1b4588709ed..eca44d20b60 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h +++ b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.h @@ -14,7 +14,7 @@ class ServiceWorkerGlobalScopeBackgroundFetch { STATIC_ONLY(ServiceWorkerGlobalScopeBackgroundFetch); public: - DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetched); + DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchsuccess); DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchfail); DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchabort); DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(backgroundfetchclick); diff --git a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.idl b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.idl index 19322597b39..2f9f6c023e5 100644 --- a/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.idl +++ b/chromium/third_party/blink/renderer/modules/background_fetch/service_worker_global_scope_background_fetch.idl @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://wicg.github.io/background-fetch/#events +// https://wicg.github.io/background-fetch/#extensions-to-service-worker-global [ ImplementedAs=ServiceWorkerGlobalScopeBackgroundFetch, RuntimeEnabled=BackgroundFetch ] partial interface ServiceWorkerGlobalScope { - attribute EventHandler onbackgroundfetched; + attribute EventHandler onbackgroundfetchsuccess; attribute EventHandler onbackgroundfetchfail; attribute EventHandler onbackgroundfetchabort; attribute EventHandler onbackgroundfetchclick; |