diff --git a/DEPS b/DEPS index ae389195..abaaf49 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '46983b7dd88603bb2a9a3c3e1ce3e147f5615f2f', + 'skia_revision': 'd1aeddeb8aa2d678a24511542935f1f33c2eebcd', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'd045bfc5ca3841992519cc709ac6e887758db631', + 'v8_revision': '0eb9c7ca20668a1c494cd52e40f27df2b6f76eee', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -64,7 +64,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'eda6525eaef97a354e52dbe2e7f454129325d36b', + 'pdfium_revision': 'a0b322b58954ccf4d834887967946b17adf0064d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -205,7 +205,7 @@ Var('chromium_git') + '/external/selenium/py.git' + '@' + '5fd78261a75fe08d27ca4835fb6c5ce4b42275bd', 'src/third_party/libvpx/source/libvpx': - Var('chromium_git') + '/webm/libvpx.git' + '@' + 'b9649d240768cdcfc233960056aafb9ed1a3db14', + Var('chromium_git') + '/webm/libvpx.git' + '@' + 'ff42e04f9cb60e63ca3fe12ac497f27c68555e1f', 'src/third_party/ffmpeg': Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '06ac9ea361fa8d48916b83783bb7f36872388cc2',
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 79b3f70a..c0324ab8 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -189,6 +189,17 @@ ), ), ( + r'XInternAtom|xcb_intern_atom', + ( + 'Use ui::GetAtom() or ui::X11AtomCache::GetAtom() instead of', + 'interning atoms directly.', + ), + True, + ( + r"^ui[\\\/]gfx[\\\/]x[\\\/]x11_atom_cache\.cc$", + ), + ), + ( 'ScopedAllowIO', ( 'New production code should not use ScopedAllowIO (using it in',
diff --git a/WATCHLISTS b/WATCHLISTS index 1482ae8..73ee4f41 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -657,7 +657,8 @@ }, 'md_settings': { 'filepath': 'chrome/browser/resources/settings/'\ - '|chrome/browser/ui/webui/settings/', + '|chrome/browser/ui/webui/settings/'\ + '|chrome/test/data/webui/settings/', }, 'media': { 'filepath': 'media/|third_party/(ffmpeg|openmax)/|webmediaplayer|'\
diff --git a/android_webview/browser/icon_helper.cc b/android_webview/browser/icon_helper.cc index c2b3162c..e258f36 100644 --- a/android_webview/browser/icon_helper.cc +++ b/android_webview/browser/icon_helper.cc
@@ -66,7 +66,7 @@ continue; switch(i->icon_type) { - case content::FaviconURL::FAVICON: + case content::FaviconURL::IconType::kFavicon: if ((listener_ && !listener_->ShouldDownloadFavicon(i->icon_url)) || WasUnableToDownloadFavicon(i->icon_url)) { break; @@ -78,15 +78,15 @@ base::Bind( &IconHelper::DownloadFaviconCallback, base::Unretained(this))); break; - case content::FaviconURL::TOUCH_ICON: + case content::FaviconURL::IconType::kTouchIcon: if (listener_) listener_->OnReceivedTouchIconUrl(i->icon_url.spec(), false); break; - case content::FaviconURL::TOUCH_PRECOMPOSED_ICON: + case content::FaviconURL::IconType::kTouchPrecomposedIcon: if (listener_) listener_->OnReceivedTouchIconUrl(i->icon_url.spec(), true); break; - case content::FaviconURL::INVALID_ICON: + case content::FaviconURL::IconType::kInvalid: // Silently ignore it. Only trigger a callback on valid icons. break; default:
diff --git a/ash/host/ash_window_tree_host_x11.cc b/ash/host/ash_window_tree_host_x11.cc index 73efb44..68d864a4 100644 --- a/ash/host/ash_window_tree_host_x11.cc +++ b/ash/host/ash_window_tree_host_x11.cc
@@ -30,6 +30,7 @@ #include "ui/events/null_event_targeter.h" #include "ui/events/platform/platform_event_source.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/x/x11_atom_cache.h" namespace ash { @@ -216,7 +217,7 @@ if (!ui::IsXInput2Available()) return; // Temporarily pause tap-to-click when the cursor is hidden. - Atom prop = atom_cache()->GetAtom("Tap Paused"); + Atom prop = ui::X11AtomCache::GetInstance()->GetAtom("Tap Paused"); unsigned char value = state; const XIDeviceList& dev_list = ui::DeviceListCacheX11::GetInstance()->GetXI2DeviceList(xdisplay());
diff --git a/base/BUILD.gn b/base/BUILD.gn index 0292e54..7735309 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -410,7 +410,6 @@ "mac/call_with_eh_frame.h", "mac/call_with_eh_frame_asm.S", "mac/close_nocancel.cc", - "mac/cocoa_protocols.h", "mac/dispatch_source_mach.cc", "mac/dispatch_source_mach.h", "mac/foundation_util.h",
diff --git a/base/mac/cocoa_protocols.h b/base/mac/cocoa_protocols.h deleted file mode 100644 index a28795c3..0000000 --- a/base/mac/cocoa_protocols.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_MAC_COCOA_PROTOCOLS_H_ -#define BASE_MAC_COCOA_PROTOCOLS_H_ - -#import <Cocoa/Cocoa.h> - -// New Mac OS X SDKs introduce new protocols used for delegates. These -// protocol defintions aren't not present in earlier releases of the Mac OS X -// SDK. In order to support building against the new SDK, which requires -// delegates to conform to these protocols, and earlier SDKs, which do not -// define these protocols at all, this file will provide empty protocol -// definitions when used with earlier SDK versions. - -#define DEFINE_EMPTY_PROTOCOL(p) \ -@protocol p \ -@end - -#if !defined(MAC_OS_X_VERSION_10_7) || \ - MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7 - -DEFINE_EMPTY_PROTOCOL(NSDraggingDestination) -DEFINE_EMPTY_PROTOCOL(ICCameraDeviceDownloadDelegate) - -#endif // MAC_OS_X_VERSION_10_7 - -#undef DEFINE_EMPTY_PROTOCOL - -#endif // BASE_MAC_COCOA_PROTOCOLS_H_
diff --git a/base/task_scheduler/task_tracker.cc b/base/task_scheduler/task_tracker.cc index 59bbe23..bd775e5 100644 --- a/base/task_scheduler/task_tracker.cc +++ b/base/task_scheduler/task_tracker.cc
@@ -254,6 +254,8 @@ if (!is_delayed) DecrementNumPendingUndelayedTasks(); + OnRunNextTaskCompleted(); + return sequence->Pop(); }
diff --git a/base/task_scheduler/task_tracker.h b/base/task_scheduler/task_tracker.h index 87fc281b..36ce7a3 100644 --- a/base/task_scheduler/task_tracker.h +++ b/base/task_scheduler/task_tracker.h
@@ -88,6 +88,10 @@ virtual bool IsPostingBlockShutdownTaskAfterShutdownAllowed(); #endif + // Called at the very end of RunNextTask() after the completion of all task + // metrics accounting. + virtual void OnRunNextTaskCompleted() {} + // Returns the number of undelayed tasks that haven't completed their // execution. int GetNumPendingUndelayedTasksForTesting() const;
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc index 4bb932e..6729460 100644 --- a/base/test/scoped_task_environment.cc +++ b/base/test/scoped_task_environment.cc
@@ -60,6 +60,7 @@ // internal::TaskSchedulerImpl::TaskTrackerImpl: void PerformRunTask(std::unique_ptr<internal::Task> task, internal::Sequence* sequence) override; + void OnRunNextTaskCompleted() override; // Synchronizes accesses to members below. Lock lock_; @@ -224,16 +225,18 @@ CHECK_GT(num_tasks_running_, 0); CHECK(can_run_tasks_); - // Notify the main thread when no task other than the current one is running - // or queued. - if (num_tasks_running_ == 1 && - GetNumPendingUndelayedTasksForTesting() == 1 && queue_empty_closure_) { - std::move(queue_empty_closure_).Run(); - } - --num_tasks_running_; } } +void ScopedTaskEnvironment::TestTaskTracker::OnRunNextTaskCompleted() { + // Notify the main thread when no tasks are running or queued. + AutoLock auto_lock(lock_); + if (num_tasks_running_ == 0 && GetNumPendingUndelayedTasksForTesting() == 0 && + queue_empty_closure_) { + std::move(queue_empty_closure_).Run(); + } +} + } // namespace test } // namespace base
diff --git a/base/timer/timer.cc b/base/timer/timer.cc index abcd70a..1f6efcc 100644 --- a/base/timer/timer.cc +++ b/base/timer/timer.cc
@@ -99,8 +99,7 @@ } Timer::~Timer() { - // TODO(gab): Enable this once Stop() properly detaches from sequence. - // DCHECK(origin_sequence_checker_.CalledOnValidSequence()); + DCHECK(origin_sequence_checker_.CalledOnValidSequence()); AbandonAndStop(); } @@ -144,6 +143,10 @@ // DCHECK(origin_sequence_checker_.CalledOnValidSequence()); is_running_ = false; + + // It's safe to destroy or restart Timer on another sequence after Stop(). + origin_sequence_checker_.DetachFromSequence(); + if (!retain_user_task_) user_task_.Reset(); // No more member accesses here: |this| could be deleted after freeing
diff --git a/base/timer/timer.h b/base/timer/timer.h index 88958d4..651ba39d 100644 --- a/base/timer/timer.h +++ b/base/timer/timer.h
@@ -203,7 +203,8 @@ TimeTicks desired_run_time_; // Timer isn't thread-safe and must only be used on its origin sequence - // (sequence on which it was started). + // (sequence on which it was started). Once fully Stop()'ed it may be + // destroyed or restarted on another sequence. SequenceChecker origin_sequence_checker_; // Repeating timers automatically post the task again before calling the task
diff --git a/cc/layers/layer.cc b/cc/layers/layer.cc index 76d0bd29..5cb9e90 100644 --- a/cc/layers/layer.cc +++ b/cc/layers/layer.cc
@@ -54,6 +54,7 @@ use_parent_backface_visibility(false), background_color(0), scroll_clip_layer_id(INVALID_ID), + scrollable(false), user_scrollable_horizontal(true), user_scrollable_vertical(true), main_thread_scrolling_reasons( @@ -818,7 +819,12 @@ if (inputs_.scroll_clip_layer_id == clip_layer_id) return; inputs_.scroll_clip_layer_id = clip_layer_id; + SetPropertyTreesNeedRebuild(); + + bool scrollable = clip_layer_id != Layer::INVALID_ID; + SetScrollable(scrollable); + SetNeedsCommit(); } @@ -827,6 +833,14 @@ return layer_tree_host_->LayerById(inputs_.scroll_clip_layer_id); } +void Layer::SetScrollable(bool scrollable) { + DCHECK(IsPropertyChangeAllowed()); + if (inputs_.scrollable == scrollable) + return; + inputs_.scrollable = scrollable; + SetNeedsCommit(); +} + void Layer::SetUserScrollable(bool horizontal, bool vertical) { DCHECK(IsPropertyChangeAllowed()); if (inputs_.user_scrollable_horizontal == horizontal && @@ -1171,6 +1185,7 @@ layer->SetShouldCheckBackfaceVisibility(should_check_backface_visibility_); layer->SetScrollClipLayer(inputs_.scroll_clip_layer_id); + layer->SetScrollable(inputs_.scrollable); layer->SetMutableProperties(inputs_.mutable_properties); // The property trees must be safe to access because they will be used below
diff --git a/cc/layers/layer.h b/cc/layers/layer.h index c88721b..a92218da 100644 --- a/cc/layers/layer.h +++ b/cc/layers/layer.h
@@ -212,10 +212,16 @@ gfx::ScrollOffset scroll_offset() const { return inputs_.scroll_offset; } void SetScrollOffsetFromImplSide(const gfx::ScrollOffset& scroll_offset); + // TODO(pdr): Remove scroll_clip_layer_id and store the scroll clip bounds + // directly instead of using scroll_clip_layer's bounds. void SetScrollClipLayerId(int clip_layer_id); - bool scrollable() const { return inputs_.scroll_clip_layer_id != INVALID_ID; } Layer* scroll_clip_layer() const; + // Marks this layer as being scrollable and needing an associated scroll node + // with bounds synced to this layer's bounds. + void SetScrollable(bool scrollable = true); + bool scrollable() const { return inputs_.scrollable; } + void SetUserScrollable(bool horizontal, bool vertical); bool user_scrollable_horizontal() const { return inputs_.user_scrollable_horizontal; @@ -565,6 +571,10 @@ // transformed relative to this layer, defines the maximum scroll offset // for this layer. int scroll_clip_layer_id; + + // Indicates that this layer will need a scroll property node and that this + // layer's bounds correspond to the scroll node's bounds. + bool scrollable : 1; bool user_scrollable_horizontal : 1; bool user_scrollable_vertical : 1;
diff --git a/cc/layers/layer_impl.cc b/cc/layers/layer_impl.cc index 57403a441..23d5abe 100644 --- a/cc/layers/layer_impl.cc +++ b/cc/layers/layer_impl.cc
@@ -55,6 +55,7 @@ scroll_clip_layer_id_(Layer::INVALID_ID), main_thread_scrolling_reasons_( MainThreadScrollingReason::kNotScrollingOnMain), + scrollable_(false), should_flatten_transform_from_property_tree_(false), layer_property_changed_(false), may_contain_video_(false), @@ -274,18 +275,23 @@ return; scroll_clip_layer_id_ = scroll_clip_layer_id; - layer_tree_impl()->RegisterScrollLayer(this); - // The scrolling bounds are determined from the scroll clip layer's bounds. layer_tree_impl()->SetScrollbarGeometriesNeedUpdate(); + + bool scrollable = scroll_clip_layer_id_ != Layer::INVALID_ID; + SetScrollable(scrollable); } LayerImpl* LayerImpl::scroll_clip_layer() const { return layer_tree_impl()->LayerById(scroll_clip_layer_id_); } -bool LayerImpl::scrollable() const { - return scroll_clip_layer_id_ != Layer::INVALID_ID; +void LayerImpl::SetScrollable(bool scrollable) { + if (scrollable_ == scrollable) + return; + scrollable_ = scrollable; + if (scrollable) + layer_tree_impl()->RegisterScrollLayer(this); } std::unique_ptr<LayerImpl> LayerImpl::CreateLayerImpl( @@ -336,6 +342,7 @@ layer->SetBounds(bounds_); layer->SetScrollClipLayer(scroll_clip_layer_id_); + layer->SetScrollable(scrollable_); layer->SetMutableProperties(mutable_properties_); // If the main thread commits multiple times before the impl thread actually
diff --git a/cc/layers/layer_impl.h b/cc/layers/layer_impl.h index 5fa037d0..3e17d84 100644 --- a/cc/layers/layer_impl.h +++ b/cc/layers/layer_impl.h
@@ -302,10 +302,15 @@ // initial scroll gfx::Vector2dF ScrollBy(const gfx::Vector2dF& scroll); + // TODO(pdr): Remove scroll_clip_layer_id and use the scroll node's scroll + // clip bounds instead of the scroll_clip_layer bounds. void SetScrollClipLayer(int scroll_clip_layer_id); - int scroll_clip_layer_id() const { return scroll_clip_layer_id_; } LayerImpl* scroll_clip_layer() const; - bool scrollable() const; + + // Marks this layer as being scrollable and having an associated scroll node + // with bounds synced to this layer's bounds. + void SetScrollable(bool scrollable = true); + bool scrollable() const { return scrollable_; } void set_main_thread_scrolling_reasons( uint32_t main_thread_scrolling_reasons) { @@ -484,6 +489,10 @@ gfx::Vector2dF offset_to_transform_parent_; uint32_t main_thread_scrolling_reasons_; + // Indicates that this layer is scrollable and has an associated scroll node + // with bounds synced to this layer's bounds. + bool scrollable_ : 1; + bool should_flatten_transform_from_property_tree_ : 1; // Tracks if drawing-related properties have changed since last redraw.
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc index 652d84e..e55c86f4 100644 --- a/cc/layers/layer_unittest.cc +++ b/cc/layers/layer_unittest.cc
@@ -912,7 +912,7 @@ EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetContentsOpaque(true)); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetPosition(gfx::PointF(4.f, 9.f))); // We can use any layer pointer here since we aren't syncing for real. - EXPECT_SET_NEEDS_COMMIT(1, + EXPECT_SET_NEEDS_COMMIT(2, test_layer->SetScrollClipLayerId(test_layer->id())); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetUserScrollable(true, false)); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetScrollOffset(
diff --git a/cc/layers/scrollbar_layer_unittest.cc b/cc/layers/scrollbar_layer_unittest.cc index f8047f6..fcd74017 100644 --- a/cc/layers/scrollbar_layer_unittest.cc +++ b/cc/layers/scrollbar_layer_unittest.cc
@@ -839,6 +839,7 @@ impl.host_impl()->active_tree()->UpdateScrollbarGeometries(); scroll_layer->SetScrollClipLayer(clip_layer->id()); + scroll_layer->SetScrollable(); DCHECK(impl.host_impl()->active_tree()->ScrollbarGeometriesNeedUpdate()); impl.host_impl()->active_tree()->UpdateScrollbarGeometries();
diff --git a/cc/tiles/checker_image_tracker.cc b/cc/tiles/checker_image_tracker.cc index 022269d..2f04b9f 100644 --- a/cc/tiles/checker_image_tracker.cc +++ b/cc/tiles/checker_image_tracker.cc
@@ -88,16 +88,19 @@ // re-decode and checker images that were pending invalidation. for (auto image_id : images_pending_invalidation_) { auto it = image_async_decode_state_.find(image_id); - DCHECK(it != image_async_decode_state_.end()); - DCHECK_EQ(it->second, DecodePolicy::SYNC_DECODED_ONCE); - + DCHECK_EQ(it->second, DecodePolicy::SYNC); it->second = DecodePolicy::ASYNC; } } images_pending_invalidation_.clear(); } +void CheckerImageTracker::DisallowCheckeringForImage(const PaintImage& image) { + image_async_decode_state_.insert( + std::make_pair(image.stable_id(), DecodePolicy::SYNC)); +} + void CheckerImageTracker::DidFinishImageDecode( PaintImage::Id image_id, ImageController::ImageDecodeRequestId request_id, @@ -119,7 +122,7 @@ return; } - it->second = DecodePolicy::SYNC_DECODED_ONCE; + it->second = DecodePolicy::SYNC; images_pending_invalidation_.insert(image_id); ScheduleNextImageDecode(); client_->NeedsInvalidationForCheckerImagedTiles(); @@ -150,9 +153,8 @@ return true; } - auto insert_result = - image_async_decode_state_.insert(std::pair<PaintImage::Id, DecodePolicy>( - image_id, DecodePolicy::SYNC_PERMANENT)); + auto insert_result = image_async_decode_state_.insert( + std::pair<PaintImage::Id, DecodePolicy>(image_id, DecodePolicy::SYNC)); auto it = insert_result.first; if (insert_result.second) { bool can_checker_image = @@ -163,7 +165,7 @@ it->second = (size >= kMinImageSizeToCheckerBytes && size <= image_controller_->image_cache_max_limit_bytes()) ? DecodePolicy::ASYNC - : DecodePolicy::SYNC_PERMANENT; + : DecodePolicy::SYNC; } }
diff --git a/cc/tiles/checker_image_tracker.h b/cc/tiles/checker_image_tracker.h index 9f64d8d..205e493 100644 --- a/cc/tiles/checker_image_tracker.h +++ b/cc/tiles/checker_image_tracker.h
@@ -58,6 +58,14 @@ // in re-checkering any images already decoded by the tracker. void ClearTracker(bool can_clear_decode_policy_tracking); + // Informs the tracker to not checker the given image. This can be used to opt + // out of the checkering behavior for certain images, such as ones that were + // decoded using the img.decode api. + // Note that if the image is already being checkered, then it will continue to + // do so. This call is meant to be issued prior to the image appearing during + // raster. + void DisallowCheckeringForImage(const PaintImage& image); + private: enum class DecodePolicy { // The image can be decoded asynchronously from raster. When set, the image @@ -65,10 +73,9 @@ // image until it has been decoded using the decode service. ASYNC, // The image has been decoded asynchronously once and should now be - // synchronously rasterized with the content. - SYNC_DECODED_ONCE, - // The image has been permanently vetoed from being decoded async. - SYNC_PERMANENT, + // synchronously rasterized with the content or the image has been + // permanently vetoed from being decoded async. + SYNC }; // Wrapper to unlock an image decode requested from the ImageController on @@ -123,6 +130,8 @@ image_id_to_decode_; base::WeakPtrFactory<CheckerImageTracker> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(CheckerImageTracker); }; } // namespace cc
diff --git a/cc/tiles/checker_image_tracker_unittest.cc b/cc/tiles/checker_image_tracker_unittest.cc index 38de60d..7a08e9cf 100644 --- a/cc/tiles/checker_image_tracker_unittest.cc +++ b/cc/tiles/checker_image_tracker_unittest.cc
@@ -416,5 +416,26 @@ completed_paint_image, WhichTree::PENDING_TREE)); } +TEST_F(CheckerImageTrackerTest, DontCheckerDisallowedImages) { + SetUpTracker(true); + + PaintImage image = CreateImage(ImageType::CHECKERABLE); + EXPECT_TRUE(checker_image_tracker_->ShouldCheckerImage( + image, WhichTree::PENDING_TREE)); + checker_image_tracker_->DisallowCheckeringForImage(image); + // Since the tracker already saw the image, even disallowing it would still + // ensure that we checker it until it's completed. + EXPECT_TRUE(checker_image_tracker_->ShouldCheckerImage( + image, WhichTree::PENDING_TREE)); + + // Reset the tracker. + checker_image_tracker_->ClearTracker(true); + // If we haven't seen the image and disallow it first, then it's not + // checkerable anymore. + checker_image_tracker_->DisallowCheckeringForImage(image); + EXPECT_FALSE(checker_image_tracker_->ShouldCheckerImage( + image, WhichTree::PENDING_TREE)); +} + } // namespace } // namespace cc
diff --git a/cc/tiles/tile_manager.h b/cc/tiles/tile_manager.h index 9b503e6a..86c66c4 100644 --- a/cc/tiles/tile_manager.h +++ b/cc/tiles/tile_manager.h
@@ -243,6 +243,10 @@ return num_of_tiles_with_checker_images_; } + CheckerImageTracker& checker_image_tracker() { + return checker_image_tracker_; + } + protected: friend class Tile; // Must be called by tile during destruction.
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 150bbcc..b29d67a0 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -2387,6 +2387,7 @@ decoded_image_tracker_.QueueImageDecode( image, base::Bind(&LayerTreeHostImpl::ImageDecodeFinished, base::Unretained(this), embedder_callback)); + tile_manager_.checker_image_tracker().DisallowCheckeringForImage(image); } void LayerTreeHostImpl::ImageDecodeFinished(
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index 14af3be..4b824ee 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -7794,19 +7794,40 @@ protected: void BeginTest() override { PostSetNeedsCommitToMainThread(); } + void InitializeSettings(LayerTreeSettings* settings) override { + settings->enable_checker_imaging = true; + } + void WillBeginMainFrame() override { if (!first_) return; first_ = false; - PaintImage image(PaintImage::GetNextId(), - CreateDiscardableImage(gfx::Size(10, 10))); + image_ = PaintImage(PaintImage::GetNextId(), + CreateDiscardableImage(gfx::Size(400, 400))); auto callback = base::Bind(&LayerTreeHostTestQueueImageDecode::ImageDecodeFinished, base::Unretained(this)); // Schedule the decode twice for the same image. - layer_tree_host()->QueueImageDecode(image, callback); - layer_tree_host()->QueueImageDecode(image, callback); + layer_tree_host()->QueueImageDecode(image_, callback); + layer_tree_host()->QueueImageDecode(image_, callback); + } + + void ReadyToCommitOnThread(LayerTreeHostImpl* impl) override { + if (one_commit_done_) + return; + EXPECT_TRUE( + impl->tile_manager()->checker_image_tracker().ShouldCheckerImage( + image_, WhichTree::PENDING_TREE)); + // Reset the tracker as if it has never seen this image. + impl->tile_manager()->checker_image_tracker().ClearTracker(true); + } + + void CommitCompleteOnThread(LayerTreeHostImpl* impl) override { + one_commit_done_ = true; + EXPECT_FALSE( + impl->tile_manager()->checker_image_tracker().ShouldCheckerImage( + image_, WhichTree::PENDING_TREE)); } void ImageDecodeFinished(bool decode_succeeded) { @@ -7821,7 +7842,9 @@ private: bool first_ = true; + bool one_commit_done_ = false; int finished_decode_count_ = 0; + PaintImage image_; }; SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestQueueImageDecode);
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 7ff75e3..94023cd 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -1739,10 +1739,10 @@ return scrollbars; } +// TODO(pdr): This function no longer registers the scroll layer. Remove this by +// inlining it into the only callsite. void LayerTreeImpl::RegisterScrollLayer(LayerImpl* layer) { - if (layer->scroll_clip_layer_id() == Layer::INVALID_ID) - return; - + DCHECK(layer->scrollable()); if (settings().scrollbar_animator == LayerTreeSettings::AURA_OVERLAY) layer->set_needs_show_scrollbars(true); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java index 64e4e274..285b4e70 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorView.java
@@ -10,14 +10,11 @@ import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; -import android.os.Build; -import android.view.Display; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; -import android.view.WindowManager; import android.widget.FrameLayout; import org.chromium.base.TraceEvent; @@ -66,9 +63,6 @@ private final LayoutRenderHost mRenderHost; private int mPreviousWindowTop = -1; - // A conservative estimate of when a frame is guaranteed to be presented after being submitted. - private long mFramePresentationDelay; - // Resource Management private ResourceManager mResourceManager; @@ -201,18 +195,6 @@ setVisibility(View.VISIBLE); - mFramePresentationDelay = 0; - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - Display display = - ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay(); - long presentationDeadline = display.getPresentationDeadlineNanos() - / NANOSECONDS_PER_MILLISECOND; - long vsyncPeriod = mWindowAndroid.getVsyncPeriodInMillis(); - mFramePresentationDelay = Math.min(3 * vsyncPeriod, - ((presentationDeadline + vsyncPeriod - 1) / vsyncPeriod) * vsyncPeriod); - } - // Grab the Resource Manager mResourceManager = nativeGetResourceManager(mNativeCompositorView); @@ -324,16 +306,6 @@ @CalledByNative private void didSwapFrame(int pendingFrameCount) { - // Clear the color used to cover the uninitialized surface. - if (getBackground() != null) { - postDelayed(new Runnable() { - @Override - public void run() { - setBackgroundResource(0); - } - }, mFramePresentationDelay); - } - mRenderHost.didSwapFrame(pendingFrameCount); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java index 8b77ff0fe..3c6e912 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java
@@ -578,14 +578,17 @@ public void didSwapFrame(int pendingFrameCount) { TraceEvent.instant("didSwapFrame"); - // Wait until the second frame to turn off the placeholder background on - // tablets so the tab strip has time to start drawing. + // Wait until the second frame to turn off the placeholder background for the CompositorView + // and the tab strip, to ensure the compositor frame has been drawn. final ViewGroup controlContainer = (ViewGroup) mControlContainer; - if (controlContainer != null && controlContainer.getBackground() != null && mHasDrawnOnce) { + if (mHasDrawnOnce) { post(new Runnable() { @Override public void run() { - controlContainer.setBackgroundResource(0); + mCompositorView.setBackgroundResource(0); + if (controlContainer != null) { + controlContainer.setBackgroundResource(0); + } } }); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java index 2181aaeb..8d745a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/InfoBarContainer.java
@@ -331,8 +331,9 @@ } public void destroy() { - if (mBottomSheetObserver != null) { - mTab.getActivity().getBottomSheet().removeObserver(mBottomSheetObserver); + ChromeActivity activity = mTab.getActivity(); + if (activity != null && mBottomSheetObserver != null && activity.getBottomSheet() != null) { + activity.getBottomSheet().removeObserver(mBottomSheetObserver); } mLayout.removeAnimationListener(mIPHSupport); removeObserver(mIPHSupport);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/locale/LocaleManager.java b/chrome/android/java/src/org/chromium/chrome/browser/locale/LocaleManager.java index 28726fd..ecb1282 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/locale/LocaleManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/locale/LocaleManager.java
@@ -228,7 +228,7 @@ Callable<PromoDialog> dialogCreator; switch (shouldShow) { case SEARCH_ENGINE_PROMO_DONT_SHOW: - return true; + return false; case SEARCH_ENGINE_PROMO_SHOW_SOGOU: dialogCreator = new Callable<PromoDialog>() { @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/BottomToolbarPhone.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/BottomToolbarPhone.java index 3550acc..55c6f70 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/BottomToolbarPhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/BottomToolbarPhone.java
@@ -219,6 +219,13 @@ } @Override + protected void setTabSwitcherMode(boolean inTabSwitcherMode, boolean showToolbar, + boolean delayAnimation, boolean animate) { + super.setTabSwitcherMode(inTabSwitcherMode, showToolbar, delayAnimation, animate); + if (!mUseToolbarHandle) mExpandButton.setClickable(!inTabSwitcherMode); + } + + @Override protected int getProgressBarColor() { int color = super.getProgressBarColor(); if (getToolbarDataProvider().getTab() != null) { @@ -371,8 +378,7 @@ public void updateButtonVisibility() { super.updateButtonVisibility(); if (!mUseToolbarHandle) { - mExpandButton.setVisibility( - urlHasFocus() || isTabSwitcherAnimationRunning() ? INVISIBLE : VISIBLE); + mExpandButton.setVisibility(urlHasFocus() ? INVISIBLE : VISIBLE); } } @@ -462,12 +468,13 @@ mExpandButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - if (mBottomSheet != null) mBottomSheet.onExpandButtonPressed(); + if (mBottomSheet != null && mTabSwitcherState == STATIC_TAB) { + mBottomSheet.onExpandButtonPressed(); + } } }); mExpandButton.setVisibility(View.VISIBLE); - mBrowsingModeViews.add(mExpandButton); updateToolbarTopMargin(); } @@ -488,7 +495,7 @@ if (mUseToolbarHandle) { mToolbarHandleView.setImageDrawable(isLightTheme() ? mHandleDark : mHandleLight); } else { - ColorStateList tint = mUseLightToolbarDrawables ? mLightModeTint : mDarkModeTint; + ColorStateList tint = isIncognito() ? mLightModeTint : mDarkModeTint; mExpandButton.setTint(tint); } } @@ -521,7 +528,11 @@ ? View.INVISIBLE : View.VISIBLE); - if (mUseToolbarHandle) mToolbarHandleView.setAlpha(1f - progress); + if (mUseToolbarHandle) { + mToolbarHandleView.setAlpha(1f - progress); + } else { + mExpandButton.setAlpha(1f - progress); + } int tabSwitcherThemeColor = getToolbarColorForVisualState(VisualState.TAB_SWITCHER_NORMAL); @@ -549,7 +560,10 @@ if (mTextureCaptureMode) { super.drawTabSwitcherAnimationOverlay(canvas, 0f); if (!mUseToolbarHandle && mExpandButton.getVisibility() != View.GONE) { + canvas.save(); + translateCanvasToView(this, mToolbarButtonsContainer, canvas); drawChild(canvas, mExpandButton, SystemClock.uptimeMillis()); + canvas.restore(); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java index 45c9ae0..b1f3583 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarPhone.java
@@ -1150,7 +1150,7 @@ * * @throws IllegalArgumentException if {@code from} is not an ancestor of {@code to}. */ - private static void translateCanvasToView(View from, View to, Canvas canvas) + protected static void translateCanvasToView(View from, View to, Canvas canvas) throws IllegalArgumentException { assert from != null; assert to != null;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/VideoFullscreenOrientationLockChromeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/VideoFullscreenOrientationLockChromeTest.java index e5b63098..063d20e3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/VideoFullscreenOrientationLockChromeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/VideoFullscreenOrientationLockChromeTest.java
@@ -44,8 +44,7 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG, MediaSwitches.IGNORE_AUTOPLAY_RESTRICTIONS_FOR_TESTS, - "enable-features=VideoFullscreenOrientationLock", - "disable-features=" + ChromeFeatureList.FULLSCREEN_ACTIVITY}) + "enable-features=VideoFullscreenOrientationLock"}) public class VideoFullscreenOrientationLockChromeTest { @Rule public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 1a1ad2b..cb4421c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -42,7 +42,6 @@ import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.compositor.bottombar.OverlayContentDelegate; @@ -98,8 +97,7 @@ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG, - ContextualSearchFieldTrial.ONLINE_DETECTION_DISABLED, - "disable-features=" + ChromeFeatureList.FULLSCREEN_ACTIVITY}) + ContextualSearchFieldTrial.ONLINE_DETECTION_DISABLED}) @Restriction(RESTRICTION_TYPE_NON_LOW_END_DEVICE) @RetryOnFailure public class ContextualSearchManagerTest {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java index 239f430..913cd89 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/fullscreen/FullscreenManagerTest.java
@@ -32,7 +32,6 @@ import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager.FullscreenListener; import org.chromium.chrome.browser.omnibox.UrlBar; @@ -63,9 +62,10 @@ * Test suite for verifying the behavior of various fullscreen actions. */ @RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, +@CommandLineFlags.Add({ + ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG, - "disable-features=" + ChromeFeatureList.FULLSCREEN_ACTIVITY}) +}) @RetryOnFailure public class FullscreenManagerTest { @Rule
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 1874c5fb..58cab9d 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2239,8 +2239,6 @@ "safe_browsing/certificate_reporting_service.h", "safe_browsing/certificate_reporting_service_factory.cc", "safe_browsing/certificate_reporting_service_factory.h", - "safe_browsing/chrome_password_protection_service.cc", - "safe_browsing/chrome_password_protection_service.h", "safe_browsing/notification_image_reporter.cc", "safe_browsing/notification_image_reporter.h", "safe_browsing/permission_reporter.cc", @@ -2288,6 +2286,8 @@ "safe_browsing/browser_feature_extractor.h", "safe_browsing/browser_features.cc", "safe_browsing/browser_features.h", + "safe_browsing/chrome_password_protection_service.cc", + "safe_browsing/chrome_password_protection_service.h", "safe_browsing/chunk_range.cc", "safe_browsing/chunk_range.h", "safe_browsing/client_side_detection_host.cc",
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index c173f2e..04a5a00 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -172,7 +172,7 @@ "DownloadHomeShowStorageInfo", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kFullscreenActivity{"FullscreenActivity", - base::FEATURE_ENABLED_BY_DEFAULT}; + base::FEATURE_DISABLED_BY_DEFAULT}; // Makes "Add to Home screen" in the app menu generate an APK for the shortcut // URL which opens Chrome in fullscreen.
diff --git a/chrome/browser/custom_home_pages_table_model.cc b/chrome/browser/custom_home_pages_table_model.cc index 5c1bc7d..8b28417a 100644 --- a/chrome/browser/custom_home_pages_table_model.cc +++ b/chrome/browser/custom_home_pages_table_model.cc
@@ -26,36 +26,6 @@ #include "ui/gfx/codec/png_codec.h" #include "url/gurl.h" -namespace { - -// Checks whether the given URL should count as one of the "current" pages. -// Returns true for all pages except dev tools and settings. -bool ShouldAddPage(const GURL& url) { - if (url.is_empty()) - return false; - - if (url.SchemeIs(content::kChromeDevToolsScheme)) - return false; - - if (url.SchemeIs(content::kChromeUIScheme)) { - if (url.host_piece() == chrome::kChromeUISettingsHost || - url.host_piece() == chrome::kChromeUISettingsFrameHost) { - return false; - } - - // For a settings page, the path will start with "/settings" not "settings" - // so find() will return 1, not 0. - if (url.host_piece() == chrome::kChromeUIUberHost && - url.path_piece().find(chrome::kChromeUISettingsHost) == 1) { - return false; - } - } - - return true; -} - -} // namespace - struct CustomHomePagesTableModel::Entry { Entry() : task_id(base::CancelableTaskTracker::kBadTaskId) {} @@ -178,7 +148,8 @@ observer_->OnItemsRemoved(index, 1); } -void CustomHomePagesTableModel::SetToCurrentlyOpenPages() { +void CustomHomePagesTableModel::SetToCurrentlyOpenPages( + const content::WebContents* ignore_contents) { // Remove the current entries. while (RowCount()) RemoveWithoutNotification(0); @@ -192,9 +163,12 @@ for (int tab_index = 0; tab_index < browser->tab_strip_model()->count(); ++tab_index) { - const GURL url = - browser->tab_strip_model()->GetWebContentsAt(tab_index)->GetURL(); - if (ShouldAddPage(url)) + const content::WebContents* contents = + browser->tab_strip_model()->GetWebContentsAt(tab_index); + if (contents == ignore_contents) + continue; + const GURL url = contents->GetURL(); + if (!url.is_empty() && !url.SchemeIs(content::kChromeDevToolsScheme)) AddWithoutNotification(add_index++, url); } }
diff --git a/chrome/browser/custom_home_pages_table_model.h b/chrome/browser/custom_home_pages_table_model.h index 9c649fa..384fb54c 100644 --- a/chrome/browser/custom_home_pages_table_model.h +++ b/chrome/browser/custom_home_pages_table_model.h
@@ -18,6 +18,10 @@ class GURL; class Profile; +namespace content { +class WebContents; +} + namespace history { class URLRow; } @@ -49,8 +53,8 @@ void Remove(int index); // Clears any entries and fills the list with pages currently opened in the - // browser. - void SetToCurrentlyOpenPages(); + // browser. |ignore_contents| is omitted from the open pages. + void SetToCurrentlyOpenPages(const content::WebContents* ignore_contents); // Returns the set of urls this model contains. std::vector<GURL> GetURLs();
diff --git a/chrome/browser/extensions/favicon_downloader.cc b/chrome/browser/extensions/favicon_downloader.cc index fa6f2ad0e..c1dc3ebe 100644 --- a/chrome/browser/extensions/favicon_downloader.cc +++ b/chrome/browser/extensions/favicon_downloader.cc
@@ -73,7 +73,7 @@ for (std::vector<content::FaviconURL>::const_iterator it = favicon_urls.begin(); it != favicon_urls.end(); ++it) { - if (it->icon_type != content::FaviconURL::INVALID_ICON) + if (it->icon_type != content::FaviconURL::IconType::kInvalid) urls.push_back(it->icon_url); } FetchIcons(urls);
diff --git a/chrome/browser/extensions/favicon_downloader_unittest.cc b/chrome/browser/extensions/favicon_downloader_unittest.cc index 1a0fb62..2c7d014 100644 --- a/chrome/browser/extensions/favicon_downloader_unittest.cc +++ b/chrome/browser/extensions/favicon_downloader_unittest.cc
@@ -103,8 +103,9 @@ TestFaviconDownloader downloader(web_contents(), std::vector<GURL>()); std::vector<content::FaviconURL> favicon_urls; - favicon_urls.push_back(content::FaviconURL( - favicon_url, content::FaviconURL::FAVICON, std::vector<gfx::Size>())); + favicon_urls.push_back( + content::FaviconURL(favicon_url, content::FaviconURL::IconType::kFavicon, + std::vector<gfx::Size>())); downloader.set_initial_favicon_urls(favicon_urls); EXPECT_EQ(0u, downloader.pending_requests()); @@ -124,8 +125,9 @@ TestFaviconDownloader downloader(web_contents(), std::vector<GURL>()); std::vector<content::FaviconURL> favicon_urls; - favicon_urls.push_back(content::FaviconURL( - favicon_url, content::FaviconURL::FAVICON, std::vector<gfx::Size>())); + favicon_urls.push_back( + content::FaviconURL(favicon_url, content::FaviconURL::IconType::kFavicon, + std::vector<gfx::Size>())); EXPECT_EQ(0u, downloader.pending_requests()); // Start downloader before favicon URLs are loaded. @@ -157,15 +159,16 @@ TestFaviconDownloader downloader(web_contents(), extra_urls); std::vector<content::FaviconURL> favicon_urls; favicon_urls.push_back(content::FaviconURL( - favicon_url_1, content::FaviconURL::FAVICON, std::vector<gfx::Size>())); + favicon_url_1, content::FaviconURL::IconType::kFavicon, + std::vector<gfx::Size>())); // This is duplicated in the favicon urls and should only be downloaded once. favicon_urls.push_back(content::FaviconURL( - empty_favicon, content::FaviconURL::FAVICON, std::vector<gfx::Size>())); + empty_favicon, content::FaviconURL::IconType::kFavicon, + std::vector<gfx::Size>())); // Invalid icons shouldn't get put into the download queue. - favicon_urls.push_back( - content::FaviconURL(GURL("http://www.google.com/invalid.ico"), - content::FaviconURL::INVALID_ICON, - std::vector<gfx::Size>())); + favicon_urls.push_back(content::FaviconURL( + GURL("http://www.google.com/invalid.ico"), + content::FaviconURL::IconType::kInvalid, std::vector<gfx::Size>())); downloader.set_initial_favicon_urls(favicon_urls); downloader.Start(); EXPECT_EQ(3u, downloader.pending_requests()); @@ -201,7 +204,8 @@ // This favicon URL should be ignored. std::vector<content::FaviconURL> favicon_urls; favicon_urls.push_back(content::FaviconURL( - favicon_url_2, content::FaviconURL::FAVICON, std::vector<gfx::Size>())); + favicon_url_2, content::FaviconURL::IconType::kFavicon, + std::vector<gfx::Size>())); downloader.set_initial_favicon_urls(favicon_urls); downloader.SkipPageFavicons(); downloader.Start();
diff --git a/chrome/browser/extensions/service_worker_apitest.cc b/chrome/browser/extensions/service_worker_apitest.cc index e432163..54dc7462 100644 --- a/chrome/browser/extensions/service_worker_apitest.cc +++ b/chrome/browser/extensions/service_worker_apitest.cc
@@ -666,6 +666,22 @@ EXPECT_EQ(starting_tab_count, browser()->tab_strip_model()->count()); } +IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, Events) { + // Extensions APIs from SW are only enabled on trunk. + ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN); + const Extension* extension = LoadExtensionWithFlags( + test_data_dir_.AppendASCII("service_worker/events"), kFlagNone); + ASSERT_TRUE(extension); + ui_test_utils::NavigateToURL(browser(), + extension->GetResourceURL("page.html")); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + std::string result; + ASSERT_TRUE(content::ExecuteScriptAndExtractString( + web_contents, "window.runEventTest()", &result)); + ASSERT_EQ("chrome.tabs.onUpdated callback", result); +} + // Tests that worker ref count increments while extension API function is // active.
diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index a730d14..97864e69 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc
@@ -547,8 +547,6 @@ BrowserThread::GetTaskRunnerForThread(BrowserThread::UI))); #endif // defined(OS_ANDROID) - globals_->host_resolver = CreateGlobalHostResolver(net_log_); - std::map<std::string, std::string> network_quality_estimator_params; variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName, &network_quality_estimator_params); @@ -578,38 +576,16 @@ globals_->network_quality_observer = content::CreateNetworkQualityObserver( globals_->network_quality_estimator.get()); - UpdateDnsClientEnabled(); -#if defined(OS_CHROMEOS) - // Creates a CertVerifyProc that doesn't allow any profile-provided certs. - globals_->cert_verifier = base::MakeUnique<net::CachingCertVerifier>( - base::MakeUnique<net::MultiThreadedCertVerifier>( - new chromeos::CertVerifyProcChromeOS())); -#else - globals_->cert_verifier = IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( - command_line, net::CertVerifier::CreateDefault()); - UMA_HISTOGRAM_BOOLEAN( - "Net.Certificate.IgnoreCertificateErrorsSPKIListPresent", - command_line.HasSwitch(switches::kIgnoreCertificateErrorsSPKIList)); -#endif - std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs( net::ct::CreateLogVerifiersForKnownLogs()); globals_->ct_logs.assign(ct_logs.begin(), ct_logs.end()); - net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier(); - globals_->cert_transparency_verifier.reset(ct_verifier); - // Add built-in logs - ct_verifier->AddLogs(globals_->ct_logs); - ct_tree_tracker_.reset(new certificate_transparency::TreeStateTracker( globals_->ct_logs, net_log_)); // Register the ct_tree_tracker_ as observer for new STHs. RegisterSTHObserver(ct_tree_tracker_.get()); - // Register the ct_tree_tracker_ as observer for verified SCTs. - globals_->cert_transparency_verifier->SetObserver(ct_tree_tracker_.get()); - CreateDefaultAuthHandlerFactory(); globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService()); globals_->host_mapping_rules.reset(new net::HostMappingRules()); if (command_line.HasSwitch(switches::kHostRules)) { @@ -654,6 +630,8 @@ #endif ConstructSystemRequestContext(); + + UpdateDnsClientEnabled(); } void IOThread::CleanUp() { @@ -670,8 +648,11 @@ // on anything observed during CleanUp process. // // Null checks are just for tests that use TestingIOThreadState. - if (globals()->cert_transparency_verifier) - globals()->cert_transparency_verifier->SetObserver(nullptr); + if (globals()->system_request_context) { + globals() + ->system_request_context->cert_transparency_verifier() + ->SetObserver(nullptr); + } if (ct_tree_tracker_.get()) { UnregisterSTHObserver(ct_tree_tracker_.get()); ct_tree_tracker_.reset(); @@ -742,7 +723,8 @@ negotiate_enable_port_.GetValue()); } -void IOThread::CreateDefaultAuthHandlerFactory() { +std::unique_ptr<net::HttpAuthHandlerFactory> +IOThread::CreateDefaultAuthHandlerFactory(net::HostResolver* host_resolver) { std::vector<std::string> supported_schemes = base::SplitString( auth_schemes_, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); globals_->http_auth_preferences.reset(new net::HttpAuthPreferences( @@ -763,16 +745,20 @@ #if defined(OS_ANDROID) UpdateAndroidAuthNegotiateAccountType(); #endif - globals_->http_auth_handler_factory = - net::HttpAuthHandlerRegistryFactory::Create( - globals_->http_auth_preferences.get(), globals_->host_resolver.get()); + + return net::HttpAuthHandlerRegistryFactory::Create( + globals_->http_auth_preferences.get(), host_resolver); } void IOThread::ClearHostCache( const base::Callback<bool(const std::string&)>& host_filter) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - net::HostCache* host_cache = globals_->host_resolver->GetHostCache(); + if (!globals_->system_request_context) + return; + + net::HostCache* host_cache = + globals_->system_request_context->host_resolver()->GetHostCache(); if (host_cache) host_cache->ClearForHosts(host_filter); } @@ -806,7 +792,8 @@ } void IOThread::UpdateDnsClientEnabled() { - globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_); + globals()->system_request_context->host_resolver()->SetDnsClientEnabled( + *dns_client_enabled_); } void IOThread::RegisterSTHObserver(net::ct::STHObserver* observer) { @@ -826,6 +813,9 @@ } void IOThread::ConstructSystemRequestContext() { + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + globals_->system_request_context = base::MakeUnique<SystemURLRequestContext>(); net::URLRequestContext* context = globals_->system_request_context.get(); @@ -853,11 +843,11 @@ globals_->data_use_ascriber->CreateNetworkDelegate( std::move(chrome_network_delegate), GetMetricsDataUseForwarder())); context->set_net_log(net_log_); - context->set_host_resolver(globals_->host_resolver.get()); + context_storage->set_host_resolver(CreateGlobalHostResolver(net_log_)); context_storage->set_ssl_config_service(GetSSLConfigService()); - context->set_http_auth_handler_factory( - globals_->http_auth_handler_factory.get()); + context_storage->set_http_auth_handler_factory( + CreateDefaultAuthHandlerFactory(context->host_resolver())); // In-memory cookie store. context_storage->set_cookie_store( @@ -875,15 +865,33 @@ context_storage->set_http_server_properties( base::MakeUnique<net::HttpServerPropertiesImpl>()); - context->set_cert_verifier(globals_->cert_verifier.get()); - context->set_cert_transparency_verifier( - globals_->cert_transparency_verifier.get()); +#if defined(OS_CHROMEOS) + // Creates a CertVerifyProc that doesn't allow any profile-provided certs. + context_storage->set_cert_verifier(base::MakeUnique<net::CachingCertVerifier>( + base::MakeUnique<net::MultiThreadedCertVerifier>( + new chromeos::CertVerifyProcChromeOS()))); +#else + context_storage->set_cert_verifier( + IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( + command_line, net::CertVerifier::CreateDefault())); + UMA_HISTOGRAM_BOOLEAN( + "Net.Certificate.IgnoreCertificateErrorsSPKIListPresent", + command_line.HasSwitch(switches::kIgnoreCertificateErrorsSPKIList)); +#endif + + std::unique_ptr<net::MultiLogCTVerifier> ct_verifier = + base::MakeUnique<net::MultiLogCTVerifier>(); + // Add built-in logs + ct_verifier->AddLogs(globals_->ct_logs); + + // Register the ct_tree_tracker_ as observer for verified SCTs. + ct_verifier->SetObserver(ct_tree_tracker_.get()); + + context_storage->set_cert_transparency_verifier(std::move(ct_verifier)); context_storage->set_ct_policy_enforcer( base::MakeUnique<net::CTPolicyEnforcer>()); - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); context_storage->set_proxy_service(ProxyServiceFactory::CreateProxyService( net_log_, context, context->network_delegate(), std::move(system_proxy_config_service_), command_line, @@ -914,7 +922,7 @@ #if !BUILDFLAG(DISABLE_FTP_SUPPORT) job_factory->SetProtocolHandler( url::kFtpScheme, - net::FtpProtocolHandler::Create(globals_->host_resolver.get())); + net::FtpProtocolHandler::Create(context->host_resolver())); #endif context_storage->set_job_factory(std::move(job_factory));
diff --git a/chrome/browser/io_thread.h b/chrome/browser/io_thread.h index 0797746a..75fa0e8 100644 --- a/chrome/browser/io_thread.h +++ b/chrome/browser/io_thread.h
@@ -75,10 +75,10 @@ } namespace net { -class CertVerifier; class CTLogVerifier; class HostMappingRules; class HostResolver; +class HttpAuthHandlerFactory; class HttpAuthPreferences; class LoggingNetworkChangeObserver; class NetworkQualityEstimator; @@ -139,11 +139,7 @@ std::unique_ptr<chrome::android::ExternalDataUseObserver> external_data_use_observer; #endif // defined(OS_ANDROID) - std::unique_ptr<net::HostResolver> host_resolver; - std::unique_ptr<net::CertVerifier> cert_verifier; std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs; - std::unique_ptr<net::CTVerifier> cert_transparency_verifier; - std::unique_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory; std::unique_ptr<net::HttpAuthPreferences> http_auth_preferences; std::unique_ptr<net::URLRequestContextStorage> system_request_context_storage; @@ -240,7 +236,8 @@ void Init() override; void CleanUp() override; - void CreateDefaultAuthHandlerFactory(); + std::unique_ptr<net::HttpAuthHandlerFactory> CreateDefaultAuthHandlerFactory( + net::HostResolver* host_resolver); // Returns an SSLConfigService instance. net::SSLConfigService* GetSSLConfigService();
diff --git a/chrome/browser/media/webrtc/window_icon_util_x11.cc b/chrome/browser/media/webrtc/window_icon_util_x11.cc index a69c365..e9b34ae5 100644 --- a/chrome/browser/media/webrtc/window_icon_util_x11.cc +++ b/chrome/browser/media/webrtc/window_icon_util_x11.cc
@@ -7,6 +7,7 @@ #include <X11/Xatom.h> #include <X11/Xutil.h> +#include "ui/base/x/x11_util.h" #include "ui/gfx/x/x11_error_tracker.h" #include "ui/gfx/x/x11_types.h" @@ -14,7 +15,7 @@ DCHECK(id.type == content::DesktopMediaID::TYPE_WINDOW); Display* display = gfx::GetXDisplay(); - Atom property = XInternAtom(display, "_NET_WM_ICON", True); + Atom property = ui::GetAtom("_NET_WM_ICON"); Atom actual_type; int actual_format; unsigned long bytes_after; // NOLINT: type required by XGetWindowProperty
diff --git a/chrome/browser/media_galleries/mac/mtp_device_delegate_impl_mac_unittest.mm b/chrome/browser/media_galleries/mac/mtp_device_delegate_impl_mac_unittest.mm index 48d39488..df2b429 100644 --- a/chrome/browser/media_galleries/mac/mtp_device_delegate_impl_mac_unittest.mm +++ b/chrome/browser/media_galleries/mac/mtp_device_delegate_impl_mac_unittest.mm
@@ -8,7 +8,6 @@ #include "base/files/file.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/mac/cocoa_protocols.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/mac/sdk_forward_declarations.h"
diff --git a/chrome/browser/metrics/variations/chrome_variations_service_client.cc b/chrome/browser/metrics/variations/chrome_variations_service_client.cc index 72b68f9..9818dfd 100644 --- a/chrome/browser/metrics/variations/chrome_variations_service_client.cc +++ b/chrome/browser/metrics/variations/chrome_variations_service_client.cc
@@ -5,12 +5,10 @@ #include "chrome/browser/metrics/variations/chrome_variations_service_client.h" #include "base/bind.h" -#include "base/threading/sequenced_worker_pool.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/common/channel_info.h" #include "components/version_info/version_info.h" -#include "content/public/browser/browser_thread.h" #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) #include "chrome/browser/upgrade_detector_impl.h" @@ -47,10 +45,6 @@ return g_browser_process->GetApplicationLocale(); } -base::SequencedWorkerPool* ChromeVariationsServiceClient::GetBlockingPool() { - return content::BrowserThread::GetBlockingPool(); -} - base::Callback<base::Version(void)> ChromeVariationsServiceClient::GetVersionForSimulationCallback() { return base::Bind(&GetVersionForSimulation);
diff --git a/chrome/browser/metrics/variations/chrome_variations_service_client.h b/chrome/browser/metrics/variations/chrome_variations_service_client.h index e62c98b..dc4ba3e9 100644 --- a/chrome/browser/metrics/variations/chrome_variations_service_client.h +++ b/chrome/browser/metrics/variations/chrome_variations_service_client.h
@@ -8,7 +8,6 @@ #include <string> #include "base/macros.h" -#include "build/build_config.h" #include "components/variations/service/variations_service_client.h" // ChromeVariationsServiceClient provides an implementation of @@ -21,7 +20,6 @@ // variations::VariationsServiceClient: std::string GetApplicationLocale() override; - base::SequencedWorkerPool* GetBlockingPool() override; base::Callback<base::Version(void)> GetVersionForSimulationCallback() override; net::URLRequestContextGetter* GetURLRequestContext() override;
diff --git a/chrome/browser/profile_resetter/brandcode_config_fetcher.cc b/chrome/browser/profile_resetter/brandcode_config_fetcher.cc index ec825eee..a061819 100644 --- a/chrome/browser/profile_resetter/brandcode_config_fetcher.cc +++ b/chrome/browser/profile_resetter/brandcode_config_fetcher.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/profile_resetter/brandcode_config_fetcher.h" #include <stddef.h> +#include <vector> #include "base/callback_helpers.h" #include "base/macros.h" @@ -22,18 +23,15 @@ const int kDownloadTimeoutSec = 10; const char kPostXml[] = -"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" -"<request version=\"1.3.17.0\" protocol=\"3.0\" testsource=\"dev\" " - "shell_version=\"1.2.3.5\">\n" -" <os platform=\"win\" version=\"6.1\" sp=\"\" arch=\"x86\" />\n" -" <app\n" -" appid=\"{8A69D345-D564-463C-AFF1-A69D9E530F96}\"\n" -" version=\"0.0.0.0\"\n" -" >\n" -" <data name=\"install\" " - "index=\"__BRANDCODE_PLACEHOLDER__\" />\n" -" </app>\n" -"</request>"; + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<request" + " version=\"chromeprofilereset-1.1\"" + " protocol=\"3.0\"" + " installsource=\"profilereset\">" + " <app appid=\"{8A69D345-D564-463C-AFF1-A69D9E530F96}\">" + " <data name=\"install\" index=\"__BRANDCODE_PLACEHOLDER__\"/>" + " </app>" + "</request>"; // Returns the query to the server which can be used to retrieve the config. // |brand| is a brand code, it mustn't be empty. @@ -139,7 +137,7 @@ std::equal(elements_.begin(), elements_.end(), data_path); } -} // namespace +} // namespace BrandcodeConfigFetcher::BrandcodeConfigFetcher(const FetchCallback& callback, const GURL& url,
diff --git a/chrome/browser/profile_resetter/brandcode_config_fetcher.h b/chrome/browser/profile_resetter/brandcode_config_fetcher.h index b56454c..c6f584b 100644 --- a/chrome/browser/profile_resetter/brandcode_config_fetcher.h +++ b/chrome/browser/profile_resetter/brandcode_config_fetcher.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_PROFILE_RESETTER_BRANDCODE_CONFIG_FETCHER_H_ #include <memory> +#include <string> #include <utility> #include "base/callback.h"
diff --git a/chrome/browser/profiles/off_the_record_profile_io_data.cc b/chrome/browser/profiles/off_the_record_profile_io_data.cc index 3510d12..c428fa01 100644 --- a/chrome/browser/profiles/off_the_record_profile_io_data.cc +++ b/chrome/browser/profiles/off_the_record_profile_io_data.cc
@@ -206,14 +206,14 @@ main_context->set_transport_security_state(transport_security_state()); main_context->set_cert_transparency_verifier( - io_thread_globals->cert_transparency_verifier.get()); + io_thread_globals->system_request_context->cert_transparency_verifier()); main_context->set_ct_policy_enforcer( io_thread_globals->system_request_context->ct_policy_enforcer()); main_context->set_net_log(io_thread->net_log()); main_context->set_http_auth_handler_factory( - io_thread_globals->http_auth_handler_factory.get()); + io_thread_globals->system_request_context->http_auth_handler_factory()); main_context->set_proxy_service(proxy_service()); // For incognito, we use the default non-persistent HttpServerPropertiesImpl.
diff --git a/chrome/browser/profiles/profile_impl_io_data.cc b/chrome/browser/profiles/profile_impl_io_data.cc index 4e01782b..26b93449 100644 --- a/chrome/browser/profiles/profile_impl_io_data.cc +++ b/chrome/browser/profiles/profile_impl_io_data.cc
@@ -484,7 +484,7 @@ main_context->set_net_log(io_thread->net_log()); main_context->set_http_auth_handler_factory( - io_thread_globals->http_auth_handler_factory.get()); + io_thread_globals->system_request_context->http_auth_handler_factory()); main_context->set_proxy_service(proxy_service()); @@ -552,7 +552,7 @@ std::move(main_job_factory), std::move(request_interceptors), std::move(profile_params->protocol_handler_interceptor), main_context->network_delegate(), - io_thread_globals->host_resolver.get())); + io_thread_globals->system_request_context->host_resolver())); main_context->set_network_quality_estimator( io_thread_globals->network_quality_estimator.get());
diff --git a/chrome/browser/profiles/profile_io_data.cc b/chrome/browser/profiles/profile_io_data.cc index 644fd76b..f0c1f86 100644 --- a/chrome/browser/profiles/profile_io_data.cc +++ b/chrome/browser/profiles/profile_io_data.cc
@@ -1030,7 +1030,7 @@ std::move(chrome_network_delegate)); main_request_context_->set_host_resolver( - io_thread_globals->host_resolver.get()); + io_thread_globals->system_request_context->host_resolver()); // NOTE: Proxy service uses the default io thread network delegate, not the // delegate just created. @@ -1097,7 +1097,8 @@ extension_info_map_ = profile_params_->extension_info_map; #endif - resource_context_->host_resolver_ = io_thread_globals->host_resolver.get(); + resource_context_->host_resolver_ = + io_thread_globals->system_request_context->host_resolver(); resource_context_->request_context_ = main_request_context_.get(); if (profile_params_->loading_predictor_observer_) { @@ -1134,7 +1135,7 @@ main_request_context_->set_cert_verifier(cert_verifier_.get()); #else main_request_context_->set_cert_verifier( - io_thread_globals->cert_verifier.get()); + io_thread_globals->system_request_context->cert_verifier()); #endif }
diff --git a/chrome/browser/resources/print_preview/data/destination_store.js b/chrome/browser/resources/print_preview/data/destination_store.js index 19499638..e4201a7 100644 --- a/chrome/browser/resources/print_preview/data/destination_store.js +++ b/chrome/browser/resources/print_preview/data/destination_store.js
@@ -595,6 +595,8 @@ this.pdfPrinterEnabled_ = !isInAppKioskMode; this.systemDefaultDestinationId_ = systemDefaultDestinationId; this.createLocalPdfPrintDestination_(); + cr.addWebUIListener('extension-printers-added', + this.onExtensionPrintersAdded_.bind(this)); if (!this.appState_.isSelectedDestinationValid()) { var destinationMatch = this.convertToDestinationMatch_( @@ -1110,7 +1112,8 @@ clearTimeout(this.extensionSearchTimeout_); this.isExtensionDestinationSearchInProgress_ = true; - this.nativeLayer_.startGetExtensionDestinations(); + this.nativeLayer_.getExtensionPrinters().then( + this.onExtensionPrintersDone_.bind(this)); cr.dispatchSimpleEvent( this, DestinationStore.EventType.DESTINATION_SEARCH_STARTED); this.extensionSearchTimeout_ = setTimeout( @@ -1383,10 +1386,6 @@ this.onPrivetCapabilitiesSet_.bind(this)); this.tracker_.add( nativeLayerEventTarget, - print_preview.NativeLayer.EventType.EXTENSION_PRINTERS_ADDED, - this.onExtensionPrintersAdded_.bind(this)); - this.tracker_.add( - nativeLayerEventTarget, print_preview.NativeLayer.EventType.EXTENSION_CAPABILITIES_SET, this.onExtensionCapabilitiesSet_.bind(this)); this.tracker_.add( @@ -1625,18 +1624,26 @@ /** * Called when an extension responds to a getExtensionDestinations * request. - * @param {Object} event Contains information about list of printers - * reported by the extension. - * {@code done} parameter is set iff this is the final list of printers - * returned as part of getExtensionDestinations request. + * @param {!Array<!{extensionId: string, + * extensionName: string, + * id: string, + * name: string, + * description: (string|undefined), + * provisional: (boolean|undefined)}>} printers The list + * containing information about printers added by an extension. * @private */ - onExtensionPrintersAdded_: function(event) { - this.insertDestinations_(event.printers.map(function(printer) { - return print_preview.ExtensionDestinationParser.parse(printer); - })); + onExtensionPrintersAdded_: function(printers) { + this.insertDestinations_( + printers.map(print_preview.ExtensionDestinationParser.parse)); + }, - if (event.done && this.isExtensionDestinationSearchInProgress_) { + /** + * Called when all extensions are done adding printers. + * @private + */ + onExtensionPrintersDone_: function() { + if (this.isExtensionDestinationSearchInProgress_) { clearTimeout(this.extensionSearchTimeout_); this.endExtensionPrinterSearch_(); }
diff --git a/chrome/browser/resources/print_preview/native_layer.js b/chrome/browser/resources/print_preview/native_layer.js index 4ad76dea..30bc22b4 100644 --- a/chrome/browser/resources/print_preview/native_layer.js +++ b/chrome/browser/resources/print_preview/native_layer.js
@@ -73,8 +73,6 @@ global.onPrivetCapabilitiesSet = this.onPrivetCapabilitiesSet_.bind(this); global.onPrivetPrintFailed = this.onPrivetPrintFailed_.bind(this); - global.onExtensionPrintersAdded = - this.onExtensionPrintersAdded_.bind(this); global.onExtensionCapabilitiesSet = this.onExtensionCapabilitiesSet_.bind(this); global.onEnableManipulateSettingsForTest = @@ -142,8 +140,6 @@ PRIVET_CAPABILITIES_SET: 'print_preview.NativeLayer.PRIVET_CAPABILITIES_SET', PRIVET_PRINT_FAILED: 'print_preview.NativeLayer.PRIVET_PRINT_FAILED', - EXTENSION_PRINTERS_ADDED: - 'print_preview.NativeLayer.EXTENSION_PRINTERS_ADDED', EXTENSION_CAPABILITIES_SET: 'print_preview.NativeLayer.EXTENSION_CAPABILITIES_SET', PRINT_PRESET_OPTIONS: 'print_preview.NativeLayer.PRINT_PRESET_OPTIONS', @@ -263,11 +259,13 @@ }, /** - * Requests that extension system dispatches an event requesting the list of - * extension managed printers. + * Request a list of extension printers. Printers are reported as they are + * found by a series of 'extension-printers-added' events. + * @return {!Promise} Will be resolved when all extension managed printers + * have been sent. */ - startGetExtensionDestinations: function() { - chrome.send('getExtensionPrinters'); + getExtensionPrinters: function() { + return cr.sendWithPromise('getExtensionPrinters'); }, /** @@ -822,24 +820,6 @@ }, /** - * @param {Array<!{extensionId: string, - * extensionName: string, - * id: string, - * name: string, - * description: (string|undefined), - * provisional: (boolean|undefined)}>} printers The list - * containing information about printers added by an extension. - * @param {boolean} done Whether this is the final list of extension - * managed printers. - */ - onExtensionPrintersAdded_: function(printers, done) { - var event = new Event(NativeLayer.EventType.EXTENSION_PRINTERS_ADDED); - event.printers = printers; - event.done = done; - this.eventTarget_.dispatchEvent(event); - }, - - /** * Called when an extension responds to a request for an extension printer * capabilities. * @param {string} printerId The printer's ID.
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc index f6138161..9827faf 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_cleaner_fetcher_win.cc
@@ -9,6 +9,7 @@ #include "base/logging.h" #include "base/macros.h" +#include "base/task_scheduler/post_task.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/safe_browsing/chrome_cleaner/srt_field_trial_win.h" #include "components/data_use_measurement/core/data_use_user_data.h" @@ -60,8 +61,8 @@ url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE); url_fetcher_->SetMaxRetriesOn5xx(3); url_fetcher_->SaveResponseToTemporaryFile( - content::BrowserThread::GetTaskRunnerForThread( - content::BrowserThread::FILE)); + base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND})); url_fetcher_->SetRequestContext(g_browser_process->system_request_context()); url_fetcher_->Start(); }
diff --git a/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc b/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc index b2a4889..ddf6a8d 100644 --- a/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc +++ b/chrome/browser/safe_browsing/client_side_detection_service_unittest.cc
@@ -70,8 +70,6 @@ class ClientSideDetectionServiceTest : public testing::Test { protected: void SetUp() override { - file_thread_.reset(new content::TestBrowserThread(BrowserThread::FILE, - &msg_loop_)); factory_.reset(new net::FakeURLFetcherFactory(NULL)); browser_thread_.reset(new content::TestBrowserThread(BrowserThread::UI, &msg_loop_)); @@ -80,7 +78,6 @@ void TearDown() override { base::RunLoop().RunUntilIdle(); csd_service_.reset(); - file_thread_.reset(); browser_thread_.reset(); } @@ -252,7 +249,6 @@ } std::unique_ptr<content::TestBrowserThread> browser_thread_; - std::unique_ptr<content::TestBrowserThread> file_thread_; std::unique_ptr<base::FieldTrialList> field_trials_; GURL phishing_url_;
diff --git a/chrome/browser/safe_browsing/download_feedback_service_unittest.cc b/chrome/browser/safe_browsing/download_feedback_service_unittest.cc index fb5e01b2..5afa6f1 100644 --- a/chrome/browser/safe_browsing/download_feedback_service_unittest.cc +++ b/chrome/browser/safe_browsing/download_feedback_service_unittest.cc
@@ -15,10 +15,12 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" +#include "base/task_scheduler/post_task.h" #include "chrome/browser/safe_browsing/download_feedback.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/mock_download_item.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -130,8 +132,8 @@ class DownloadFeedbackServiceTest : public testing::Test { public: DownloadFeedbackServiceTest() - : file_task_runner_(content::BrowserThread::GetTaskRunnerForThread( - content::BrowserThread::FILE)), + : file_task_runner_(base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND})), io_task_runner_(content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO)), request_context_getter_( @@ -165,7 +167,7 @@ protected: base::ScopedTempDir temp_dir_; content::TestBrowserThreadBundle thread_bundle_; - scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_; FakeDownloadFeedbackFactory download_feedback_factory_; @@ -248,7 +250,7 @@ feedback(0)->finish_callback().Run(); EXPECT_FALSE(feedback(0)); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_TRUE(base::PathExists(file_path)); } @@ -355,7 +357,7 @@ EXPECT_FALSE(feedback(2)); } - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); // These files should still exist since the FakeDownloadFeedback does not // delete them. EXPECT_TRUE(base::PathExists(file_path[0])); @@ -425,7 +427,7 @@ // File should still exist since the FileUtilProxy task hasn't run yet. EXPECT_TRUE(base::PathExists(file_path[2])); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); // File should be deleted since the AcquireFileCallback ran after the service // was deleted. EXPECT_FALSE(base::PathExists(file_path[2]));
diff --git a/chrome/browser/safe_browsing/download_feedback_unittest.cc b/chrome/browser/safe_browsing/download_feedback_unittest.cc index f18adfeb..8bd291f 100644 --- a/chrome/browser/safe_browsing/download_feedback_unittest.cc +++ b/chrome/browser/safe_browsing/download_feedback_unittest.cc
@@ -10,10 +10,12 @@ #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/task_scheduler/post_task.h" #include "chrome/browser/safe_browsing/two_phase_uploader.h" #include "components/safe_browsing/csd.pb.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -104,8 +106,8 @@ class DownloadFeedbackTest : public testing::Test { public: DownloadFeedbackTest() - : file_task_runner_(content::BrowserThread::GetTaskRunnerForThread( - content::BrowserThread::FILE)), + : file_task_runner_(base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND})), io_task_runner_(content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO)), url_request_context_getter_( @@ -140,7 +142,7 @@ base::FilePath upload_file_path_; std::string upload_file_data_; content::TestBrowserThreadBundle thread_bundle_; - scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; + scoped_refptr<base::SequencedTaskRunner> file_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; FakeUploaderFactory two_phase_uploader_factory_; scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_; @@ -187,7 +189,7 @@ TwoPhaseUploader::STATE_SUCCESS, net::OK, 0, ""); EXPECT_TRUE(feedback_finish_called_); feedback.reset(); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(base::PathExists(upload_file_path_)); } @@ -219,7 +221,7 @@ feedback.reset(); EXPECT_FALSE(feedback_finish_called_); - base::RunLoop().RunUntilIdle(); + content::RunAllBlockingPoolTasksUntilIdle(); EXPECT_FALSE(base::PathExists(upload_file_path_)); }
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.cc b/chrome/browser/safe_browsing/safe_browsing_service.cc index 72d4baa..bf6795ad 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service.cc
@@ -26,7 +26,6 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/browser/safe_browsing/ping_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h" #include "chrome/browser/safe_browsing/ui_manager.h" @@ -71,6 +70,7 @@ #include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" #include "chrome/browser/safe_browsing/incident_reporting/variations_seed_signature_analyzer.h" #include "chrome/browser/safe_browsing/protocol_manager.h" +#include "components/safe_browsing/password_protection/password_protection_service.h" #endif using content::BrowserThread; @@ -208,9 +208,6 @@ // observer of the preferences. prefs_map_.clear(); - // Delete the ChromePasswordProtectionService instances. - password_protection_service_map_.clear(); - Stop(true); services_delegate_->ShutdownServices(); @@ -297,10 +294,7 @@ PasswordProtectionService* SafeBrowsingService::GetPasswordProtectionService( Profile* profile) const { - DCHECK(profile); - auto it = password_protection_service_map_.find(profile); - DCHECK(it != password_protection_service_map_.end()); - return it->second.get(); + return services_delegate_->GetPasswordProtectionService(profile); } std::unique_ptr<prefs::mojom::TrackedPreferenceValidationDelegate> @@ -502,7 +496,7 @@ case chrome::NOTIFICATION_PROFILE_CREATED: { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = content::Source<Profile>(source).ptr(); - CreatePasswordProtectionService(profile); + services_delegate_->CreatePasswordProtectionService(profile); if (!profile->IsOffTheRecord()) AddPrefService(profile->GetPrefs()); break; @@ -510,7 +504,7 @@ case chrome::NOTIFICATION_PROFILE_DESTROYED: { DCHECK_CURRENTLY_ON(BrowserThread::UI); Profile* profile = content::Source<Profile>(source).ptr(); - RemovePasswordProtectionService(profile); + services_delegate_->RemovePasswordProtectionService(profile); if (!profile->IsOffTheRecord()) RemovePrefService(profile->GetPrefs()); break; @@ -621,24 +615,6 @@ services_delegate_->ProcessResourceRequest(&request); } -void SafeBrowsingService::CreatePasswordProtectionService(Profile* profile) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(profile); - auto it = password_protection_service_map_.find(profile); - DCHECK(it == password_protection_service_map_.end()); - std::unique_ptr<ChromePasswordProtectionService> service = - base::MakeUnique<ChromePasswordProtectionService>(this, profile); - password_protection_service_map_[profile] = std::move(service); -} - -void SafeBrowsingService::RemovePasswordProtectionService(Profile* profile) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(profile); - auto it = password_protection_service_map_.find(profile); - if (it != password_protection_service_map_.end()) - password_protection_service_map_.erase(it); -} - void SafeBrowsingService::CreateTriggerManager() { DCHECK_CURRENTLY_ON(BrowserThread::UI); trigger_manager_ = base::MakeUnique<TriggerManager>(ui_manager_.get());
diff --git a/chrome/browser/safe_browsing/safe_browsing_service.h b/chrome/browser/safe_browsing/safe_browsing_service.h index 262facf..93957b4 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service.h +++ b/chrome/browser/safe_browsing/safe_browsing_service.h
@@ -54,7 +54,6 @@ class ClientSideDetectionService; class DownloadProtectionService; class PasswordProtectionService; -class ChromePasswordProtectionService; struct ResourceRequestInfo; struct SafeBrowsingProtocolConfig; class SafeBrowsingDatabaseManager; @@ -282,10 +281,6 @@ // Process the observed resource requests on the UI thread. void ProcessResourceRequest(const ResourceRequestInfo& request); - void CreatePasswordProtectionService(Profile* profile); - - void RemovePasswordProtectionService(Profile* profile); - void CreateTriggerManager(); // The factory used to instantiate a SafeBrowsingService object. @@ -357,12 +352,6 @@ scoped_refptr<SafeBrowsingNavigationObserverManager> navigation_observer_manager_; - // Tracks existing Profiles, and their corresponding - // ChromePasswordProtectionService instances. - // Accessed on UI thread. - std::map<Profile*, std::unique_ptr<ChromePasswordProtectionService>> - password_protection_service_map_; - std::unique_ptr<TriggerManager> trigger_manager_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingService);
diff --git a/chrome/browser/safe_browsing/services_delegate.h b/chrome/browser/safe_browsing/services_delegate.h index 463e56b3..75a2f30b 100644 --- a/chrome/browser/safe_browsing/services_delegate.h +++ b/chrome/browser/safe_browsing/services_delegate.h
@@ -31,6 +31,7 @@ class ClientSideDetectionService; class DownloadProtectionService; class IncidentReportingService; +class PasswordProtectionService; class ResourceRequestDetector; struct ResourceRequestInfo; class SafeBrowsingService; @@ -106,6 +107,11 @@ net::URLRequestContextGetter* url_request_context_getter, const V4ProtocolConfig& v4_config) = 0; virtual void StopOnIOThread(bool shutdown) = 0; + + virtual void CreatePasswordProtectionService(Profile* profile) = 0; + virtual void RemovePasswordProtectionService(Profile* profile) = 0; + virtual PasswordProtectionService* GetPasswordProtectionService( + Profile* profile) const = 0; }; } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/services_delegate_impl.cc b/chrome/browser/safe_browsing/services_delegate_impl.cc index 89997f8f..e50cb929 100644 --- a/chrome/browser/safe_browsing/services_delegate_impl.cc +++ b/chrome/browser/safe_browsing/services_delegate_impl.cc
@@ -102,6 +102,9 @@ resource_request_detector_.reset(); incident_service_.reset(); + // Delete the ChromePasswordProtectionService instances. + password_protection_service_map_.clear(); + // Must shut down last. download_service_.reset(); } @@ -179,4 +182,31 @@ } } +void ServicesDelegateImpl::CreatePasswordProtectionService(Profile* profile) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(profile); + auto it = password_protection_service_map_.find(profile); + DCHECK(it == password_protection_service_map_.end()); + std::unique_ptr<ChromePasswordProtectionService> service = + base::MakeUnique<ChromePasswordProtectionService>(safe_browsing_service_, + profile); + password_protection_service_map_[profile] = std::move(service); +} + +void ServicesDelegateImpl::RemovePasswordProtectionService(Profile* profile) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(profile); + auto it = password_protection_service_map_.find(profile); + if (it != password_protection_service_map_.end()) + password_protection_service_map_.erase(it); +} + +PasswordProtectionService* ServicesDelegateImpl::GetPasswordProtectionService( + Profile* profile) const { + DCHECK(profile); + auto it = password_protection_service_map_.find(profile); + DCHECK(it != password_protection_service_map_.end()); + return it->second.get(); +} + } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/services_delegate_impl.h b/chrome/browser/safe_browsing/services_delegate_impl.h index 565d1e8..0138ec8 100644 --- a/chrome/browser/safe_browsing/services_delegate_impl.h +++ b/chrome/browser/safe_browsing/services_delegate_impl.h
@@ -8,11 +8,13 @@ #include <memory> #include "base/macros.h" +#include "chrome/browser/safe_browsing/chrome_password_protection_service.h" #include "chrome/browser/safe_browsing/client_side_detection_service.h" #include "chrome/browser/safe_browsing/download_protection_service.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" #include "chrome/browser/safe_browsing/incident_reporting/resource_request_detector.h" #include "chrome/browser/safe_browsing/services_delegate.h" +#include "components/safe_browsing/password_protection/password_protection_service.h" namespace safe_browsing { @@ -61,6 +63,11 @@ IncidentReportingService* CreateIncidentReportingService(); ResourceRequestDetector* CreateResourceRequestDetector(); + void CreatePasswordProtectionService(Profile* profile) override; + void RemovePasswordProtectionService(Profile* profile) override; + PasswordProtectionService* GetPasswordProtectionService( + Profile* profile) const override; + std::unique_ptr<ClientSideDetectionService> csd_service_; std::unique_ptr<DownloadProtectionService> download_service_; std::unique_ptr<IncidentReportingService> incident_service_; @@ -73,6 +80,12 @@ // Accessed on both UI and IO thread. scoped_refptr<SafeBrowsingDatabaseManager> v4_local_database_manager_; + // Tracks existing Profiles, and their corresponding + // ChromePasswordProtectionService instances. + // Accessed on UI thread. + std::map<Profile*, std::unique_ptr<ChromePasswordProtectionService>> + password_protection_service_map_; + DISALLOW_COPY_AND_ASSIGN(ServicesDelegateImpl); };
diff --git a/chrome/browser/safe_browsing/services_delegate_stub.cc b/chrome/browser/safe_browsing/services_delegate_stub.cc index b3f189d..9288ceb 100644 --- a/chrome/browser/safe_browsing/services_delegate_stub.cc +++ b/chrome/browser/safe_browsing/services_delegate_stub.cc
@@ -71,4 +71,12 @@ void ServicesDelegateStub::StopOnIOThread(bool shutdown) {} +void ServicesDelegateStub::CreatePasswordProtectionService(Profile* profile) {} +void ServicesDelegateStub::RemovePasswordProtectionService(Profile* profile) {} +PasswordProtectionService* ServicesDelegateStub::GetPasswordProtectionService( + Profile* profile) const { + NOTIMPLEMENTED(); + return nullptr; +} + } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/services_delegate_stub.h b/chrome/browser/safe_browsing/services_delegate_stub.h index 9dbe3531..2fbbec0 100644 --- a/chrome/browser/safe_browsing/services_delegate_stub.h +++ b/chrome/browser/safe_browsing/services_delegate_stub.h
@@ -38,6 +38,10 @@ net::URLRequestContextGetter* url_request_context_getter, const V4ProtocolConfig& v4_config) override; void StopOnIOThread(bool shutdown) override; + void CreatePasswordProtectionService(Profile* profile) override; + void RemovePasswordProtectionService(Profile* profile) override; + PasswordProtectionService* GetPasswordProtectionService( + Profile* profile) const override; scoped_refptr<SafeBrowsingDatabaseManager> v4_local_database_manager_;
diff --git a/chrome/browser/ui/app_list/search/answer_card_search_provider.cc b/chrome/browser/ui/app_list/search/answer_card_search_provider.cc index 2cc8230..19f01330 100644 --- a/chrome/browser/ui/app_list/search/answer_card_search_provider.cc +++ b/chrome/browser/ui/app_list/search/answer_card_search_provider.cc
@@ -81,6 +81,7 @@ public: SearchAnswerResult(Profile* profile, const std::string& result_url, + const base::string16& result_title, views::View* web_view, content::WebContents* web_contents) : WebContentsObserver(web_contents), @@ -91,6 +92,7 @@ set_id(result_url); set_relevance(1); set_view(web_view); + set_title(result_title); // web_contents may be null if the result is being duplicated after the // search provider's WebContents was destroyed. if (web_contents) { @@ -114,7 +116,7 @@ // SearchResult overrides: std::unique_ptr<SearchResult> Duplicate() const override { - return base::MakeUnique<SearchAnswerResult>(profile_, id(), view(), + return base::MakeUnique<SearchAnswerResult>(profile_, id(), title(), view(), web_contents()); } @@ -194,6 +196,8 @@ received_answer_ = false; OnResultAvailable(false); current_request_url_ = GURL(); + result_url_.empty(); + result_title_.empty(); server_request_start_time_ = answer_loaded_time_ = base::TimeTicks(); if (is_voice_query) { @@ -353,7 +357,8 @@ if (is_available) { results.reserve(1); results.emplace_back(base::MakeUnique<SearchAnswerResult>( - profile_, result_url_, web_view_.get(), web_contents_.get())); + profile_, result_url_, base::UTF8ToUTF16(result_title_), + web_view_.get(), web_contents_.get())); } SwapResults(&results); } @@ -366,6 +371,8 @@ return false; if (!headers->GetNormalizedHeader("SearchAnswer-OpenResultUrl", &result_url_)) return false; + if (!headers->GetNormalizedHeader("SearchAnswer-Title", &result_title_)) + return false; return true; }
diff --git a/chrome/browser/ui/app_list/search/answer_card_search_provider.h b/chrome/browser/ui/app_list/search/answer_card_search_provider.h index bba2a140..d2996e40 100644 --- a/chrome/browser/ui/app_list/search/answer_card_search_provider.h +++ b/chrome/browser/ui/app_list/search/answer_card_search_provider.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_WEB_CONTENTS_DELEGATE_H_ -#define CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_WEB_CONTENTS_DELEGATE_H_ +#ifndef CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_CARD_SEARCH_PROVIDER_H_ +#define CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_CARD_SEARCH_PROVIDER_H_ #include <memory> #include <string> @@ -106,9 +106,12 @@ // Url to open when the user clicks at the result. std::string result_url_; + // Title of the result. + std::string result_title_; + DISALLOW_COPY_AND_ASSIGN(AnswerCardSearchProvider); }; } // namespace app_list -#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_WEB_CONTENTS_DELEGATE_H_ +#endif // CHROME_BROWSER_UI_APP_LIST_SEARCH_ANSWER_CARD_SEARCH_PROVIDER_H_
diff --git a/chrome/browser/ui/app_list/search/search_controller_factory.cc b/chrome/browser/ui/app_list/search/search_controller_factory.cc index c8bc238..6220d78 100644 --- a/chrome/browser/ui/app_list/search/search_controller_factory.cc +++ b/chrome/browser/ui/app_list/search/search_controller_factory.cc
@@ -67,12 +67,13 @@ // omnibox. Each group has a "soft" maximum number of results. However, if // a query turns up very few results, the mixer may take more than this // maximum from a particular group. - size_t apps_group_id = controller->AddGroup(kMaxAppsGroupResults, 1.0); - size_t omnibox_group_id = controller->AddGroup(kMaxOmniboxResults, 1.0); - size_t webstore_group_id = controller->AddGroup(kMaxWebstoreResults, 0.4); + // Multiplier 100 is used because the answer card is designed to be the most // relevant result and must be on the top of the result list. size_t answer_card_group_id = controller->AddGroup(1, 100.0); + size_t apps_group_id = controller->AddGroup(kMaxAppsGroupResults, 1.0); + size_t omnibox_group_id = controller->AddGroup(kMaxOmniboxResults, 1.0); + size_t webstore_group_id = controller->AddGroup(kMaxWebstoreResults, 0.4); // Add search providers. controller->AddProvider(
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h b/chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h index 50d1bcb..865ce91f 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h
@@ -12,7 +12,6 @@ #include <memory> #include <unordered_map> -#import "base/mac/cocoa_protocols.h" #include "base/mac/scoped_nsobject.h" #include "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_bridge.h" #import "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_constants.h"
diff --git a/chrome/browser/ui/webui/options/startup_pages_handler.cc b/chrome/browser/ui/webui/options/startup_pages_handler.cc index b80a4c07..70e4655 100644 --- a/chrome/browser/ui/webui/options/startup_pages_handler.cc +++ b/chrome/browser/ui/webui/options/startup_pages_handler.cc
@@ -150,7 +150,8 @@ void StartupPagesHandler::SetStartupPagesToCurrentPages( const base::ListValue* args) { - startup_custom_pages_table_model_->SetToCurrentlyOpenPages(); + startup_custom_pages_table_model_->SetToCurrentlyOpenPages( + web_ui()->GetWebContents()); } void StartupPagesHandler::RemoveStartupPages(const base::ListValue* args) {
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index a499f47..9edc6249 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc
@@ -709,13 +709,18 @@ void PrintPreviewHandler::HandleGetExtensionPrinters( const base::ListValue* args) { + std::string callback_id; + CHECK(args->GetString(0, &callback_id)); + CHECK(!callback_id.empty()); + + AllowJavascript(); EnsureExtensionPrinterHandlerSet(); // Make sure all in progress requests are canceled before new printer search // starts. extension_printer_handler_->Reset(); extension_printer_handler_->StartGetPrinters( base::Bind(&PrintPreviewHandler::OnGotPrintersForExtension, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr(), callback_id)); } void PrintPreviewHandler::HandleGrantExtensionPrinterAccess( @@ -1735,10 +1740,15 @@ } void PrintPreviewHandler::OnGotPrintersForExtension( + const std::string& callback_id, const base::ListValue& printers, bool done) { - web_ui()->CallJavascriptFunctionUnsafe("onExtensionPrintersAdded", printers, - base::Value(done)); + AllowJavascript(); + + FireWebUIListener("extension-printers-added", printers); + if (done) { + ResolveJavascriptCallback(base::Value(callback_id), base::Value()); + } } void PrintPreviewHandler::OnGotExtensionPrinterInfo(
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.h b/chrome/browser/ui/webui/print_preview/print_preview_handler.h index 8cee113..a6c69fa 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.h +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.h
@@ -320,10 +320,14 @@ void EnsureExtensionPrinterHandlerSet(); // Called when a list of printers is reported by an extension. + // |callback_id|: The javascript callback to call if all extension printers + // are loaded (when |done| = true) // |printers|: The list of printers managed by the extension. // |done|: Whether all the extensions have reported the list of printers // they manage. - void OnGotPrintersForExtension(const base::ListValue& printers, bool done); + void OnGotPrintersForExtension(const std::string& callback_id, + const base::ListValue& printers, + bool done); // Called when an extension reports information requested for a provisional // printer.
diff --git a/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc b/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc index 5c9142f..4b128752 100644 --- a/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_startup_pages_handler.cc
@@ -174,7 +174,8 @@ void StartupPagesHandler::HandleSetStartupPagesToCurrentPages( const base::ListValue* args) { - startup_custom_pages_table_model_.SetToCurrentlyOpenPages(); + startup_custom_pages_table_model_.SetToCurrentlyOpenPages( + web_ui()->GetWebContents()); SaveStartupPagesPref(); }
diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 221bbf5f..c3cd379 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json
@@ -401,7 +401,7 @@ "contexts": ["blessed_extension"] }, "extension.getURL": { - "contexts": ["blessed_extension", "unblessed_extension", "content_script"] + "contexts": ["blessed_extension", "unblessed_extension", "content_script", "extension_service_worker"] }, "extension.getViews": [ {
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/manifest.json b/chrome/test/data/extensions/api_test/service_worker/events/manifest.json new file mode 100644 index 0000000..7de5131 --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/manifest.json
@@ -0,0 +1,6 @@ +{ + "name": "Service worker events test (chrome.tabs.onUpdated)", + "version": "1.0", + "manifest_version": 2, + "permissions": [ "tabs" ] +}
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/on_updated.html b/chrome/test/data/extensions/api_test/service_worker/events/on_updated.html new file mode 100644 index 0000000..7e096ed --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/on_updated.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<!-- + 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. +--> +<html> +<head> + <script src="on_updated.js"></script> +</head> +</html>
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/on_updated.js b/chrome/test/data/extensions/api_test/service_worker/events/on_updated.js new file mode 100644 index 0000000..5ce2a61 --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/on_updated.js
@@ -0,0 +1,13 @@ +// 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. + +window.onload = function() { + setTimeout(function() { + document.title = 'foo'; + setTimeout(function() { + document.title = 'bar'; + }, 0); + }, 0); +} +
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/page.html b/chrome/test/data/extensions/api_test/service_worker/events/page.html new file mode 100644 index 0000000..bbd70762 --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/page.html
@@ -0,0 +1,7 @@ +<!DOCTYPE html> +<!-- + 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. +--> +<script src="page.js"></script>
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/page.js b/chrome/test/data/extensions/api_test/service_worker/events/page.js new file mode 100644 index 0000000..3cd23d5 --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/page.js
@@ -0,0 +1,34 @@ +// 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. + +var workerPromise = new Promise(function(resolve, reject) { + navigator.serviceWorker.register('sw.js').then(function() { + return navigator.serviceWorker.ready; + }).then(function(registration) { + var sw = registration.active; + var channel = new MessageChannel(); + channel.port1.onmessage = function(e) { + var data = e.data; + if (data == 'listener-added') { + var url = chrome.extension.getURL('on_updated.html'); + chrome.tabs.create({url: url}); + } else if (data == 'chrome.tabs.onUpdated callback') { + resolve(data); + } else { + reject(data); + } + }; + sw.postMessage('addOnUpdatedListener', [channel.port2]); + }).catch(function(err) { + reject(err); + }); +}); + +window.runEventTest = function() { + workerPromise.then(function(message) { + window.domAutomationController.send(message); + }).catch(function(err) { + window.domAutomationController.send('FAILURE'); + }); +};
diff --git a/chrome/test/data/extensions/api_test/service_worker/events/sw.js b/chrome/test/data/extensions/api_test/service_worker/events/sw.js new file mode 100644 index 0000000..7fd97d3 --- /dev/null +++ b/chrome/test/data/extensions/api_test/service_worker/events/sw.js
@@ -0,0 +1,54 @@ +// 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. + +var expectedEventData; +var capturedEventData; + +function expect(data) { + expectedEventData = data; + capturedEventData = []; +} + +var messagePort = null; +function sendMessage(msg) { messagePort.postMessage(msg); } + +function checkExpectations() { + if (capturedEventData.length < expectedEventData.length) { + return; + } + + var passed = JSON.stringify(expectedEventData) == + JSON.stringify(capturedEventData); + if (passed) { + sendMessage('chrome.tabs.onUpdated callback'); + } else { + sendMessage('FAILURE'); + } +} + +self.onmessage = function(e) { + var data = e.data; + messagePort = e.ports[0]; + if (data == 'addOnUpdatedListener') { + addOnUpdatedListener(); + e.ports[0].postMessage('listener-added'); + } +}; + +function addOnUpdatedListener() { + chrome.tabs.onUpdated.addListener(function(tabId, info, tab) { + console.log('onUpdated, tabId: ' + tabId + ', info: ' + + JSON.stringify(info) + ', tab: ' + JSON.stringify(tab)); + capturedEventData.push(info); + checkExpectations(); + }); + + var url = chrome.extension.getURL('on_updated.html'); + expect([ + {status: 'loading', 'url': url}, + {status: 'complete'}, + {title: 'foo'}, + {title: 'bar'} + ]); +};
diff --git a/chrome/test/data/webui/polymer_browser_test_base.js b/chrome/test/data/webui/polymer_browser_test_base.js index 4165afc..150a30b 100644 --- a/chrome/test/data/webui/polymer_browser_test_base.js +++ b/chrome/test/data/webui/polymer_browser_test_base.js
@@ -11,8 +11,7 @@ * @constructor * @extends testing.Test */ -function PolymerTest() { -} +function PolymerTest() {} PolymerTest.prototype = { __proto__: testing.Test.prototype, @@ -43,18 +42,6 @@ 'chrome/test/data/webui/mocha_adapter.js', ], - /** Time when preLoad starts, i.e. before the browsePreload page is loaded. */ - preloadTime: 0, - - /** Time when test run starts. */ - runTime: 0, - - /** @override */ - preLoad: function() { - this.preloadTime = window.performance.now(); - testing.Test.prototype.preLoad.call(this); - }, - /** @override */ setUp: function() { testing.Test.prototype.setUp.call(this); @@ -109,24 +96,11 @@ }, /** @override */ - runTest: function(testBody) { - this.runTime = window.performance.now(); - testing.Test.prototype.runTest.call(this, testBody); - }, - - /** @override */ tearDown: function() { // Note: We do this in tearDown() so that we have a chance to stamp all the // dom-if templates, add elements through interaction, etc. PolymerTest.testIronIcons(document.body); - var endTime = window.performance.now(); - var delta = this.runTime - this.preloadTime; - console.log('Page load time: ' + delta.toFixed(0) + " ms"); - delta = endTime - this.runTime; - console.log('Test run time: ' + delta.toFixed(0) + " ms"); - delta = endTime - this.preloadTime; - console.log('Total time: ' + delta.toFixed(0) + " ms"); testing.Test.prototype.tearDown.call(this); } };
diff --git a/chrome/test/data/webui/print_preview/native_layer_stub.js b/chrome/test/data/webui/print_preview/native_layer_stub.js index 33aca5f..4e35e6b 100644 --- a/chrome/test/data/webui/print_preview/native_layer_stub.js +++ b/chrome/test/data/webui/print_preview/native_layer_stub.js
@@ -10,7 +10,11 @@ */ function NativeLayerStub() { TestBrowserProxy.call(this, [ - 'getInitialSettings', 'getPrinters', 'setupPrinter' ]); + 'getInitialSettings', + 'getPrinters', + 'getExtensionPrinters', + 'setupPrinter' + ]); /** * @private {!cr.EventTarget} The event target used for dispatching and @@ -80,6 +84,12 @@ }, /** @override */ + getExtensionPrinters: function() { + this.methodCalled('getExtensionPrinters'); + return Promise.resolve(true); + }, + + /** @override */ setupPrinter: function(printerId) { this.methodCalled('setupPrinter', printerId); return this.shouldRejectPrinterSetup_ ? @@ -91,7 +101,6 @@ previewReadyForTest: function() {}, startGetLocalDestinations: function() {}, startGetPrivetDestinations: function() {}, - startGetExtensionDestinations: function() {}, startGetLocalDestinationCapabilities: function(destinationId) { if (destinationId == this.destinationToWatch_) this.getLocalDestinationCapabilitiesCallCount_++;
diff --git a/chrome/test/data/webui/test_api.js b/chrome/test/data/webui/test_api.js index a58c731..8868a016 100644 --- a/chrome/test/data/webui/test_api.js +++ b/chrome/test/data/webui/test_api.js
@@ -53,16 +53,15 @@ * will break. animationend events should still work. */ Test.disableAnimationsAndTransitions = function() { - var noAnimationStyle = document.createElement('style'); - noAnimationStyle.id = 'no-animation'; - noAnimationStyle.textContent = - '*, * /deep/ * {' + - ' -webkit-transition-duration: 0ms !important;' + - ' -webkit-transition-delay: 0ms !important;' + - ' animation-duration: 0ms !important;' + - ' animation-delay: 0ms !important;' + - '}'; - document.querySelector('head').appendChild(noAnimationStyle); + let all = document.body.querySelectorAll('*, * /deep/ *'); + const ZERO_MS_IMPORTANT = '0ms !important'; + for (let i = 0, l = all.length; i < l; ++i) { + let style = all[i].style; + style.animationDelay = ZERO_MS_IMPORTANT; + style.animationDuration = ZERO_MS_IMPORTANT; + style.transitionDelay = ZERO_MS_IMPORTANT; + style.transitionDuration = ZERO_MS_IMPORTANT; + } var realElementAnimate = Element.prototype.animate; Element.prototype.animate = function(keyframes, opt_options) {
diff --git a/chromecast/base/alarm_manager.cc b/chromecast/base/alarm_manager.cc index f724489b..83eb24a 100644 --- a/chromecast/base/alarm_manager.cc +++ b/chromecast/base/alarm_manager.cc
@@ -4,18 +4,22 @@ #include "chromecast/base/alarm_manager.h" +#include <utility> + +#include "base/bind.h" +#include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/clock.h" #include "base/time/default_clock.h" -#include "base/timer/timer.h" -#define MAKE_SURE_OWN_THREAD(callback, ...) \ - if (!task_runner_->BelongsToCurrentThread()) { \ - task_runner_->PostTask( \ - FROM_HERE, base::Bind(&AlarmManager::callback, \ - weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ - return; \ +#define MAKE_SURE_OWN_THREAD(callback, ...) \ + if (!task_runner_->BelongsToCurrentThread()) { \ + task_runner_->PostTask( \ + FROM_HERE, base::BindOnce(&AlarmManager::callback, \ + weak_factory_.GetWeakPtr(), ##__VA_ARGS__)); \ + return; \ } namespace chromecast { @@ -23,35 +27,43 @@ namespace { int kClockPollInterval = 5; -void VerifyHandleCallback(const base::Closure& task, +void VerifyHandleCallback(base::OnceClosure task, base::WeakPtr<AlarmHandle> handle) { if (!handle.get()) { return; } - task.Run(); + std::move(task).Run(); } } // namespace AlarmManager::AlarmInfo::AlarmInfo( - const base::Closure& task, + base::OnceClosure task, base::Time time, scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : task_(task), time_(time), task_runner_(task_runner) {} + : task_(std::move(task)), + time_(time), + task_runner_(std::move(task_runner)) {} AlarmManager::AlarmInfo::~AlarmInfo() {} +void AlarmManager::AlarmInfo::PostTask() { + task_runner_->PostTask(FROM_HERE, std::move(task_)); +} + AlarmManager::AlarmManager( std::unique_ptr<base::Clock> clock, scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : clock_(std::move(clock)), task_runner_(task_runner), weak_factory_(this) { - DCHECK(task_runner.get()); - clock_tick_timer_.reset(new base::RepeatingTimer()); - clock_tick_timer_->SetTaskRunner(task_runner_); + : clock_(std::move(clock)), + task_runner_(std::move(task_runner)), + weak_factory_(this) { + DCHECK(clock_); + DCHECK(task_runner_); + clock_tick_timer_.SetTaskRunner(task_runner_); base::TimeDelta polling_frequency = base::TimeDelta::FromSeconds(kClockPollInterval); - clock_tick_timer_->Start( - FROM_HERE, polling_frequency, - base::Bind(&AlarmManager::CheckAlarm, weak_factory_.GetWeakPtr())); + clock_tick_timer_.Start(FROM_HERE, polling_frequency, + base::BindRepeating(&AlarmManager::CheckAlarm, + weak_factory_.GetWeakPtr())); } AlarmManager::AlarmManager() @@ -60,32 +72,31 @@ AlarmManager::~AlarmManager() {} -std::unique_ptr<AlarmHandle> AlarmManager::PostAlarmTask( - const base::Closure& task, - base::Time time) { +std::unique_ptr<AlarmHandle> AlarmManager::PostAlarmTask(base::OnceClosure task, + base::Time time) { + DCHECK(task); std::unique_ptr<AlarmHandle> handle = base::MakeUnique<AlarmHandle>(); - AddAlarm(base::Bind(&VerifyHandleCallback, task, handle->AsWeakPtr()), time, - base::ThreadTaskRunnerHandle::Get()); + AddAlarm(base::BindOnce(&VerifyHandleCallback, std::move(task), + handle->AsWeakPtr()), + time, base::ThreadTaskRunnerHandle::Get()); return handle; } void AlarmManager::AddAlarm( - const base::Closure& task, + base::OnceClosure task, base::Time time, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - MAKE_SURE_OWN_THREAD(AddAlarm, task, time, task_runner); - std::unique_ptr<AlarmInfo> info = - base::MakeUnique<AlarmInfo>(task, time, task_runner); - next_alarm_.push(std::move(info)); + MAKE_SURE_OWN_THREAD(AddAlarm, std::move(task), time, std::move(task_runner)); + next_alarm_.push(base::MakeUnique<AlarmInfo>(std::move(task), time, + std::move(task_runner))); } void AlarmManager::CheckAlarm() { DCHECK(task_runner_->BelongsToCurrentThread()); base::Time now = clock_->Now(); // Fire appropriate alarms. - while ((!next_alarm_.empty()) && now >= next_alarm_.top()->time()) { - next_alarm_.top()->task_runner()->PostTask(FROM_HERE, - next_alarm_.top()->task()); + while (!next_alarm_.empty() && now >= next_alarm_.top()->time()) { + next_alarm_.top()->PostTask(); next_alarm_.pop(); } }
diff --git a/chromecast/base/alarm_manager.h b/chromecast/base/alarm_manager.h index 45e497b..70ec2869 100644 --- a/chromecast/base/alarm_manager.h +++ b/chromecast/base/alarm_manager.h
@@ -5,6 +5,8 @@ #ifndef CHROMECAST_BASE_ALARM_MANAGER_H_ #define CHROMECAST_BASE_ALARM_MANAGER_H_ +#include <functional> +#include <memory> #include <queue> #include <vector> @@ -12,11 +14,11 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" +#include "base/timer/timer.h" namespace base { class Clock; class SingleThreadTaskRunner; -class Timer; } namespace chromecast { @@ -55,26 +57,24 @@ // if it is past the requested time if the software is suspended. However, // once woken up, the event will fire within 5 seconds if the target time has // passed. - std::unique_ptr<AlarmHandle> PostAlarmTask(const base::Closure& task, + std::unique_ptr<AlarmHandle> PostAlarmTask(base::OnceClosure task, base::Time time) WARN_UNUSED_RESULT; private: class AlarmInfo { public: - AlarmInfo(const base::Closure& task, + AlarmInfo(base::OnceClosure task, base::Time time, scoped_refptr<base::SingleThreadTaskRunner> task_runner); ~AlarmInfo(); - const base::Closure task() const { return task_; } + void PostTask(); + base::Time time() const { return time_; } - scoped_refptr<base::SingleThreadTaskRunner> task_runner() const { - return task_runner_; - } private: - const base::Closure task_; + base::OnceClosure task_; const base::Time time_; const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; DISALLOW_COPY_AND_ASSIGN(AlarmInfo); @@ -83,7 +83,7 @@ // Check if an alarm should fire. void CheckAlarm(); // Add the alarm to the queue. - void AddAlarm(const base::Closure& task, + void AddAlarm(base::OnceClosure task, base::Time time, scoped_refptr<base::SingleThreadTaskRunner> task_runner); @@ -106,7 +106,7 @@ // Poller for wall clock time. std::unique_ptr<base::Clock> clock_; - std::unique_ptr<base::Timer> clock_tick_timer_; + base::RepeatingTimer clock_tick_timer_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; base::WeakPtrFactory<AlarmManager> weak_factory_;
diff --git a/chromecast/base/alarm_manager_unittest.cc b/chromecast/base/alarm_manager_unittest.cc index 09f62cd..fb14c24 100644 --- a/chromecast/base/alarm_manager_unittest.cc +++ b/chromecast/base/alarm_manager_unittest.cc
@@ -4,6 +4,9 @@ #include "chromecast/base/alarm_manager.h" +#include <memory> +#include <utility> + #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" @@ -13,6 +16,7 @@ #include "testing/gtest/include/gtest/gtest.h" namespace chromecast { + class AlarmManagerTest : public ::testing::Test { protected: class WallClockDependantTask { @@ -55,7 +59,7 @@ base::Time alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), alarm_time)); task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(9)); clock->Advance(base::TimeDelta::FromMinutes(9)); @@ -79,7 +83,7 @@ // Add an alarm. base::Time alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), alarm_time)); clock->Advance(base::TimeDelta::FromMinutes(10)); task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(10)); @@ -109,7 +113,7 @@ // Add an alarm in the past. Should fire right away. base::Time alarm_time = base::Time::Now() - base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), alarm_time)); task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(10)); task_runner_->RunUntilIdle(); @@ -132,7 +136,7 @@ // Add an alarm. The time jumps to the future. base::Time alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), alarm_time)); clock->Advance(base::TimeDelta::FromMinutes(10)); task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(1)); @@ -156,7 +160,7 @@ // Add an alarm. The time jumps far into the future. base::Time alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task.GetWeakPtr()), alarm_time)); clock->Advance(base::TimeDelta::FromMinutes(60)); task_runner_->FastForwardBy(base::TimeDelta::FromMinutes(1)); @@ -182,13 +186,13 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), alarm_time)); // First task should fire. @@ -228,13 +232,13 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(10); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), alarm_time)); // Second task should fire. @@ -276,19 +280,19 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(16); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), alarm_time)); // Add third task. alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle3(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), alarm_time)); // First and third task should fire. @@ -320,19 +324,19 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(15); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(16); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), alarm_time)); // Add third task. alarm_time = now + base::TimeDelta::FromMinutes(11); std::unique_ptr<AlarmHandle> handle3(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3.GetWeakPtr()), alarm_time)); // Third task should fire. @@ -369,19 +373,19 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(15); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add it again with less time. alarm_time = now + base::TimeDelta::FromMinutes(1); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1.GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(16); std::unique_ptr<AlarmHandle> handle3(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2.GetWeakPtr()), alarm_time)); // First task should fire. @@ -425,19 +429,19 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(16); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), alarm_time)); // Add third task. alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle3(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), alarm_time)); // Remove the first task. @@ -474,19 +478,19 @@ // Add first task. base::Time alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle1(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task1->GetWeakPtr()), alarm_time)); // Add second task. alarm_time = now + base::TimeDelta::FromMinutes(16); std::unique_ptr<AlarmHandle> handle2(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task2->GetWeakPtr()), alarm_time)); // Add third task. alarm_time = now + base::TimeDelta::FromMinutes(12); std::unique_ptr<AlarmHandle> handle3(manager->PostAlarmTask( - base::Bind(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), + base::BindOnce(&WallClockDependantTask::OnAlarmFire, task3->GetWeakPtr()), alarm_time)); // Delete the first task's handle. @@ -500,4 +504,5 @@ ASSERT_FALSE(task2->fired_); ASSERT_TRUE(task3->fired_); } -} + +} // namespace chromecast
diff --git a/chromecast/base/chromecast_config_android.cc b/chromecast/base/chromecast_config_android.cc index a13da60..1b36b79 100644 --- a/chromecast/base/chromecast_config_android.cc +++ b/chromecast/base/chromecast_config_android.cc
@@ -4,6 +4,8 @@ #include "chromecast/base/chromecast_config_android.h" +#include <utility> + #include "base/android/jni_android.h" #include "base/lazy_instance.h" #include "jni/ChromecastConfigAndroid_jni.h" @@ -43,16 +45,20 @@ // Registers a handler to be notified when SendUsageStats is changed. void ChromecastConfigAndroid::SetSendUsageStatsChangedCallback( - const base::Callback<void(bool)>& callback) { - send_usage_stats_changed_callback_ = callback; + base::RepeatingCallback<void(bool)> callback) { + send_usage_stats_changed_callback_ = std::move(callback); +} + +void ChromecastConfigAndroid::RunSendUsageStatsChangedCallback(bool enabled) { + send_usage_stats_changed_callback_.Run(enabled); } // Called from Java. void SetSendUsageStatsEnabled(JNIEnv* env, const JavaParamRef<jclass>& caller, jboolean enabled) { - ChromecastConfigAndroid::GetInstance()-> - send_usage_stats_changed_callback().Run(enabled); + ChromecastConfigAndroid::GetInstance()->RunSendUsageStatsChangedCallback( + enabled); } } // namespace android
diff --git a/chromecast/base/chromecast_config_android.h b/chromecast/base/chromecast_config_android.h index 88c35365d..4f2864f 100644 --- a/chromecast/base/chromecast_config_android.h +++ b/chromecast/base/chromecast_config_android.h
@@ -25,11 +25,9 @@ // Registers a handler to be notified when SendUsageStats is changed. void SetSendUsageStatsChangedCallback( - const base::Callback<void(bool)>& callback); + base::RepeatingCallback<void(bool)> callback); - const base::Callback<void(bool)>& send_usage_stats_changed_callback() const { - return send_usage_stats_changed_callback_; - } + void RunSendUsageStatsChangedCallback(bool enabled); private: friend struct base::LazyInstanceTraitsBase<ChromecastConfigAndroid>; @@ -37,7 +35,7 @@ ChromecastConfigAndroid(); ~ChromecastConfigAndroid(); - base::Callback<void(bool)> send_usage_stats_changed_callback_; + base::RepeatingCallback<void(bool)> send_usage_stats_changed_callback_; DISALLOW_COPY_AND_ASSIGN(ChromecastConfigAndroid); };
diff --git a/chromecast/base/component/component.cc b/chromecast/base/component/component.cc index 1c7662d..4807ca1 100644 --- a/chromecast/base/component/component.cc +++ b/chromecast/base/component/component.cc
@@ -5,6 +5,7 @@ #include "chromecast/base/component/component.h" #include <set> +#include <utility> #include "base/atomicops.h" #include "base/bind.h" @@ -142,7 +143,7 @@ void DisableComplete() { if (!task_runner_->BelongsToCurrentThread()) { task_runner_->PostTask( - FROM_HERE, base::Bind(&DependencyCount::DisableComplete, this)); + FROM_HERE, base::BindOnce(&DependencyCount::DisableComplete, this)); return; } // Need to make sure that Enable() was not called in the meantime. @@ -302,9 +303,9 @@ void ComponentBase::OnEnableComplete(bool success) { // Always post a task, to prevent the stack from getting too deep. - task_runner_->PostTask(FROM_HERE, - base::Bind(&ComponentBase::OnEnableCompleteInternal, - base::Unretained(this), success)); + task_runner_->PostTask( + FROM_HERE, base::BindOnce(&ComponentBase::OnEnableCompleteInternal, + base::Unretained(this), success)); } void ComponentBase::OnEnableCompleteInternal(bool success) { @@ -377,9 +378,9 @@ void ComponentBase::OnDisableComplete() { // Always post a task, to prevent calls to Disable() from within Enable(). - task_runner_->PostTask(FROM_HERE, - base::Bind(&ComponentBase::OnDisableCompleteInternal, - base::Unretained(this))); + task_runner_->PostTask( + FROM_HERE, base::BindOnce(&ComponentBase::OnDisableCompleteInternal, + base::Unretained(this))); } void ComponentBase::OnDisableCompleteInternal() {
diff --git a/chromecast/base/component/component.h b/chromecast/base/component/component.h index a545ea435..c4f4a17 100644 --- a/chromecast/base/component/component.h +++ b/chromecast/base/component/component.h
@@ -81,8 +81,8 @@ // // ... Enable setup manager ... // // OnEnableComplete() may be called asynchronously. // base::ThreadTaskRunnerHandle::Get()->PostTask( -// FROM_HERE, base::Bind(&SetupManagerImpl::CompleteEnable, -// base::Unretained(this))); +// FROM_HERE, base::BindOnce(&SetupManagerImpl::CompleteEnable, +// base::Unretained(this))); // } // // void CompleteEnable() {
diff --git a/chromecast/base/component/component_unittest.cc b/chromecast/base/component/component_unittest.cc index 60348cd0..d56e2ff7 100644 --- a/chromecast/base/component/component_unittest.cc +++ b/chromecast/base/component/component_unittest.cc
@@ -45,8 +45,8 @@ Test(); } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ComponentA::OnEnableComplete, - base::Unretained(this), !fail_enable_)); + FROM_HERE, base::BindOnce(&ComponentA::OnEnableComplete, + base::Unretained(this), !fail_enable_)); } void OnDisable() override { @@ -55,7 +55,7 @@ enabled_ = false; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ComponentA::OnDisableComplete, base::Unretained(this))); + base::BindOnce(&ComponentA::OnDisableComplete, base::Unretained(this))); } void Test() { @@ -85,8 +85,8 @@ Test(); } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ComponentB::OnEnableComplete, - base::Unretained(this), !fail_enable_)); + FROM_HERE, base::BindOnce(&ComponentB::OnEnableComplete, + base::Unretained(this), !fail_enable_)); } void OnDisable() override { @@ -95,7 +95,7 @@ enabled_ = false; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ComponentB::OnDisableComplete, base::Unretained(this))); + base::BindOnce(&ComponentB::OnDisableComplete, base::Unretained(this))); } void Test() { @@ -124,8 +124,8 @@ Test(); } base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&ComponentC::OnEnableComplete, - base::Unretained(this), !fail_enable_)); + FROM_HERE, base::BindOnce(&ComponentC::OnEnableComplete, + base::Unretained(this), !fail_enable_)); } void OnDisable() override { @@ -134,7 +134,7 @@ enabled_ = false; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::Bind(&ComponentC::OnDisableComplete, base::Unretained(this))); + base::BindOnce(&ComponentC::OnDisableComplete, base::Unretained(this))); } void Test() {
diff --git a/chromecast/base/device_capabilities_impl.cc b/chromecast/base/device_capabilities_impl.cc index 8f4bbaa6..d6b1685bb 100644 --- a/chromecast/base/device_capabilities_impl.cc +++ b/chromecast/base/device_capabilities_impl.cc
@@ -8,6 +8,8 @@ #include <utility> +#include "base/bind.h" +#include "base/bind_helpers.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" @@ -271,9 +273,9 @@ // post a task to the Validator's thread with weak_ptr. This way, if the // Validator gets unregistered, the call to Validate will get skipped. validator_it->second->task_runner()->PostTask( - FROM_HERE, base::Bind(&ValidatorInfo::Validate, - validator_it->second->AsWeakPtr(), path, - base::Passed(&proposed_value))); + FROM_HERE, base::BindOnce(&ValidatorInfo::Validate, + validator_it->second->AsWeakPtr(), path, + std::move(proposed_value))); return; } } @@ -309,8 +311,8 @@ if (!task_runner_for_writes_->BelongsToCurrentThread()) { task_runner_for_writes_->PostTask( FROM_HERE, - base::Bind(&DeviceCapabilitiesImpl::SetPublicValidatedValue, - base::Unretained(this), path, base::Passed(&new_value))); + base::BindOnce(&DeviceCapabilitiesImpl::SetPublicValidatedValue, + base::Unretained(this), path, std::move(new_value))); return; } @@ -372,8 +374,8 @@ if (!task_runner_for_writes_->BelongsToCurrentThread()) { task_runner_for_writes_->PostTask( FROM_HERE, - base::Bind(&DeviceCapabilitiesImpl::SetPrivateValidatedValue, - base::Unretained(this), path, base::Passed(&new_value))); + base::BindOnce(&DeviceCapabilitiesImpl::SetPrivateValidatedValue, + base::Unretained(this), path, std::move(new_value))); return; }
diff --git a/chromecast/base/metrics/cast_metrics_helper.cc b/chromecast/base/metrics/cast_metrics_helper.cc index 8bf5dd4..269ff089 100644 --- a/chromecast/base/metrics/cast_metrics_helper.cc +++ b/chromecast/base/metrics/cast_metrics_helper.cc
@@ -6,6 +6,7 @@ #include <memory> #include <string> +#include <utility> #include <vector> #include "base/bind.h" @@ -26,12 +27,12 @@ namespace metrics { // A useful macro to make sure current member function runs on the valid thread. -#define MAKE_SURE_THREAD(callback, ...) \ - if (!task_runner_->BelongsToCurrentThread()) { \ - task_runner_->PostTask(FROM_HERE, \ - base::Bind(&CastMetricsHelper::callback, \ - base::Unretained(this), ##__VA_ARGS__)); \ - return; \ +#define MAKE_SURE_THREAD(callback, ...) \ + if (!task_runner_->BelongsToCurrentThread()) { \ + task_runner_->PostTask( \ + FROM_HERE, base::BindOnce(&CastMetricsHelper::callback, \ + base::Unretained(this), ##__VA_ARGS__)); \ + return; \ } namespace { @@ -118,7 +119,8 @@ : task_runner_(task_runner), metrics_sink_(NULL), logged_first_audio_(false), - record_action_callback_(base::Bind(&base::RecordComputedAction)) { + record_action_callback_( + base::BindRepeating(&base::RecordComputedAction)) { DCHECK(task_runner_.get()); DCHECK(!g_instance); g_instance = this; @@ -252,10 +254,9 @@ metrics_sink_ = delegate; } -void CastMetricsHelper::SetRecordActionCallback( - const RecordActionCallback& callback) { +void CastMetricsHelper::SetRecordActionCallback(RecordActionCallback callback) { DCHECK(task_runner_->BelongsToCurrentThread()); - record_action_callback_ = callback; + record_action_callback_ = std::move(callback); } void CastMetricsHelper::SetDummySessionIdForTesting() {
diff --git a/chromecast/base/metrics/cast_metrics_helper.h b/chromecast/base/metrics/cast_metrics_helper.h index 2ecca8a..61f9b3cf 100644 --- a/chromecast/base/metrics/cast_metrics_helper.h +++ b/chromecast/base/metrics/cast_metrics_helper.h
@@ -30,7 +30,8 @@ kAbortedBuffering, }; - typedef base::Callback<void(const std::string&)> RecordActionCallback; + using RecordActionCallback = + base::RepeatingCallback<void(const std::string&)>; class MetricsSink { public: @@ -113,7 +114,7 @@ // Sets a default callback to record user action when MetricsSink is not set. // This function could be called multiple times (in unittests), and // CastMetricsHelper only honors the last one. - virtual void SetRecordActionCallback(const RecordActionCallback& callback); + virtual void SetRecordActionCallback(RecordActionCallback callback); // Sets an all-0's session ID for running browser tests. void SetDummySessionIdForTesting();
diff --git a/chromecast/base/metrics/mock_cast_metrics_helper.h b/chromecast/base/metrics/mock_cast_metrics_helper.h index 7436620..9afd107 100644 --- a/chromecast/base/metrics/mock_cast_metrics_helper.h +++ b/chromecast/base/metrics/mock_cast_metrics_helper.h
@@ -5,6 +5,8 @@ #ifndef CHROMECAST_BASE_METRICS_MOCK_CAST_METRICS_HELPER_H_ #define CHROMECAST_BASE_METRICS_MOCK_CAST_METRICS_HELPER_H_ +#include <string> + #include "base/macros.h" #include "chromecast/base/metrics/cast_metrics_helper.h" #include "testing/gmock/include/gmock/gmock.h" @@ -36,8 +38,7 @@ std::string(const std::string& prefix, const std::string& suffix)); MOCK_METHOD1(SetMetricsSink, void(MetricsSink* delegate)); - MOCK_METHOD1(SetRecordActionCallback, - void(const RecordActionCallback& callback)); + MOCK_METHOD1(SetRecordActionCallback, void(RecordActionCallback callback)); private: DISALLOW_COPY_AND_ASSIGN(MockCastMetricsHelper);
diff --git a/chromecast/base/system_time_change_notifier.cc b/chromecast/base/system_time_change_notifier.cc index 174a385..fbceae1 100644 --- a/chromecast/base/system_time_change_notifier.cc +++ b/chromecast/base/system_time_change_notifier.cc
@@ -4,6 +4,7 @@ #include "chromecast/base/system_time_change_notifier.h" +#include "base/bind.h" #include "base/location.h" #include "base/sequenced_task_runner.h" @@ -80,8 +81,8 @@ expected_system_time_ = now + next_checking_interval; task_runner_->PostDelayedTask( FROM_HERE, - base::Bind(&SystemTimeChangeNotifierPeriodicMonitor::CheckSystemTime, - weak_factory_.GetWeakPtr()), + base::BindOnce(&SystemTimeChangeNotifierPeriodicMonitor::CheckSystemTime, + weak_factory_.GetWeakPtr()), next_checking_interval); }
diff --git a/chromecast/base/task_runner_impl.cc b/chromecast/base/task_runner_impl.cc index ff0c62a..90e40410 100644 --- a/chromecast/base/task_runner_impl.cc +++ b/chromecast/base/task_runner_impl.cc
@@ -23,7 +23,7 @@ // TODO(halliwell): FROM_HERE is misleading, we should consider a macro for // vendor backends to send the callsite info. return runner_->PostDelayedTask( - FROM_HERE, base::Bind(&Task::Run, base::Owned(task)), + FROM_HERE, base::BindOnce(&Task::Run, base::Owned(task)), base::TimeDelta::FromMilliseconds(delay_milliseconds)); }
diff --git a/chromecast/browser/cast_browser_main_parts.cc b/chromecast/browser/cast_browser_main_parts.cc index ea8a603..56e941ce 100644 --- a/chromecast/browser/cast_browser_main_parts.cc +++ b/chromecast/browser/cast_browser_main_parts.cc
@@ -235,6 +235,7 @@ #if defined(OS_ANDROID) {switches::kDisableGLDrawingForTests, ""}, {switches::kSkipGpuDataLoading, ""}, + {switches::kDisableGpuCompositing, ""}, #endif // defined(OS_ANDROID) #endif // BUILDFLAG(IS_CAST_AUDIO_ONLY) #if defined(OS_LINUX)
diff --git a/components/browsing_data_strings.grdp b/components/browsing_data_strings.grdp index 993cd7f..2f5317c 100644 --- a/components/browsing_data_strings.grdp +++ b/components/browsing_data_strings.grdp
@@ -116,10 +116,10 @@ =1 {and 1 more} other {and # more}} </message> - <message name="IDS_DEL_MEDIA_LICENSES_COUNTER_GENERAL_COMMENT" desc="A static message shown in the Clear Browsing Data dialog explaining to the user that clearing media licenses will result in the user being unable to play some premium content"> - You may lose access to premium content from some sites. + <message name="IDS_DEL_MEDIA_LICENSES_COUNTER_GENERAL_COMMENT" desc="A static message shown in the Clear Browsing Data dialog explaining to the user that clearing media licenses will result in the user being unable to play some protected content"> + You may lose access to protected content from some sites. </message> - <message name="IDS_DEL_MEDIA_LICENSES_COUNTER_SITE_COMMENT" desc="A message shown in the Clear Browsing Data dialog explaining to the user that clearing media licenses will result in the user being unable to play some premium content from at least one specific web site"> - You may lose access to premium content from <ph name="SITE">$1<ex>youtube.com</ex></ph> and some other sites. + <message name="IDS_DEL_MEDIA_LICENSES_COUNTER_SITE_COMMENT" desc="A message shown in the Clear Browsing Data dialog explaining to the user that clearing media licenses will result in the user being unable to play some protected content from at least one specific web site"> + You may lose access to protected content from <ph name="SITE">$1<ex>youtube.com</ex></ph> and some other sites. </message> </grit-part>
diff --git a/components/favicon/content/content_favicon_driver_unittest.cc b/components/favicon/content/content_favicon_driver_unittest.cc index 5439aee..0c52143 100644 --- a/components/favicon/content/content_favicon_driver_unittest.cc +++ b/components/favicon/content/content_favicon_driver_unittest.cc
@@ -78,7 +78,7 @@ // Mimic a page load. TestFetchFaviconForPage( kPageURL, - {content::FaviconURL(kIconURL, content::FaviconURL::FAVICON, + {content::FaviconURL(kIconURL, content::FaviconURL::IconType::kFavicon, kEmptyIconSizes)}); EXPECT_TRUE(web_contents_tester()->TestDidDownloadImage( kIconURL, 200, kEmptyIcons, kEmptyIconSizes)); @@ -92,7 +92,7 @@ // Mimic a page load. TestFetchFaviconForPage( kPageURL, - {content::FaviconURL(kIconURL, content::FaviconURL::FAVICON, + {content::FaviconURL(kIconURL, content::FaviconURL::IconType::kFavicon, kEmptyIconSizes)}); // Verify that no download request is pending for the image. EXPECT_FALSE(web_contents_tester()->HasPendingDownloadImage(kIconURL)); @@ -105,9 +105,10 @@ // Mimic a page load. TestFetchFaviconForPage( kPageURL, - {content::FaviconURL(kIconURL, content::FaviconURL::FAVICON, + {content::FaviconURL(kIconURL, content::FaviconURL::IconType::kFavicon, kEmptyIconSizes), - content::FaviconURL(kOtherIconURL, content::FaviconURL::FAVICON, + content::FaviconURL(kOtherIconURL, + content::FaviconURL::IconType::kFavicon, kEmptyIconSizes)}); // Verify a download request is pending for the second image. EXPECT_FALSE(web_contents_tester()->HasPendingDownloadImage(kIconURL)); @@ -121,9 +122,9 @@ ASSERT_EQ(nullptr, web_contents()->GetController().GetLastCommittedEntry()); std::vector<content::FaviconURL> favicon_urls; - favicon_urls.push_back( - content::FaviconURL(GURL("http://www.google.ca/favicon.ico"), - content::FaviconURL::FAVICON, kEmptyIconSizes)); + favicon_urls.push_back(content::FaviconURL( + GURL("http://www.google.ca/favicon.ico"), + content::FaviconURL::IconType::kFavicon, kEmptyIconSizes)); favicon::ContentFaviconDriver* driver = favicon::ContentFaviconDriver::FromWebContents(web_contents()); static_cast<content::WebContentsObserver*>(driver) @@ -141,9 +142,9 @@ // Navigation to a page updating one icon. NavigateAndCommit(GURL("http://www.youtube.com")); - driver_as_observer->DidUpdateFaviconURL( - {content::FaviconURL(GURL("http://www.youtube.com/favicon.ico"), - content::FaviconURL::FAVICON, kSizes16x16and32x32)}); + driver_as_observer->DidUpdateFaviconURL({content::FaviconURL( + GURL("http://www.youtube.com/favicon.ico"), + content::FaviconURL::IconType::kFavicon, kSizes16x16and32x32)}); EXPECT_THAT(tester.GetAllSamples("Favicons.CandidatesCount"), ElementsAre(base::Bucket(/*min=*/1, /*count=*/1))); @@ -154,12 +155,14 @@ std::vector<content::FaviconURL> favicon_urls = { content::FaviconURL(GURL("http://www.google.ca/favicon.ico"), - content::FaviconURL::FAVICON, kSizes16x16and32x32), + content::FaviconURL::IconType::kFavicon, + kSizes16x16and32x32), content::FaviconURL(GURL("http://www.google.ca/precomposed_icon.png"), - content::FaviconURL::TOUCH_PRECOMPOSED_ICON, + content::FaviconURL::IconType::kTouchPrecomposedIcon, kEmptyIconSizes), content::FaviconURL(GURL("http://www.google.ca/touch_icon.png"), - content::FaviconURL::TOUCH_ICON, kEmptyIconSizes)}; + content::FaviconURL::IconType::kTouchIcon, + kEmptyIconSizes)}; // Double navigation to a page with 3 different icons. NavigateAndCommit(GURL("http://www.google.ca"));
diff --git a/components/favicon/content/favicon_url_util.cc b/components/favicon/content/favicon_url_util.cc index c77ff8b..f08149ac 100644 --- a/components/favicon/content/favicon_url_util.cc +++ b/components/favicon/content/favicon_url_util.cc
@@ -17,13 +17,13 @@ favicon_base::IconType IconTypeFromContentIconType( content::FaviconURL::IconType icon_type) { switch (icon_type) { - case content::FaviconURL::FAVICON: + case content::FaviconURL::IconType::kFavicon: return favicon_base::FAVICON; - case content::FaviconURL::TOUCH_ICON: + case content::FaviconURL::IconType::kTouchIcon: return favicon_base::TOUCH_ICON; - case content::FaviconURL::TOUCH_PRECOMPOSED_ICON: + case content::FaviconURL::IconType::kTouchPrecomposedIcon: return favicon_base::TOUCH_PRECOMPOSED_ICON; - case content::FaviconURL::INVALID_ICON: + case content::FaviconURL::IconType::kInvalid: return favicon_base::INVALID_ICON; } NOTREACHED();
diff --git a/components/offline_pages/core/prefetch/BUILD.gn b/components/offline_pages/core/prefetch/BUILD.gn index 915cd91..a8da79a 100644 --- a/components/offline_pages/core/prefetch/BUILD.gn +++ b/components/offline_pages/core/prefetch/BUILD.gn
@@ -58,6 +58,26 @@ ] } +static_library("test_support") { + testonly = true + sources = [ + "prefetch_service_test_taco.cc", + "prefetch_service_test_taco.h", + "test_offline_metrics_collector.h", + "test_prefetch_dispatcher.cc", + "test_prefetch_dispatcher.h", + "test_prefetch_gcm_handler.cc", + "test_prefetch_gcm_handler.h", + ] + + deps = [ + ":prefetch", + "//base", + "//components/keyed_service/core", + "//components/offline_pages/core", + ] +} + proto_library("proto") { sources = [ "proto/any.proto", @@ -84,6 +104,7 @@ deps = [ ":prefetch", + ":test_support", "//components/offline_pages/core", "//components/offline_pages/core:test_support", "//net:test_support",
diff --git a/components/offline_pages/core/prefetch/prefetch_service.h b/components/offline_pages/core/prefetch/prefetch_service.h index b7fbae13..b507bab 100644 --- a/components/offline_pages/core/prefetch/prefetch_service.h +++ b/components/offline_pages/core/prefetch/prefetch_service.h
@@ -24,11 +24,14 @@ // lightweight, all heavy work must be done on-demand only. // The service manages lifetime, hookup and initialization of Prefetch // system that consists of multiple specialized objects, all vended by this - // service. All pointers are raw and are always valid. + // service. virtual OfflineMetricsCollector* GetOfflineMetricsCollector() = 0; virtual PrefetchDispatcher* GetPrefetchDispatcher() = 0; virtual PrefetchGCMHandler* GetPrefetchGCMHandler() = 0; virtual PrefetchStore* GetPrefetchStore() = 0; + + // May be |nullptr| in tests. The PrefetchService does not depend on the + // SuggestedArticlesObserver, it merely owns it for lifetime purposes. virtual SuggestedArticlesObserver* GetSuggestedArticlesObserver() = 0; };
diff --git a/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc new file mode 100644 index 0000000..4161a07 --- /dev/null +++ b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc
@@ -0,0 +1,67 @@ +// 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 "components/offline_pages/core/prefetch/prefetch_service_test_taco.h" + +#include "base/memory/ptr_util.h" + +#include "components/offline_pages/core/prefetch/offline_metrics_collector.h" +#include "components/offline_pages/core/prefetch/prefetch_dispatcher.h" +#include "components/offline_pages/core/prefetch/prefetch_dispatcher_impl.h" +#include "components/offline_pages/core/prefetch/prefetch_gcm_handler.h" +#include "components/offline_pages/core/prefetch/prefetch_in_memory_store.h" +#include "components/offline_pages/core/prefetch/prefetch_service_impl.h" +#include "components/offline_pages/core/prefetch/suggested_articles_observer.h" +#include "components/offline_pages/core/prefetch/test_offline_metrics_collector.h" +#include "components/offline_pages/core/prefetch/test_prefetch_gcm_handler.h" + +namespace offline_pages { + +PrefetchServiceTestTaco::PrefetchServiceTestTaco() { + metrics_collector_ = base::MakeUnique<TestOfflineMetricsCollector>(); + dispatcher_ = base::MakeUnique<PrefetchDispatcherImpl>(); + gcm_handler_ = base::MakeUnique<TestPrefetchGCMHandler>(); + store_ = base::MakeUnique<PrefetchInMemoryStore>(); +} + +PrefetchServiceTestTaco::~PrefetchServiceTestTaco() = default; + +void PrefetchServiceTestTaco::SetOfflineMetricsCollector( + std::unique_ptr<OfflineMetricsCollector> metrics_collector) { + CHECK(!prefetch_service_); + metrics_collector_ = std::move(metrics_collector); +} + +void PrefetchServiceTestTaco::SetPrefetchDispatcher( + std::unique_ptr<PrefetchDispatcher> dispatcher) { + CHECK(!prefetch_service_); + dispatcher_ = std::move(dispatcher); +} + +void PrefetchServiceTestTaco::SetPrefetchGCMHandler( + std::unique_ptr<PrefetchGCMHandler> gcm_handler) { + CHECK(!prefetch_service_); + gcm_handler_ = std::move(gcm_handler); +} + +void PrefetchServiceTestTaco::SetPrefetchStore( + std::unique_ptr<PrefetchStore> store) { + CHECK(!prefetch_service_); + store_ = std::move(store); +} + +void PrefetchServiceTestTaco::SetSuggestedArticlesObserver( + std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer) { + CHECK(!prefetch_service_); + suggested_articles_observer_ = std::move(suggested_articles_observer); +} + +void PrefetchServiceTestTaco::CreatePrefetchService() { + prefetch_service_ = base::MakeUnique<PrefetchServiceImpl>( + std::move(metrics_collector_), std::move(dispatcher_), + std::move(gcm_handler_), std::move(store_), + std::move(suggested_articles_observer_)); +} + +} // namespace offline_page
diff --git a/components/offline_pages/core/prefetch/prefetch_service_test_taco.h b/components/offline_pages/core/prefetch/prefetch_service_test_taco.h new file mode 100644 index 0000000..08ccfd6 --- /dev/null +++ b/components/offline_pages/core/prefetch/prefetch_service_test_taco.h
@@ -0,0 +1,71 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_PREFETCH_SERVICE_TEST_TACO_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_PREFETCH_SERVICE_TEST_TACO_H_ + +#include <memory> + +#include "base/logging.h" + +namespace offline_pages { +class OfflineMetricsCollector; +class PrefetchDispatcher; +class PrefetchGCMHandler; +class PrefetchService; +class PrefetchStore; +class SuggestedArticlesObserver; + +// The taco class acts as a wrapper around the prefetch service making +// it easy to create for tests, using test versions of the dependencies. +// This class is like a taco shell, and the filling is the prefetch service. +// The default dependencies may be replaced by the test author to provide +// custom versions that have test-specific hooks. +// +// Default types of objects held by the test service: +// * TestOfflineMetricsCollector +// * PrefetchDispatcherImpl +// * TestPrefetchGCMHandler +// * PrefetchInMemoryStore +// * |nullptr| SuggestedArticlesObserver, since this is default just a lifetime +// arrangement. +class PrefetchServiceTestTaco { + public: + PrefetchServiceTestTaco(); + ~PrefetchServiceTestTaco(); + + // These methods must be called before CreatePrefetchService() is invoked. + // If called after they will CHECK(). + void SetOfflineMetricsCollector( + std::unique_ptr<OfflineMetricsCollector> metrics_collector); + void SetPrefetchDispatcher(std::unique_ptr<PrefetchDispatcher> dispatcher); + void SetPrefetchGCMHandler(std::unique_ptr<PrefetchGCMHandler> gcm_handler); + void SetPrefetchStore(std::unique_ptr<PrefetchStore> prefetch_store); + void SetSuggestedArticlesObserver( + std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer); + + // Creates and caches an instance of PrefetchService, using default or + // overridden test dependencies. + void CreatePrefetchService(); + + // Once CreatePrefetchService() is called, this accessor method starts + // returning the PrefetchService. + + PrefetchService* prefetch_service() { + CHECK(prefetch_service_); + return prefetch_service_.get(); + } + + private: + std::unique_ptr<OfflineMetricsCollector> metrics_collector_; + std::unique_ptr<PrefetchDispatcher> dispatcher_; + std::unique_ptr<PrefetchGCMHandler> gcm_handler_; + std::unique_ptr<PrefetchStore> store_; + std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer_; + + std::unique_ptr<PrefetchService> prefetch_service_; +}; + +} // namespace offline_pages +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_PREFETCH_SERVICE_TEST_TACO_H_
diff --git a/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc b/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc index d91d07b..0338550 100644 --- a/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc +++ b/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc
@@ -11,6 +11,8 @@ #include "components/offline_pages/core/prefetch/prefetch_dispatcher.h" #include "components/offline_pages/core/prefetch/prefetch_gcm_app_handler.h" #include "components/offline_pages/core/prefetch/prefetch_service.h" +#include "components/offline_pages/core/prefetch/prefetch_service_test_taco.h" +#include "components/offline_pages/core/prefetch/test_prefetch_dispatcher.h" #include "components/offline_pages/core/stub_offline_page_model.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -28,76 +30,26 @@ return ContentSuggestion(category, test_url.spec(), test_url); } -class TestingPrefetchDispatcher : public PrefetchDispatcher { - public: - TestingPrefetchDispatcher() = default; - - void SetService(PrefetchService* service) override{}; - - void AddCandidatePrefetchURLs( - const std::vector<PrefetchURL>& prefetch_urls) override { - latest_prefetch_urls = prefetch_urls; - new_suggestions_count++; - } - - void RemoveAllUnprocessedPrefetchURLs( - const std::string& name_space) override { - DCHECK_EQ(kSuggestedArticlesNamespace, name_space); - latest_prefetch_urls.clear(); - remove_all_suggestions_count++; - } - - void RemovePrefetchURLsByClientId(const ClientId& client_id) override { - DCHECK_EQ(kSuggestedArticlesNamespace, client_id.name_space); - remove_by_client_id_count++; - last_removed_client_id = client_id; - } - - void BeginBackgroundTask( - std::unique_ptr<ScopedBackgroundTask> task) override {} - void StopBackgroundTask() override {} - void RequestFinishBackgroundTaskForTest() override {} - - std::vector<PrefetchURL> latest_prefetch_urls; - ClientId last_removed_client_id; - - int new_suggestions_count = 0; - int remove_all_suggestions_count = 0; - int remove_by_client_id_count = 0; -}; - -class TestingPrefetchService : public PrefetchService { - public: - TestingPrefetchService() : observer(&dispatcher) {} - - OfflineMetricsCollector* GetOfflineMetricsCollector() override { - return nullptr; - } - PrefetchDispatcher* GetPrefetchDispatcher() override { return &dispatcher; } - PrefetchGCMHandler* GetPrefetchGCMHandler() override { return nullptr; } - PrefetchStore* GetPrefetchStore() override { return nullptr; } - SuggestedArticlesObserver* GetSuggestedArticlesObserver() override { - return &observer; - } - - TestingPrefetchDispatcher dispatcher; - SuggestedArticlesObserver observer; -}; - } // namespace class OfflinePageSuggestedArticlesObserverTest : public testing::Test { public: - OfflinePageSuggestedArticlesObserverTest() {} - - SuggestedArticlesObserver* observer() { - return &(test_prefetch_service()->observer); + OfflinePageSuggestedArticlesObserverTest() { + test_prefetch_dispatcher_ = new TestPrefetchDispatcher(); + prefetch_service_test_taco_.SetPrefetchDispatcher( + base::WrapUnique(test_prefetch_dispatcher_)); + prefetch_service_test_taco_.SetSuggestedArticlesObserver( + base::MakeUnique<SuggestedArticlesObserver>(test_prefetch_dispatcher_)); + prefetch_service_test_taco_.CreatePrefetchService(); } - TestingPrefetchService* test_prefetch_service() { return &prefetch_service_; } + SuggestedArticlesObserver* observer() { + return prefetch_service_test_taco_.prefetch_service() + ->GetSuggestedArticlesObserver(); + } - TestingPrefetchDispatcher* test_prefetch_dispatcher() { - return &(test_prefetch_service()->dispatcher); + TestPrefetchDispatcher* test_prefetch_dispatcher() { + return test_prefetch_dispatcher_; } protected: @@ -105,7 +57,10 @@ Category::FromKnownCategory(ntp_snippets::KnownCategories::ARTICLES); private: - TestingPrefetchService prefetch_service_; + PrefetchServiceTestTaco prefetch_service_test_taco_; + + // Owned by the PrefetchServiceTestTaco. + TestPrefetchDispatcher* test_prefetch_dispatcher_; }; TEST_F(OfflinePageSuggestedArticlesObserverTest, @@ -161,8 +116,9 @@ ntp_snippets::ContentSuggestion::ID(category, test_url_1.spec())); EXPECT_EQ(1, test_prefetch_dispatcher()->remove_by_client_id_count); + EXPECT_NE(nullptr, test_prefetch_dispatcher()->last_removed_client_id.get()); EXPECT_EQ(test_url_1.spec(), - test_prefetch_dispatcher()->last_removed_client_id.id); + test_prefetch_dispatcher()->last_removed_client_id->id); EXPECT_EQ( kSuggestedArticlesNamespace, test_prefetch_dispatcher()->latest_prefetch_urls[0].client_id.name_space);
diff --git a/components/offline_pages/core/prefetch/test_offline_metrics_collector.h b/components/offline_pages/core/prefetch/test_offline_metrics_collector.h new file mode 100644 index 0000000..f3c679333c --- /dev/null +++ b/components/offline_pages/core/prefetch/test_offline_metrics_collector.h
@@ -0,0 +1,26 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_OFFLINE_METRICS_COLLECTOR_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_OFFLINE_METRICS_COLLECTOR_H_ + +#include "components/offline_pages/core/prefetch/offline_metrics_collector.h" + +namespace offline_pages { + +// Testing metrics collector that does nothing. +class TestOfflineMetricsCollector : public OfflineMetricsCollector { + public: + TestOfflineMetricsCollector() = default; + ~TestOfflineMetricsCollector() override = default; + + void OnAppStartupOrResume() override {} + void OnSuccessfulNavigationOnline() override {} + void OnSuccessfulNavigationOffline() override {} + void ReportAccumulatedStats() override {} +}; + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_OFFLINE_METRICS_COLLECTOR_H_
diff --git a/components/offline_pages/core/prefetch/test_prefetch_dispatcher.cc b/components/offline_pages/core/prefetch/test_prefetch_dispatcher.cc new file mode 100644 index 0000000..97fd67b7 --- /dev/null +++ b/components/offline_pages/core/prefetch/test_prefetch_dispatcher.cc
@@ -0,0 +1,42 @@ +// 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 "components/offline_pages/core/prefetch/test_prefetch_dispatcher.h" + +#include "base/memory/ptr_util.h" +#include "components/offline_pages/core/offline_page_item.h" + +namespace offline_pages { + +TestPrefetchDispatcher::TestPrefetchDispatcher() = default; +TestPrefetchDispatcher::~TestPrefetchDispatcher() = default; + +void TestPrefetchDispatcher::AddCandidatePrefetchURLs( + const std::vector<PrefetchURL>& suggested_urls) { + latest_prefetch_urls = suggested_urls; + new_suggestions_count++; +} + +void TestPrefetchDispatcher::RemoveAllUnprocessedPrefetchURLs( + const std::string& name_space) { + latest_prefetch_urls.clear(); + remove_all_suggestions_count++; +} + +void TestPrefetchDispatcher::RemovePrefetchURLsByClientId( + const ClientId& client_id) { + remove_by_client_id_count++; + last_removed_client_id = base::MakeUnique<ClientId>(client_id); +} + +void TestPrefetchDispatcher::BeginBackgroundTask( + std::unique_ptr<ScopedBackgroundTask> task) {} + +void TestPrefetchDispatcher::StopBackgroundTask() {} + +void TestPrefetchDispatcher::SetService(PrefetchService* service) {} + +void TestPrefetchDispatcher::RequestFinishBackgroundTaskForTest() {} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/test_prefetch_dispatcher.h b/components/offline_pages/core/prefetch/test_prefetch_dispatcher.h new file mode 100644 index 0000000..609dcbc3 --- /dev/null +++ b/components/offline_pages/core/prefetch/test_prefetch_dispatcher.h
@@ -0,0 +1,43 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_DISPATCHER_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_DISPATCHER_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "components/offline_pages/core/prefetch/prefetch_dispatcher.h" + +namespace offline_pages { +struct ClientId; + +// Testing version of the prefetch dispatcher. +class TestPrefetchDispatcher : public PrefetchDispatcher { + public: + TestPrefetchDispatcher(); + ~TestPrefetchDispatcher() override; + + // PrefetchDispatcher implementation. + void AddCandidatePrefetchURLs( + const std::vector<PrefetchURL>& suggested_urls) override; + void RemoveAllUnprocessedPrefetchURLs(const std::string& name_space) override; + void RemovePrefetchURLsByClientId(const ClientId& client_id) override; + void BeginBackgroundTask(std::unique_ptr<ScopedBackgroundTask> task) override; + void StopBackgroundTask() override; + void SetService(PrefetchService* service) override; + void RequestFinishBackgroundTaskForTest() override; + + std::vector<PrefetchURL> latest_prefetch_urls; + std::unique_ptr<ClientId> last_removed_client_id; + + int new_suggestions_count = 0; + int remove_all_suggestions_count = 0; + int remove_by_client_id_count = 0; +}; + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_DISPATCHER_H_
diff --git a/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.cc b/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.cc new file mode 100644 index 0000000..3a658df --- /dev/null +++ b/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.cc
@@ -0,0 +1,20 @@ +// 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 "components/offline_pages/core/prefetch/test_prefetch_gcm_handler.h" + +namespace offline_pages { + +TestPrefetchGCMHandler::TestPrefetchGCMHandler() = default; +TestPrefetchGCMHandler::~TestPrefetchGCMHandler() = default; + +gcm::GCMAppHandler* TestPrefetchGCMHandler::AsGCMAppHandler() { + return nullptr; +} + +std::string TestPrefetchGCMHandler::GetAppId() const { + return "com.google.test.PrefetchAppId"; +} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.h b/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.h new file mode 100644 index 0000000..c6274c8 --- /dev/null +++ b/components/offline_pages/core/prefetch/test_prefetch_gcm_handler.h
@@ -0,0 +1,26 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_GCM_HANDLER_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_GCM_HANDLER_H_ + +#include <string> + +#include "components/offline_pages/core/prefetch/prefetch_gcm_handler.h" + +namespace offline_pages { + +// Test for testing. +class TestPrefetchGCMHandler : public PrefetchGCMHandler { + public: + TestPrefetchGCMHandler(); + ~TestPrefetchGCMHandler() override; + + gcm::GCMAppHandler* AsGCMAppHandler() override; + std::string GetAppId() const override; +}; + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_TEST_PREFETCH_GCM_HANDLER_H_
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index 056d7d6..30a1555 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -189,10 +189,6 @@ sources -= [ "login_database_posix.cc" ] } - if (!is_ios) { - deps += [ "//components/safe_browsing/password_protection" ] - } - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] }
diff --git a/components/password_manager/core/browser/DEPS b/components/password_manager/core/browser/DEPS index d4cbab2..5e1a7a7 100644 --- a/components/password_manager/core/browser/DEPS +++ b/components/password_manager/core/browser/DEPS
@@ -2,7 +2,6 @@ "+components/autofill/core/browser", "+components/keyed_service/core", "+components/pref_registry", - "+components/safe_browsing/password_protection", "+components/security_state", "+components/sync/base", "+components/sync/driver",
diff --git a/components/password_manager/core/browser/password_reuse_detection_manager.cc b/components/password_manager/core/browser/password_reuse_detection_manager.cc index d4942acf..49a0691 100644 --- a/components/password_manager/core/browser/password_reuse_detection_manager.cc +++ b/components/password_manager/core/browser/password_reuse_detection_manager.cc
@@ -11,9 +11,6 @@ #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "ui/events/keycodes/keyboard_codes_posix.h" -#if defined(SAFE_BROWSING_DB_LOCAL) || defined(SAFE_BROWSING_DB_REMOTE) -#include "components/safe_browsing/password_protection/password_protection_service.h" -#endif using base::Time; using base::TimeDelta;
diff --git a/components/password_manager/core/browser/password_reuse_detector.cc b/components/password_manager/core/browser/password_reuse_detector.cc index 5bf0abb..33da0da 100644 --- a/components/password_manager/core/browser/password_reuse_detector.cc +++ b/components/password_manager/core/browser/password_reuse_detector.cc
@@ -37,6 +37,8 @@ } // namespace +const char kSyncPasswordDomain[] = "CHROME SYNC"; + bool ReverseStringLess::operator()(const base::string16& lhs, const base::string16& rhs) const { return std::lexicographical_compare(lhs.rbegin(), lhs.rend(), rhs.rbegin(), @@ -94,8 +96,8 @@ base::StringPiece16 input_suffix(input.c_str() + i, input.size() - i); if (password_manager_util::Calculate37BitsOfSHA256Hash(input_suffix) == sync_password_hash_.value()) { - consumer->OnReuseFound(input_suffix.as_string(), gaia_origin.host(), 1, - 0); + consumer->OnReuseFound(input_suffix.as_string(), + std::string(kSyncPasswordDomain), 1, 0); return true; } }
diff --git a/components/password_manager/core/browser/password_reuse_detector.h b/components/password_manager/core/browser/password_reuse_detector.h index 3cf6569..f6d2d49d 100644 --- a/components/password_manager/core/browser/password_reuse_detector.h +++ b/components/password_manager/core/browser/password_reuse_detector.h
@@ -29,6 +29,9 @@ bool operator()(const base::string16& lhs, const base::string16& rhs) const; }; +// Used to identify chrome sync password in password entry event. +extern const char kSyncPasswordDomain[]; + // Per-profile class responsible for detection of password reuse, i.e. that the // user input on some site contains the password saved on another site. // It receives saved passwords through PasswordStoreConsumer interface.
diff --git a/components/password_manager/core/browser/password_reuse_detector_consumer.h b/components/password_manager/core/browser/password_reuse_detector_consumer.h index b621b77..fb6dc8c8 100644 --- a/components/password_manager/core/browser/password_reuse_detector_consumer.h +++ b/components/password_manager/core/browser/password_reuse_detector_consumer.h
@@ -21,8 +21,8 @@ virtual ~PasswordReuseDetectorConsumer(); // Called when a password reuse is found. - // |legitimate_domain| is the domain on which |password| is saved or the sync - // domain if |password| is a sync password. + // |legitimate_domain| is the domain on which |password| is saved or + // safe_browsing::kChromeSyncDomain if |password| is a sync password. // |saved_passwords| is total number of passwords stored in Password Manager. // |number_matches| is a number of sites on which |password| is saved. virtual void OnReuseFound(const base::string16& password,
diff --git a/components/password_manager/core/browser/password_reuse_detector_unittest.cc b/components/password_manager/core/browser/password_reuse_detector_unittest.cc index 94d2fa82..2f45d16d 100644 --- a/components/password_manager/core/browser/password_reuse_detector_unittest.cc +++ b/components/password_manager/core/browser/password_reuse_detector_unittest.cc
@@ -209,8 +209,9 @@ reuse_detector.SaveSyncPasswordHash(ASCIIToUTF16("sync_password")); - EXPECT_CALL(mockConsumer, OnReuseFound(ASCIIToUTF16("sync_password"), - "accounts.google.com", 1, 0)); + EXPECT_CALL(mockConsumer, + OnReuseFound(ASCIIToUTF16("sync_password"), + std::string(kSyncPasswordDomain), 1, 0)); reuse_detector.CheckReuse(ASCIIToUTF16("sync_password"), "https://evil.com", &mockConsumer); }
diff --git a/components/password_manager/core/browser/password_store_unittest.cc b/components/password_manager/core/browser/password_store_unittest.cc index c32f2e1..7f166a8 100644 --- a/components/password_manager/core/browser/password_store_unittest.cc +++ b/components/password_manager/core/browser/password_store_unittest.cc
@@ -28,6 +28,7 @@ #include "components/password_manager/core/browser/affiliation_service.h" #include "components/password_manager/core/browser/mock_affiliated_match_helper.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_reuse_detector.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "components/password_manager/core/browser/password_store_default.h" #include "testing/gmock/include/gmock/gmock.h" @@ -989,8 +990,9 @@ // Check that sync password reuse is found. MockPasswordReuseDetectorConsumer mock_consumer; - EXPECT_CALL(mock_consumer, - OnReuseFound(sync_password, "accounts.google.com", 1, 0)); + EXPECT_CALL( + mock_consumer, + OnReuseFound(sync_password, std::string(kSyncPasswordDomain), 1, 0)); store->CheckReuse(input, "https://facebook.com", &mock_consumer); base::RunLoop().RunUntilIdle(); testing::Mock::VerifyAndClearExpectations(&mock_consumer);
diff --git a/components/safe_browsing/password_protection/BUILD.gn b/components/safe_browsing/password_protection/BUILD.gn index a7be564..dcd862f 100644 --- a/components/safe_browsing/password_protection/BUILD.gn +++ b/components/safe_browsing/password_protection/BUILD.gn
@@ -3,48 +3,54 @@ # found in the LICENSE file. source_set("password_protection") { - sources = [ - "password_protection_request.cc", - "password_protection_request.h", - "password_protection_service.cc", - "password_protection_service.h", - ] + if (!is_android && !is_ios) { + sources = [ + "password_protection_request.cc", + "password_protection_request.h", + "password_protection_service.cc", + "password_protection_service.h", + ] - public_deps = [ - "//google_apis:google_apis", - ] + public_deps = [ + "//google_apis:google_apis", + ] - deps = [ - "//base:base", - "//components/content_settings/core/browser:browser", - "//components/data_use_measurement/core:core", - "//components/history/core/browser:browser", - "//components/safe_browsing:csd_proto", - "//components/safe_browsing_db:database_manager", - "//components/safe_browsing_db:v4_protocol_manager_util", - "//content/public/browser:browser", - "//net:net", - "//third_party/protobuf:protobuf_lite", - ] + deps = [ + "//base:base", + "//components/content_settings/core/browser:browser", + "//components/data_use_measurement/core:core", + "//components/history/core/browser:browser", + "//components/password_manager/core/browser:browser", + "//components/safe_browsing:csd_proto", + "//components/safe_browsing_db:database_manager", + "//components/safe_browsing_db:v4_protocol_manager_util", + "//content/public/browser:browser", + "//net:net", + "//third_party/protobuf:protobuf_lite", + ] + } } source_set("password_protection_unittest") { testonly = true - sources = [ - "password_protection_service_unittest.cc", - ] - deps = [ - ":password_protection", - "//base", - "//base/test:test_support", - "//components/content_settings/core/browser:browser", - "//components/history/core/browser:browser", - "//components/safe_browsing_db:test_database_manager", - "//components/sync_preferences:test_support", - "//content/test:test_support", - "//net:test_support", - "//testing/gmock", - "//testing/gtest", - "//third_party/protobuf:protobuf_lite", - ] + if (!is_android && !is_ios) { + sources = [ + "password_protection_service_unittest.cc", + ] + deps = [ + ":password_protection", + "//base", + "//base/test:test_support", + "//components/content_settings/core/browser:browser", + "//components/history/core/browser:browser", + "//components/password_manager/core/browser:browser", + "//components/safe_browsing_db:test_database_manager", + "//components/sync_preferences:test_support", + "//content/test:test_support", + "//net:test_support", + "//testing/gmock", + "//testing/gtest", + "//third_party/protobuf:protobuf_lite", + ] + } }
diff --git a/components/safe_browsing/password_protection/DEPS b/components/safe_browsing/password_protection/DEPS index f04e7f6..1752444f 100644 --- a/components/safe_browsing/password_protection/DEPS +++ b/components/safe_browsing/password_protection/DEPS
@@ -1,11 +1,8 @@ include_rules = [ - "-content", "+components/content_settings/core/browser", "+components/history/core/browser", - "+components/safe_browsing/csd.pb.h", - "+components/safe_browsing_db", + "+components/password_manager/core/browser/password_reuse_detector.h", "+components/sync_preferences/testing_pref_service_syncable.h", - "+content/public/browser", "+content/public/test", "+net", ]
diff --git a/components/safe_browsing/password_protection/password_protection_request.cc b/components/safe_browsing/password_protection/password_protection_request.cc index 0f74a1e..245dcf9 100644 --- a/components/safe_browsing/password_protection/password_protection_request.cc +++ b/components/safe_browsing/password_protection/password_protection_request.cc
@@ -7,12 +7,14 @@ #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "components/data_use_measurement/core/data_use_user_data.h" +#include "components/password_manager/core/browser/password_reuse_detector.h" #include "content/public/browser/web_contents.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" +#include "url/origin.h" using content::BrowserThread; using content::WebContents; @@ -124,7 +126,10 @@ break; } case LoginReputationClientRequest::PASSWORD_REUSE_EVENT: { - // TODO(jialiul): Fill more password reuse related information when ready. + LoginReputationClientRequest::PasswordReuseEvent* reuse_event = + request_proto_->mutable_password_reuse_event(); + reuse_event->set_is_chrome_signin_password( + saved_domain_ == std::string(password_manager::kSyncPasswordDomain)); break; } default:
diff --git a/components/safe_browsing/password_protection/password_protection_service_unittest.cc b/components/safe_browsing/password_protection/password_protection_service_unittest.cc index 6169728..78d638d5 100644 --- a/components/safe_browsing/password_protection/password_protection_service_unittest.cc +++ b/components/safe_browsing/password_protection/password_protection_service_unittest.cc
@@ -10,6 +10,7 @@ #include "base/test/histogram_tester.h" #include "base/test/null_task_runner.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/password_manager/core/browser/password_reuse_detector.h" #include "components/safe_browsing/password_protection/password_protection_request.h" #include "components/safe_browsing_db/test_database_manager.h" #include "components/sync_preferences/testing_pref_service_syncable.h" @@ -176,14 +177,15 @@ request_->Start(); } - void InitializeAndStartPasswordEntryRequest(bool match_whitelist, + void InitializeAndStartPasswordEntryRequest(const std::string& saved_domain, + bool match_whitelist, int timeout_in_ms) { GURL target_url(kTargetUrl); EXPECT_CALL(*database_manager_.get(), MatchCsdWhitelistUrl(target_url)) .WillRepeatedly(testing::Return(match_whitelist)); request_ = new PasswordProtectionRequest( - nullptr, target_url, GURL(), GURL(), std::string(kSavedDomain), + nullptr, target_url, GURL(), GURL(), saved_domain, LoginReputationClientRequest::PASSWORD_REUSE_EVENT, password_protection_service_.get(), timeout_in_ms); request_->Start(); @@ -627,8 +629,7 @@ EXPECT_EQ(kFormActionUrl, actual_request->frames(1).forms(0).action_url()); } -TEST_F(PasswordProtectionServiceTest, - VerifyProtectedPasswordEntryRequestProto) { +TEST_F(PasswordProtectionServiceTest, VerifyPasswordProtectionRequestProto) { // Set up valid response. net::TestURLFetcher fetcher(0, GURL("http://bar.com"), nullptr); fetcher.set_status( @@ -637,8 +638,10 @@ LoginReputationClientResponse expected_response = CreateVerdictProto( LoginReputationClientResponse::PHISHING, 600, GURL(kTargetUrl).host()); fetcher.SetResponseString(expected_response.SerializeAsString()); - InitializeAndStartPasswordEntryRequest(false /* match whitelist */, - 100000 /* timeout in ms*/); + // Initialize request triggered by chrome sync password reuse. + InitializeAndStartPasswordEntryRequest( + std::string(password_manager::kSyncPasswordDomain), + false /* match whitelist */, 100000 /* timeout in ms*/); base::RunLoop().RunUntilIdle(); request_->OnURLFetchComplete(&fetcher); base::RunLoop().RunUntilIdle(); @@ -650,8 +653,22 @@ actual_request->trigger_type()); EXPECT_EQ(1, actual_request->frames_size()); EXPECT_EQ(kTargetUrl, actual_request->frames(0).url()); - // TODO(jialiul): Update this test when we're ready to fill more fields. - ASSERT_FALSE(actual_request->has_password_reuse_event()); + ASSERT_TRUE(actual_request->has_password_reuse_event()); + ASSERT_TRUE( + actual_request->password_reuse_event().is_chrome_signin_password()); + + // Initialize request triggered by saved password reuse. + InitializeAndStartPasswordEntryRequest(std::string(kSavedDomain), + false /* match whitelist */, + 100000 /* timeout in ms*/); + base::RunLoop().RunUntilIdle(); + request_->OnURLFetchComplete(&fetcher); + base::RunLoop().RunUntilIdle(); + + actual_request = password_protection_service_->GetLatestRequestProto(); + ASSERT_TRUE(actual_request->has_password_reuse_event()); + ASSERT_FALSE( + actual_request->password_reuse_event().is_chrome_signin_password()); } } // namespace safe_browsing
diff --git a/components/storage_monitor/image_capture_device.h b/components/storage_monitor/image_capture_device.h index 55dc1fe5..15246efd 100644 --- a/components/storage_monitor/image_capture_device.h +++ b/components/storage_monitor/image_capture_device.h
@@ -10,7 +10,6 @@ #include "base/files/file.h" #include "base/files/file_path.h" -#include "base/mac/cocoa_protocols.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/memory/ref_counted.h"
diff --git a/components/update_client/background_downloader_win.cc b/components/update_client/background_downloader_win.cc index 2c3766f..dcbcd64 100644 --- a/components/update_client/background_downloader_win.cc +++ b/components/update_client/background_downloader_win.cc
@@ -448,10 +448,6 @@ base::Bind(&BackgroundDownloader::OnDownloading, base::Unretained(this))); } -bool BackgroundDownloader::TimerIsRunning() const { - return timer_.get() && timer_->IsRunning(); -} - void BackgroundDownloader::DoStartDownload(const GURL& url) { DCHECK(thread_checker_.CalledOnValidThread()); task_runner()->PostTask(FROM_HERE, @@ -574,8 +570,6 @@ void BackgroundDownloader::EndDownload(HRESULT error) { DCHECK(task_runner()->RunsTasksOnCurrentThread()); - DCHECK(!TimerIsRunning()); - const base::TimeTicks download_end_time(base::TimeTicks::Now()); const base::TimeDelta download_time = download_end_time >= download_start_time_ @@ -621,9 +615,8 @@ base::Unretained(this), is_handled, result, download_metrics)); // Once the task is posted to the the main thread, this object may be deleted - // by its owner. It is not safe to access members of this object on the - // task runner from this point on. The timer is stopped and all BITS - // interface pointers have been released. + // by its owner. It is not safe to access members of this object on this task + // runner from now on. } // Called when the BITS job has been transferred successfully. Completes the
diff --git a/components/update_client/background_downloader_win.h b/components/update_client/background_downloader_win.h index cf90d18..52ed1e25 100644 --- a/components/update_client/background_downloader_win.h +++ b/components/update_client/background_downloader_win.h
@@ -87,10 +87,6 @@ void StartTimer(); void OnTimer(); - // Returns true if the timer is running or false if the timer is not - // created or not running at all. - bool TimerIsRunning() const; - HRESULT QueueBitsJob(const GURL& url, IBackgroundCopyJob** job); HRESULT CreateOrOpenJob(const GURL& url, IBackgroundCopyJob** job); HRESULT InitializeNewJob(
diff --git a/components/variations/BUILD.gn b/components/variations/BUILD.gn index 51bb6448..c2d2eea 100644 --- a/components/variations/BUILD.gn +++ b/components/variations/BUILD.gn
@@ -20,6 +20,8 @@ "caching_permuted_entropy_provider.h", "child_process_field_trial_syncer.cc", "child_process_field_trial_syncer.h", + "client_filterable_state.cc", + "client_filterable_state.h", "entropy_provider.cc", "entropy_provider.h", "experiment_labels.cc",
diff --git a/components/variations/client_filterable_state.cc b/components/variations/client_filterable_state.cc new file mode 100644 index 0000000..0e36db82 --- /dev/null +++ b/components/variations/client_filterable_state.cc
@@ -0,0 +1,35 @@ +// 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 "components/variations/client_filterable_state.h" + +#include "build/build_config.h" + +namespace variations { + +// static +Study::Platform ClientFilterableState::GetCurrentPlatform() { +#if defined(OS_WIN) + return Study::PLATFORM_WINDOWS; +#elif defined(OS_IOS) + return Study::PLATFORM_IOS; +#elif defined(OS_MACOSX) + return Study::PLATFORM_MAC; +#elif defined(OS_CHROMEOS) + return Study::PLATFORM_CHROMEOS; +#elif defined(OS_ANDROID) + return Study::PLATFORM_ANDROID; +#elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS) + // Default BSD and SOLARIS to Linux to not break those builds, although these + // platforms are not officially supported by Chrome. + return Study::PLATFORM_LINUX; +#else +#error Unknown platform +#endif +} + +ClientFilterableState::ClientFilterableState() {} +ClientFilterableState::~ClientFilterableState() {} + +} // namespace variations
diff --git a/components/variations/client_filterable_state.h b/components/variations/client_filterable_state.h new file mode 100644 index 0000000..c2671f37 --- /dev/null +++ b/components/variations/client_filterable_state.h
@@ -0,0 +1,56 @@ +// 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 COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_ +#define COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_ + +#include "base/macros.h" +#include "base/time/time.h" +#include "base/version.h" +#include "components/variations/proto/study.pb.h" + +namespace variations { + +// A contianer for all of the client state which is used for filtering studies. +struct ClientFilterableState { + static Study::Platform GetCurrentPlatform(); + + ClientFilterableState(); + ~ClientFilterableState(); + + // The system locale. + std::string locale; + + // The date on which the variations seed was fetched. + base::Time reference_date; + + // The Chrome version to filter on. + base::Version version; + + // The Channel for this Chrome installation. + Study::Channel channel; + + // The hardware form factor that Chrome is running on. + Study::FormFactor form_factor; + + // The OS on which Chrome is running. + Study::Platform platform; + + // The named hardware configuration that Chrome is running on -- used to + // identify models of devices. + std::string hardware_class; + + // The country code to use for studies configured with session consistency. + std::string session_consistency_country; + + // The country code to use for studies configured with permanent consistency. + std::string permanent_consistency_country; + + private: + DISALLOW_COPY_AND_ASSIGN(ClientFilterableState); +}; + +} // namespace variations + +#endif // COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_
diff --git a/components/variations/service/variations_service.cc b/components/variations/service/variations_service.cc index 749a6dd5..fb594ac 100644 --- a/components/variations/service/variations_service.cc +++ b/components/variations/service/variations_service.cc
@@ -18,6 +18,7 @@ #include "base/strings/string_util.h" #include "base/sys_info.h" #include "base/task_runner_util.h" +#include "base/task_scheduler/post_task.h" #include "base/threading/sequenced_worker_pool.h" #include "base/timer/elapsed_timer.h" #include "base/values.h" @@ -333,22 +334,18 @@ if (!current_version.IsValid()) return false; - variations::Study_Channel channel = - GetChannelForVariations(client_->GetChannel()); - UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.UserChannel", channel); + std::unique_ptr<ClientFilterableState> client_state = + GetClientFilterableStateForVersion(current_version); + UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.UserChannel", client_state->channel); - const std::string latest_country = GetLatestCountry(); std::unique_ptr<const base::FieldTrial::EntropyProvider> low_entropy_provider( CreateLowEntropyProvider()); // Note that passing |&ui_string_overrider_| via base::Unretained below is // safe because the callback is executed synchronously. It is not possible - // to pass UIStringOverrider itself to VariationSeedProcesor as variations + // to pass UIStringOverrider itself to VariationSeedProcessor as variations // components should not depends on //ui/base. variations::VariationsSeedProcessor().CreateTrialsFromSeed( - seed, client_->GetApplicationLocale(), - GetReferenceDateForExpiryChecks(local_state_), current_version, channel, - GetCurrentFormFactor(), GetHardwareClass(), latest_country, - LoadPermanentConsistencyCountry(current_version, latest_country), + seed, *client_state, base::Bind(&UIStringOverrider::OverrideUIString, base::Unretained(&ui_string_overrider_)), low_entropy_provider.get(), feature_list); @@ -609,8 +606,8 @@ if (!state_manager_) return true; - base::PostTaskAndReplyWithResult( - client_->GetBlockingPool(), FROM_HERE, + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, client_->GetVersionForSimulationCallback(), base::Bind(&VariationsService::PerformSimulationWithVersion, weak_ptr_factory_.GetWeakPtr(), base::Passed(&seed))); @@ -626,6 +623,24 @@ return seed_store_.LoadSeed(seed); } +std::unique_ptr<ClientFilterableState> +VariationsService::GetClientFilterableStateForVersion( + const base::Version& version) { + std::unique_ptr<ClientFilterableState> state = + base::MakeUnique<ClientFilterableState>(); + state->locale = client_->GetApplicationLocale(); + state->reference_date = GetReferenceDateForExpiryChecks(local_state_); + state->version = version; + state->channel = GetChannelForVariations(client_->GetChannel()); + state->form_factor = GetCurrentFormFactor(); + state->platform = ClientFilterableState::GetCurrentPlatform(); + state->hardware_class = GetHardwareClass(); + state->session_consistency_country = GetLatestCountry(); + state->permanent_consistency_country = LoadPermanentConsistencyCountry( + version, state->session_consistency_country); + return state; +} + void VariationsService::FetchVariationsSeed() { DCHECK(thread_checker_.CalledOnValidThread()); @@ -770,14 +785,10 @@ variations::VariationsSeedSimulator seed_simulator(*default_provider, *low_provider); - const std::string latest_country = GetLatestCountry(); - const variations::VariationsSeedSimulator::Result result = - seed_simulator.SimulateSeedStudies( - *seed, client_->GetApplicationLocale(), - GetReferenceDateForExpiryChecks(local_state_), version, - GetChannelForVariations(client_->GetChannel()), - GetCurrentFormFactor(), GetHardwareClass(), latest_country, - LoadPermanentConsistencyCountry(version, latest_country)); + std::unique_ptr<ClientFilterableState> client_state = + GetClientFilterableStateForVersion(version); + const VariationsSeedSimulator::Result result = + seed_simulator.SimulateSeedStudies(*seed, *client_state); UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.NormalChanges", result.normal_group_change_count);
diff --git a/components/variations/service/variations_service.h b/components/variations/service/variations_service.h index 6e7033b..fdc7dad7 100644 --- a/components/variations/service/variations_service.h +++ b/components/variations/service/variations_service.h
@@ -16,6 +16,7 @@ #include "base/observer_list.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" +#include "components/variations/client_filterable_state.h" #include "components/variations/service/ui_string_overrider.h" #include "components/variations/service/variations_service_client.h" #include "components/variations/variations_request_scheduler.h" @@ -236,6 +237,11 @@ // so that it can be overridden by tests. virtual bool LoadSeed(VariationsSeed* seed); + // Returns all of the client state used for filtering studies. + // As a side-effect, may update the stored permanent consistency country. + std::unique_ptr<ClientFilterableState> GetClientFilterableStateForVersion( + const base::Version& version); + // Sets the stored permanent country pref for this client. void StorePermanentCountry(const base::Version& version, const std::string& country);
diff --git a/components/variations/service/variations_service_client.h b/components/variations/service/variations_service_client.h index 89a27c1..c9a269b3 100644 --- a/components/variations/service/variations_service_client.h +++ b/components/variations/service/variations_service_client.h
@@ -12,10 +12,6 @@ #include "base/version.h" #include "components/version_info/version_info.h" -namespace base { -class SequencedWorkerPool; -} - namespace net { class URLRequestContextGetter; } @@ -35,14 +31,9 @@ // Returns the current application locale (e.g. "en-US"). virtual std::string GetApplicationLocale() = 0; - // Returns the SequencedWorkerPool on which the VariationsService should run - // tasks that may block. - virtual base::SequencedWorkerPool* GetBlockingPool() = 0; - // Returns a callback that when run returns the base::Version to use for // variations seed simulation. VariationsService guarantees that the callback - // will be run on the pool returned by - // VariationsServiceClient::GetBlockingPool(). + // will be run on a background threadt that permits blocking. virtual base::Callback<base::Version(void)> GetVersionForSimulationCallback() = 0;
diff --git a/components/variations/service/variations_service_unittest.cc b/components/variations/service/variations_service_unittest.cc index a0515f08..9f3217f 100644 --- a/components/variations/service/variations_service_unittest.cc +++ b/components/variations/service/variations_service_unittest.cc
@@ -44,7 +44,6 @@ // variations::VariationsServiceClient: std::string GetApplicationLocale() override { return std::string(); } - base::SequencedWorkerPool* GetBlockingPool() override { return nullptr; } base::Callback<base::Version(void)> GetVersionForSimulationCallback() override { return base::Callback<base::Version(void)>();
diff --git a/components/variations/study_filtering.cc b/components/variations/study_filtering.cc index 0712c206..e7ccd25 100644 --- a/components/variations/study_filtering.cc +++ b/components/variations/study_filtering.cc
@@ -10,32 +10,12 @@ #include <set> #include "base/stl_util.h" -#include "build/build_config.h" +#include "base/strings/string_util.h" +#include "components/variations/client_filterable_state.h" namespace variations { - namespace { -Study_Platform GetCurrentPlatform() { -#if defined(OS_WIN) - return Study_Platform_PLATFORM_WINDOWS; -#elif defined(OS_IOS) - return Study_Platform_PLATFORM_IOS; -#elif defined(OS_MACOSX) - return Study_Platform_PLATFORM_MAC; -#elif defined(OS_CHROMEOS) - return Study_Platform_PLATFORM_CHROMEOS; -#elif defined(OS_ANDROID) - return Study_Platform_PLATFORM_ANDROID; -#elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS) - // Default BSD and SOLARIS to Linux to not break those builds, although these - // platforms are not officially supported by Chrome. - return Study_Platform_PLATFORM_LINUX; -#else -#error Unknown platform -#endif -} - // Converts |date_time| in Study date format to base::Time. base::Time ConvertStudyDateToBaseTime(int64_t date_time) { return base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(date_time); @@ -45,7 +25,7 @@ namespace internal { -bool CheckStudyChannel(const Study_Filter& filter, Study_Channel channel) { +bool CheckStudyChannel(const Study::Filter& filter, Study::Channel channel) { // An empty channel list matches all channels. if (filter.channel_size() == 0) return true; @@ -57,8 +37,8 @@ return false; } -bool CheckStudyFormFactor(const Study_Filter& filter, - Study_FormFactor form_factor) { +bool CheckStudyFormFactor(const Study::Filter& filter, + Study::FormFactor form_factor) { // Empty whitelist and blacklist signifies matching any form factor. if (filter.form_factor_size() == 0 && filter.exclude_form_factor_size() == 0) return true; @@ -74,7 +54,7 @@ return !base::ContainsValue(filter.exclude_form_factor(), form_factor); } -bool CheckStudyHardwareClass(const Study_Filter& filter, +bool CheckStudyHardwareClass(const Study::Filter& filter, const std::string& hardware_class) { // Empty hardware_class and exclude_hardware_class matches all. if (filter.hardware_class_size() == 0 && @@ -109,7 +89,7 @@ return true; } -bool CheckStudyLocale(const Study_Filter& filter, const std::string& locale) { +bool CheckStudyLocale(const Study::Filter& filter, const std::string& locale) { // Empty locale and exclude_locale lists matches all locales. if (filter.locale_size() == 0 && filter.exclude_locale_size() == 0) return true; @@ -124,7 +104,7 @@ return !base::ContainsValue(filter.exclude_locale(), locale); } -bool CheckStudyPlatform(const Study_Filter& filter, Study_Platform platform) { +bool CheckStudyPlatform(const Study::Filter& filter, Study::Platform platform) { // An empty platform list matches all platforms. if (filter.platform_size() == 0) return true; @@ -136,7 +116,7 @@ return false; } -bool CheckStudyStartDate(const Study_Filter& filter, +bool CheckStudyStartDate(const Study::Filter& filter, const base::Time& date_time) { if (filter.has_start_date()) { const base::Time start_date = @@ -147,7 +127,7 @@ return true; } -bool CheckStudyEndDate(const Study_Filter& filter, +bool CheckStudyEndDate(const Study::Filter& filter, const base::Time& date_time) { if (filter.has_end_date()) { const base::Time end_date = ConvertStudyDateToBaseTime(filter.end_date()); @@ -157,7 +137,7 @@ return true; } -bool CheckStudyVersion(const Study_Filter& filter, +bool CheckStudyVersion(const Study::Filter& filter, const base::Version& version) { if (filter.has_min_version()) { if (version.CompareToWildcardString(filter.min_version()) < 0) @@ -172,7 +152,8 @@ return true; } -bool CheckStudyCountry(const Study_Filter& filter, const std::string& country) { +bool CheckStudyCountry(const Study::Filter& filter, + const std::string& country) { // Empty country and exclude_country matches all. if (filter.country_size() == 0 && filter.exclude_country_size() == 0) return true; @@ -187,6 +168,27 @@ return !base::ContainsValue(filter.exclude_country(), country); } +const std::string& GetClientCountryForStudy( + const Study& study, + const ClientFilterableState& client_state) { + switch (study.consistency()) { + case Study::SESSION: + return client_state.session_consistency_country; + case Study::PERMANENT: + // Use the saved country for permanent consistency studies. This allows + // Chrome to use the same country for filtering permanent consistency + // studies between Chrome upgrades. Since some studies have user-visible + // effects, this helps to avoid annoying users with experimental group + // churn while traveling. + return client_state.permanent_consistency_country; + } + + // Unless otherwise specified, use an empty country that won't pass any + // filters that specifically include countries, but will pass any filters + // that specifically exclude countries. + return base::EmptyString(); +} + bool IsStudyExpired(const Study& study, const base::Time& date_time) { if (study.has_expiry_date()) { const base::Time expiry_date = @@ -197,59 +199,53 @@ return false; } -bool ShouldAddStudy( - const Study& study, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& country) { +bool ShouldAddStudy(const Study& study, + const ClientFilterableState& client_state) { if (study.has_filter()) { - if (!CheckStudyChannel(study.filter(), channel)) { + if (!CheckStudyChannel(study.filter(), client_state.channel)) { DVLOG(1) << "Filtered out study " << study.name() << " due to channel."; return false; } - if (!CheckStudyFormFactor(study.filter(), form_factor)) { + if (!CheckStudyFormFactor(study.filter(), client_state.form_factor)) { DVLOG(1) << "Filtered out study " << study.name() << " due to form factor."; return false; } - if (!CheckStudyLocale(study.filter(), locale)) { + if (!CheckStudyLocale(study.filter(), client_state.locale)) { DVLOG(1) << "Filtered out study " << study.name() << " due to locale."; return false; } - if (!CheckStudyPlatform(study.filter(), GetCurrentPlatform())) { + if (!CheckStudyPlatform(study.filter(), client_state.platform)) { DVLOG(1) << "Filtered out study " << study.name() << " due to platform."; return false; } - if (!CheckStudyVersion(study.filter(), version)) { + if (!CheckStudyVersion(study.filter(), client_state.version)) { DVLOG(1) << "Filtered out study " << study.name() << " due to version."; return false; } - if (!CheckStudyStartDate(study.filter(), reference_date)) { + if (!CheckStudyStartDate(study.filter(), client_state.reference_date)) { DVLOG(1) << "Filtered out study " << study.name() << " due to start date."; return false; } - if (!CheckStudyEndDate(study.filter(), reference_date)) { + if (!CheckStudyEndDate(study.filter(), client_state.reference_date)) { DVLOG(1) << "Filtered out study " << study.name() << " due to end date."; return false; } - if (!CheckStudyHardwareClass(study.filter(), hardware_class)) { + if (!CheckStudyHardwareClass(study.filter(), client_state.hardware_class)) { DVLOG(1) << "Filtered out study " << study.name() << " due to hardware_class."; return false; } + const std::string& country = GetClientCountryForStudy(study, client_state); if (!CheckStudyCountry(study.filter(), country)) { DVLOG(1) << "Filtered out study " << study.name() << " due to country."; return false; @@ -263,16 +259,9 @@ } // namespace internal void FilterAndValidateStudies(const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country, + const ClientFilterableState& client_state, std::vector<ProcessedStudy>* filtered_studies) { - DCHECK(version.IsValid()); + DCHECK(client_state.version.IsValid()); // Add expired studies (in a disabled state) only after all the non-expired // studies have been added (and do not add an expired study if a corresponding @@ -283,32 +272,10 @@ for (int i = 0; i < seed.study_size(); ++i) { const Study& study = seed.study(i); - - // Unless otherwise specified, use an empty country that won't pass any - // filters that specifically include countries, but will pass any filters - // that specifically exclude countries. - std::string country; - switch (study.consistency()) { - case Study_Consistency_SESSION: - country = session_consistency_country; - break; - case Study_Consistency_PERMANENT: - // Use the saved |permanent_consistency_country| for permanent - // consistency studies. This allows Chrome to use the same country for - // filtering permanent consistency studies between Chrome upgrades. - // Since some studies have user-visible effects, this helps to avoid - // annoying users with experimental group churn while traveling. - country = permanent_consistency_country; - break; - } - - if (!internal::ShouldAddStudy(study, locale, reference_date, version, - channel, form_factor, hardware_class, - country)) { + if (!internal::ShouldAddStudy(study, client_state)) continue; - } - if (internal::IsStudyExpired(study, reference_date)) { + if (internal::IsStudyExpired(study, client_state.reference_date)) { expired_studies.push_back(&study); } else if (!base::ContainsKey(created_studies, study.name())) { ProcessedStudy::ValidateAndAppendStudy(&study, false, filtered_studies);
diff --git a/components/variations/study_filtering.h b/components/variations/study_filtering.h index 9917ec7..a5667cd 100644 --- a/components/variations/study_filtering.h +++ b/components/variations/study_filtering.h
@@ -17,70 +17,67 @@ namespace variations { +struct ClientFilterableState; + // Internal functions exposed for testing purposes only. namespace internal { // Checks whether a study is applicable for the given |channel| per |filter|. -bool CheckStudyChannel(const Study_Filter& filter, Study_Channel channel); +bool CheckStudyChannel(const Study::Filter& filter, Study::Channel channel); // Checks whether a study is applicable for the given |form_factor| per // |filter|. -bool CheckStudyFormFactor(const Study_Filter& filter, - Study_FormFactor form_factor); +bool CheckStudyFormFactor(const Study::Filter& filter, + Study::FormFactor form_factor); // Checks whether a study is applicable for the given |hardware_class| per // |filter|. -bool CheckStudyHardwareClass(const Study_Filter& filter, +bool CheckStudyHardwareClass(const Study::Filter& filter, const std::string& hardware_class); // Checks whether a study is applicable for the given |locale| per |filter|. -bool CheckStudyLocale(const Study_Filter& filter, const std::string& locale); +bool CheckStudyLocale(const Study::Filter& filter, const std::string& locale); // Checks whether a study is applicable for the given |platform| per |filter|. -bool CheckStudyPlatform(const Study_Filter& filter, Study_Platform platform); +bool CheckStudyPlatform(const Study::Filter& filter, Study::Platform platform); // Checks whether a study is applicable for the given date/time per |filter|. -bool CheckStudyStartDate(const Study_Filter& filter, +bool CheckStudyStartDate(const Study::Filter& filter, const base::Time& date_time); // Checks whether a study is applicable for the given date/time per |filter|. -bool CheckStudyEndDate(const Study_Filter& filter, const base::Time& date_time); +bool CheckStudyEndDate(const Study::Filter& filter, + const base::Time& date_time); // Checks whether a study is applicable for the given version per |filter|. -bool CheckStudyVersion(const Study_Filter& filter, +bool CheckStudyVersion(const Study::Filter& filter, const base::Version& version); // Checks whether a study is applicable for the given |country| per |filter|. -bool CheckStudyCountry(const Study_Filter& filter, const std::string& country); +bool CheckStudyCountry(const Study::Filter& filter, const std::string& country); + +// Returns the country that should be used for filtering this study, depending +// on whether the study has session or permanent consistency. +const std::string& GetClientCountryForStudy( + const Study& study, + const ClientFilterableState& client_state); // Checks whether |study| is expired using the given date/time. bool IsStudyExpired(const Study& study, const base::Time& date_time); -// Returns whether |study| should be disabled according to its restriction -// parameters. +// Returns whether |study| should be disabled according to the restriction +// parameters in the |config|. bool ShouldAddStudy(const Study& study, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& country); + const ClientFilterableState& client_state); } // namespace internal -// Filters the list of studies in |seed| and validates and pre-processes them, -// adding any kept studies to |filtered_studies| list. Ensures that the -// resulting list will not have more than one study with the same name. +// Filters the list of studies in |seed| according ot the |client_state|, and +// validates and pre-processes them, adding any kept studies to the +// |filtered_studies| list. Ensures that the resulting list will not have more +// than one study with the same name. void FilterAndValidateStudies(const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country, + const ClientFilterableState& client_state, std::vector<ProcessedStudy>* filtered_studies); } // namespace variations
diff --git a/components/variations/study_filtering_unittest.cc b/components/variations/study_filtering_unittest.cc index 14f4f08..7572118 100644 --- a/components/variations/study_filtering_unittest.cc +++ b/components/variations/study_filtering_unittest.cc
@@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/strings/string_split.h" +#include "components/variations/client_filterable_state.h" #include "components/variations/processed_study.h" #include "testing/gtest/include/gtest/gtest.h" @@ -25,9 +26,10 @@ } // Adds an experiment to |study| with the specified |name| and |probability|. -Study_Experiment* AddExperiment(const std::string& name, int probability, - Study* study) { - Study_Experiment* experiment = study->add_experiment(); +Study::Experiment* AddExperiment(const std::string& name, + int probability, + Study* study) { + Study::Experiment* experiment = study->add_experiment(); experiment->set_name(name); experiment->set_probability_weight(probability); return experiment; @@ -36,15 +38,12 @@ } // namespace TEST(VariationsStudyFilteringTest, CheckStudyChannel) { - const Study_Channel channels[] = { - Study_Channel_CANARY, - Study_Channel_DEV, - Study_Channel_BETA, - Study_Channel_STABLE, + const Study::Channel channels[] = { + Study::CANARY, Study::DEV, Study::BETA, Study::STABLE, }; bool channel_added[arraysize(channels)] = { 0 }; - Study_Filter filter; + Study::Filter filter; // Check in the forwarded order. The loop cond is <= arraysize(channels) // instead of < so that the result of adding the last channel gets checked. @@ -80,18 +79,15 @@ } TEST(VariationsStudyFilteringTest, CheckStudyFormFactor) { - const Study_FormFactor form_factors[] = { - Study_FormFactor_DESKTOP, - Study_FormFactor_PHONE, - Study_FormFactor_TABLET, - Study_FormFactor_KIOSK, + const Study::FormFactor form_factors[] = { + Study::DESKTOP, Study::PHONE, Study::TABLET, Study::KIOSK, }; - ASSERT_EQ(Study_FormFactor_FormFactor_ARRAYSIZE, + ASSERT_EQ(Study::FormFactor_ARRAYSIZE, static_cast<int>(arraysize(form_factors))); bool form_factor_added[arraysize(form_factors)] = { 0 }; - Study_Filter filter; + Study::Filter filter; for (size_t i = 0; i <= arraysize(form_factors); ++i) { for (size_t j = 0; j < arraysize(form_factors); ++j) { @@ -196,7 +192,7 @@ }; for (size_t i = 0; i < arraysize(test_cases); ++i) { - Study_Filter filter; + Study::Filter filter; for (const std::string& locale : base::SplitString( test_cases[i].filter_locales, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) @@ -215,19 +211,14 @@ } TEST(VariationsStudyFilteringTest, CheckStudyPlatform) { - const Study_Platform platforms[] = { - Study_Platform_PLATFORM_WINDOWS, - Study_Platform_PLATFORM_MAC, - Study_Platform_PLATFORM_LINUX, - Study_Platform_PLATFORM_CHROMEOS, - Study_Platform_PLATFORM_ANDROID, - Study_Platform_PLATFORM_IOS, + const Study::Platform platforms[] = { + Study::PLATFORM_WINDOWS, Study::PLATFORM_MAC, Study::PLATFORM_LINUX, + Study::PLATFORM_CHROMEOS, Study::PLATFORM_ANDROID, Study::PLATFORM_IOS, }; - ASSERT_EQ(Study_Platform_Platform_ARRAYSIZE, - static_cast<int>(arraysize(platforms))); + ASSERT_EQ(Study::Platform_ARRAYSIZE, static_cast<int>(arraysize(platforms))); bool platform_added[arraysize(platforms)] = { 0 }; - Study_Filter filter; + Study::Filter filter; // Check in the forwarded order. The loop cond is <= arraysize(platforms) // instead of < so that the result of adding the last channel gets checked. @@ -276,7 +267,7 @@ {now + delta, false}, }; - Study_Filter filter; + Study::Filter filter; // Start date not set should result in true. EXPECT_TRUE(internal::CheckStudyStartDate(filter, now)); @@ -299,7 +290,7 @@ {now - delta, false}, {now + delta, true}, }; - Study_Filter filter; + Study::Filter filter; // End date not set should result in true. EXPECT_TRUE(internal::CheckStudyEndDate(filter, now)); @@ -354,7 +345,7 @@ { "1.*", "2.3.4", false }, }; - Study_Filter filter; + Study::Filter filter; // Min/max version not set should result in true. EXPECT_TRUE(internal::CheckStudyVersion(filter, base::Version("1.2.3"))); @@ -438,7 +429,7 @@ }; for (size_t i = 0; i < arraysize(test_cases); ++i) { - Study_Filter filter; + Study::Filter filter; for (const std::string& cur : base::SplitString( test_cases[i].hardware_class, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) @@ -488,7 +479,7 @@ }; for (const auto& test : test_cases) { - Study_Filter filter; + Study::Filter filter; for (const std::string& country : base::SplitString( test.country, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) filter.add_country(country); @@ -526,11 +517,16 @@ AddExperiment("A", 10, study3); AddExperiment("Default", 25, study3); + ClientFilterableState client_state; + client_state.locale = "en-CA"; + client_state.reference_date = base::Time::Now(); + client_state.version = base::Version("20.0.0.0"); + client_state.channel = Study::STABLE; + client_state.form_factor = Study::DESKTOP; + client_state.platform = Study::PLATFORM_ANDROID; + std::vector<ProcessedStudy> processed_studies; - FilterAndValidateStudies(seed, "en-CA", base::Time::Now(), - base::Version("20.0.0.0"), Study_Channel_STABLE, - Study_FormFactor_DESKTOP, "", "", "", - &processed_studies); + FilterAndValidateStudies(seed, client_state, &processed_studies); // Check that only the first kTrial1Name study was kept. ASSERT_EQ(2U, processed_studies.size()); @@ -544,27 +540,27 @@ const char kPermanentCountry[] = "us"; struct { - Study_Consistency consistency; + Study::Consistency consistency; const char* filter_country; const char* filter_exclude_country; bool expect_study_kept; } test_cases[] = { // Country-agnostic studies should be kept regardless of country. - {Study_Consistency_SESSION, nullptr, nullptr, true}, - {Study_Consistency_PERMANENT, nullptr, nullptr, true}, + {Study::SESSION, nullptr, nullptr, true}, + {Study::PERMANENT, nullptr, nullptr, true}, // Session-consistency studies should obey the country code in the seed. - {Study_Consistency_SESSION, kSessionCountry, nullptr, true}, - {Study_Consistency_SESSION, nullptr, kSessionCountry, false}, - {Study_Consistency_SESSION, kPermanentCountry, nullptr, false}, - {Study_Consistency_SESSION, nullptr, kPermanentCountry, true}, + {Study::SESSION, kSessionCountry, nullptr, true}, + {Study::SESSION, nullptr, kSessionCountry, false}, + {Study::SESSION, kPermanentCountry, nullptr, false}, + {Study::SESSION, nullptr, kPermanentCountry, true}, // Permanent-consistency studies should obey the permanent-consistency // country code. - {Study_Consistency_PERMANENT, kPermanentCountry, nullptr, true}, - {Study_Consistency_PERMANENT, nullptr, kPermanentCountry, false}, - {Study_Consistency_PERMANENT, kSessionCountry, nullptr, false}, - {Study_Consistency_PERMANENT, nullptr, kSessionCountry, true}, + {Study::PERMANENT, kPermanentCountry, nullptr, true}, + {Study::PERMANENT, nullptr, kPermanentCountry, false}, + {Study::PERMANENT, kSessionCountry, nullptr, false}, + {Study::PERMANENT, nullptr, kSessionCountry, true}, }; for (const auto& test : test_cases) { @@ -579,16 +575,45 @@ if (test.filter_exclude_country) study->mutable_filter()->add_exclude_country(test.filter_exclude_country); + ClientFilterableState client_state; + client_state.locale = "en-CA"; + client_state.reference_date = base::Time::Now(); + client_state.version = base::Version("20.0.0.0"); + client_state.channel = Study::STABLE; + client_state.form_factor = Study::DESKTOP; + client_state.platform = Study::PLATFORM_ANDROID; + client_state.session_consistency_country = kSessionCountry; + client_state.permanent_consistency_country = kPermanentCountry; + std::vector<ProcessedStudy> processed_studies; - FilterAndValidateStudies(seed, "en-CA", base::Time::Now(), - base::Version("20.0.0.0"), Study_Channel_STABLE, - Study_FormFactor_DESKTOP, "", kSessionCountry, - kPermanentCountry, &processed_studies); + FilterAndValidateStudies(seed, client_state, &processed_studies); EXPECT_EQ(test.expect_study_kept, !processed_studies.empty()); } } +TEST(VariationsStudyFilteringTest, GetClientCountryForStudy_Session) { + ClientFilterableState client_state; + client_state.session_consistency_country = "session_country"; + client_state.permanent_consistency_country = "permanent_country"; + + Study study; + study.set_consistency(Study::SESSION); + EXPECT_EQ("session_country", + internal::GetClientCountryForStudy(study, client_state)); +} + +TEST(VariationsStudyFilteringTest, GetClientCountryForStudy_Permanent) { + ClientFilterableState client_state; + client_state.session_consistency_country = "session_country"; + client_state.permanent_consistency_country = "permanent_country"; + + Study study; + study.set_consistency(Study::PERMANENT); + EXPECT_EQ("permanent_country", + internal::GetClientCountryForStudy(study, client_state)); +} + TEST(VariationsStudyFilteringTest, IsStudyExpired) { const base::Time now = base::Time::Now(); const base::TimeDelta delta = base::TimeDelta::FromHours(1); @@ -618,7 +643,7 @@ Study study; study.set_default_experiment_name("def"); AddExperiment("abc", 100, &study); - Study_Experiment* default_group = AddExperiment("def", 200, &study); + Study::Experiment* default_group = AddExperiment("def", 200, &study); ProcessedStudy processed_study; EXPECT_TRUE(processed_study.Init(&study, false)); @@ -653,7 +678,7 @@ default_group->set_name("def"); EXPECT_TRUE(processed_study.Init(&study, false)); - Study_Experiment* repeated_group = study.add_experiment(); + Study::Experiment* repeated_group = study.add_experiment(); repeated_group->set_name("abc"); repeated_group->set_probability_weight(1); EXPECT_FALSE(processed_study.Init(&study, false));
diff --git a/components/variations/variations_seed_processor.cc b/components/variations/variations_seed_processor.cc index c1bb22f..9ac9388f 100644 --- a/components/variations/variations_seed_processor.cc +++ b/components/variations/variations_seed_processor.cc
@@ -14,6 +14,7 @@ #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" +#include "components/variations/client_filterable_state.h" #include "components/variations/processed_study.h" #include "components/variations/study_filtering.h" #include "components/variations/variations_associated_data.h" @@ -175,26 +176,17 @@ void VariationsSeedProcessor::CreateTrialsFromSeed( const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country, + const ClientFilterableState& client_state, const UIStringOverrideCallback& override_callback, const base::FieldTrial::EntropyProvider* low_entropy_provider, base::FeatureList* feature_list) { std::vector<ProcessedStudy> filtered_studies; - FilterAndValidateStudies(seed, locale, reference_date, version, channel, - form_factor, hardware_class, - session_consistency_country, - permanent_consistency_country, &filtered_studies); + FilterAndValidateStudies(seed, client_state, &filtered_studies); - for (size_t i = 0; i < filtered_studies.size(); ++i) - CreateTrialFromStudy(filtered_studies[i], override_callback, - low_entropy_provider, feature_list); + for (const ProcessedStudy& study : filtered_studies) { + CreateTrialFromStudy(study, override_callback, low_entropy_provider, + feature_list); + } } // static
diff --git a/components/variations/variations_seed_processor.h b/components/variations/variations_seed_processor.h index bcb938a..140dc271 100644 --- a/components/variations/variations_seed_processor.h +++ b/components/variations/variations_seed_processor.h
@@ -28,6 +28,7 @@ namespace variations { class ProcessedStudy; +struct ClientFilterableState; // Helper class to instantiate field trials from a variations seed. class VariationsSeedProcessor { @@ -38,20 +39,13 @@ VariationsSeedProcessor(); virtual ~VariationsSeedProcessor(); - // Creates field trials from the specified variations |seed|, based on the - // specified configuration, as specified in the parameters. Any study that - // should use low entropy will use |low_entropy_provider| for group - // selection. These studies are defined by ShouldStudyUseLowEntropy; + // Creates field trials from the specified variations |seed|, filtered + // according to the client's |client_state|. Any study that should use low + // entropy will use |low_entropy_provider| for group selection. These studies + // are defined by ShouldStudyUseLowEntropy; void CreateTrialsFromSeed( const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country, + const ClientFilterableState& client_state, const UIStringOverrideCallback& override_callback, const base::FieldTrial::EntropyProvider* low_entropy_provider, base::FeatureList* feature_list);
diff --git a/components/variations/variations_seed_processor_unittest.cc b/components/variations/variations_seed_processor_unittest.cc index ef34a066..620c9da5 100644 --- a/components/variations/variations_seed_processor_unittest.cc +++ b/components/variations/variations_seed_processor_unittest.cc
@@ -23,6 +23,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/mock_entropy_provider.h" #include "base/test/scoped_feature_list.h" +#include "components/variations/client_filterable_state.h" #include "components/variations/processed_study.h" #include "components/variations/study_filtering.h" #include "components/variations/variations_associated_data.h" @@ -262,7 +263,13 @@ const base::Time year_ago = base::Time::Now() - base::TimeDelta::FromDays(365); - const base::Version version("20.0.0.0"); + ClientFilterableState client_state; + client_state.locale = "en-CA"; + client_state.reference_date = base::Time::Now(); + client_state.version = base::Version("20.0.0.0"); + client_state.channel = Study::STABLE; + client_state.form_factor = Study::DESKTOP; + client_state.platform = Study::PLATFORM_ANDROID; // Check that adding [expired, non-expired] activates the non-expired one. ASSERT_EQ(std::string(), base::FieldTrialList::FindFullName(kTrialName)); @@ -270,10 +277,9 @@ base::FeatureList feature_list; base::FieldTrialList field_trial_list(nullptr); study1->set_expiry_date(TimeToProtoTime(year_ago)); - seed_processor.CreateTrialsFromSeed( - seed, "en-CA", base::Time::Now(), version, Study_Channel_STABLE, - Study_FormFactor_DESKTOP, "", "", "", override_callback_.callback(), - nullptr, &feature_list); + seed_processor.CreateTrialsFromSeed(seed, client_state, + override_callback_.callback(), nullptr, + &feature_list); EXPECT_EQ(kGroup1Name, base::FieldTrialList::FindFullName(kTrialName)); } @@ -284,10 +290,9 @@ base::FieldTrialList field_trial_list(nullptr); study1->clear_expiry_date(); study2->set_expiry_date(TimeToProtoTime(year_ago)); - seed_processor.CreateTrialsFromSeed( - seed, "en-CA", base::Time::Now(), version, Study_Channel_STABLE, - Study_FormFactor_DESKTOP, "", "", "", override_callback_.callback(), - nullptr, &feature_list); + seed_processor.CreateTrialsFromSeed(seed, client_state, + override_callback_.callback(), nullptr, + &feature_list); EXPECT_EQ(kGroup1Name, base::FieldTrialList::FindFullName(kTrialName)); } } @@ -532,11 +537,18 @@ AddExperiment("Default", 0, study3); study3->set_activation_type(Study_ActivationType_ACTIVATION_EXPLICIT); + ClientFilterableState client_state; + client_state.locale = "en-CA"; + client_state.reference_date = base::Time::Now(); + client_state.version = base::Version("20.0.0.0"); + client_state.channel = Study::STABLE; + client_state.form_factor = Study::DESKTOP; + client_state.platform = Study::PLATFORM_ANDROID; + VariationsSeedProcessor seed_processor; - seed_processor.CreateTrialsFromSeed( - seed, "en-CA", base::Time::Now(), base::Version("20.0.0.0"), - Study_Channel_STABLE, Study_FormFactor_DESKTOP, "", "", "", - override_callback_.callback(), nullptr, &feature_list_); + seed_processor.CreateTrialsFromSeed(seed, client_state, + override_callback_.callback(), nullptr, + &feature_list_); // Non-specified and ACTIVATION_EXPLICIT should not start active, but // ACTIVATION_AUTO should.
diff --git a/components/variations/variations_seed_simulator.cc b/components/variations/variations_seed_simulator.cc index 59b56643..05f5f73e 100644 --- a/components/variations/variations_seed_simulator.cc +++ b/components/variations/variations_seed_simulator.cc
@@ -9,6 +9,7 @@ #include <map> #include "base/metrics/field_trial.h" +#include "components/variations/client_filterable_state.h" #include "components/variations/processed_study.h" #include "components/variations/proto/study.pb.h" #include "components/variations/study_filtering.h" @@ -114,19 +115,9 @@ VariationsSeedSimulator::Result VariationsSeedSimulator::SimulateSeedStudies( const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country) { + const ClientFilterableState& client_state) { std::vector<ProcessedStudy> filtered_studies; - FilterAndValidateStudies(seed, locale, reference_date, version, channel, - form_factor, hardware_class, - session_consistency_country, - permanent_consistency_country, &filtered_studies); + FilterAndValidateStudies(seed, client_state, &filtered_studies); return ComputeDifferences(filtered_studies); }
diff --git a/components/variations/variations_seed_simulator.h b/components/variations/variations_seed_simulator.h index c18e6c32..72986af 100644 --- a/components/variations/variations_seed_simulator.h +++ b/components/variations/variations_seed_simulator.h
@@ -18,6 +18,7 @@ namespace variations { class ProcessedStudy; +struct ClientFilterableState; class VariationsSeed; // VariationsSeedSimulator simulates the result of creating a set of studies @@ -59,14 +60,7 @@ // results of the simulation as a set of expected group change counts of each // type. Result SimulateSeedStudies(const VariationsSeed& seed, - const std::string& locale, - const base::Time& reference_date, - const base::Version& version, - Study_Channel channel, - Study_FormFactor form_factor, - const std::string& hardware_class, - const std::string& session_consistency_country, - const std::string& permanent_consistency_country); + const ClientFilterableState& client_state); private: friend class VariationsSeedSimulatorTest;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index def8a56..ee4d332 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -261,6 +261,8 @@ "accessibility/browser_accessibility_win.h", "accessibility/one_shot_accessibility_tree_search.cc", "accessibility/one_shot_accessibility_tree_search.h", + "android/android_overlay_provider_impl.cc", + "android/android_overlay_provider_impl.h", "android/app_web_message_port.cc", "android/app_web_message_port.h", "android/background_sync_network_observer_android.cc",
diff --git a/content/browser/android/android_overlay_provider_impl.cc b/content/browser/android/android_overlay_provider_impl.cc new file mode 100644 index 0000000..17e71f03 --- /dev/null +++ b/content/browser/android/android_overlay_provider_impl.cc
@@ -0,0 +1,33 @@ +// 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 "content/browser/android/android_overlay_provider_impl.h" + +#include "jni/AndroidOverlayProviderImpl_jni.h" + +using base::android::AttachCurrentThread; +using base::android::ScopedJavaLocalRef; + +namespace content { + +// static +AndroidOverlayProvider* AndroidOverlayProvider::GetInstance() { + static AndroidOverlayProvider* instance = nullptr; + if (!instance) + instance = new AndroidOverlayProviderImpl(); + + return instance; +} + +AndroidOverlayProviderImpl::AndroidOverlayProviderImpl() {} + +AndroidOverlayProviderImpl::~AndroidOverlayProviderImpl() {} + +bool AndroidOverlayProviderImpl::AreOverlaysSupported() const { + JNIEnv* env = AttachCurrentThread(); + + return Java_AndroidOverlayProviderImpl_areOverlaysSupported(env); +} + +} // namespace content
diff --git a/content/browser/android/android_overlay_provider_impl.h b/content/browser/android/android_overlay_provider_impl.h new file mode 100644 index 0000000..f32ea22 --- /dev/null +++ b/content/browser/android/android_overlay_provider_impl.h
@@ -0,0 +1,28 @@ +// 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 CONTENT_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_IMPL_H_ +#define CONTENT_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_IMPL_H_ + +#include "base/android/jni_android.h" +#include "base/android/jni_weak_ref.h" +#include "base/android/scoped_java_ref.h" +#include "content/public/browser/android/android_overlay_provider.h" + +namespace content { + +// Native counterpart to AndroidOverlayProviderImpl java class. +class AndroidOverlayProviderImpl : public AndroidOverlayProvider { + public: + AndroidOverlayProviderImpl(); + + bool AreOverlaysSupported() const override; + + private: + ~AndroidOverlayProviderImpl() override; +}; + +} // namespace content + +#endif // CONTENT_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_IMPL_H_
diff --git a/content/browser/android/android_overlay_provider_impl_unittest.cc b/content/browser/android/android_overlay_provider_impl_unittest.cc new file mode 100644 index 0000000..d7b80ff --- /dev/null +++ b/content/browser/android/android_overlay_provider_impl_unittest.cc
@@ -0,0 +1,21 @@ +// 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 "content/browser/android/android_overlay_provider_impl.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { +namespace { + +class AndroidOverlayProviderImplTest : public ::testing::Test {}; + +TEST_F(AndroidOverlayProviderImplTest, AreOverlaysSupported) { + // Right now, AndroidOverlay always claims to support overlays. + AndroidOverlayProvider* provider = AndroidOverlayProviderImpl::GetInstance(); + ASSERT_NE(provider, nullptr); + ASSERT_TRUE(provider->AreOverlaysSupported()); +} + +} // namespace +} // namespace content
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.cc b/content/browser/devtools/render_frame_devtools_agent_host.cc index 5362c36..2383d1d 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.cc +++ b/content/browser/devtools/render_frame_devtools_agent_host.cc
@@ -469,6 +469,8 @@ current_frame_crashed_ = true; } + UpdateTypeAndTitle(host); + g_instances.Get().push_back(this); AddRef(); // Balanced in RenderFrameHostDestroyed. @@ -825,6 +827,16 @@ handlers_frame_host_ == manager->pending_frame_host(); } +void RenderFrameDevToolsAgentHost::UpdateTypeAndTitle(RenderFrameHost* host) { + DevToolsManager* manager = DevToolsManager::GetInstance(); + if (!manager->delegate()) + return; + if (type_.empty() || type_ == DevToolsAgentHost::kTypeOther) + type_ = manager->delegate()->GetTargetType(host); + if (title_.empty()) + title_ = manager->delegate()->GetTargetTitle(host); +} + #if defined(OS_ANDROID) device::mojom::WakeLock* RenderFrameDevToolsAgentHost::GetWakeLock() { // Here is a lazy binding, and will not reconnect after connection error. @@ -1022,26 +1034,20 @@ } std::string RenderFrameDevToolsAgentHost::GetType() { - DevToolsManager* manager = DevToolsManager::GetInstance(); - if (manager->delegate() && current_) { - std::string type = manager->delegate()->GetTargetType(current_->host()); - if (!type.empty()) - return type; - } - + if (current_) + UpdateTypeAndTitle(current_->host()); + if (!type_.empty()) + return type_; if (IsChildFrame()) return kTypeFrame; return kTypePage; } std::string RenderFrameDevToolsAgentHost::GetTitle() { - DevToolsManager* manager = DevToolsManager::GetInstance(); - if (manager->delegate() && current_) { - std::string title = manager->delegate()->GetTargetTitle(current_->host()); - if (!title.empty()) - return title; - } - + if (current_) + UpdateTypeAndTitle(current_->host()); + if (!title_.empty()) + return title_; if (current_ && current_->host()->GetParent()) return current_->host()->GetLastCommittedURL().spec(); content::WebContents* web_contents = GetWebContents();
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.h b/content/browser/devtools/render_frame_devtools_agent_host.h index 3efc20b2..88fdccbc 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.h +++ b/content/browser/devtools/render_frame_devtools_agent_host.h
@@ -150,6 +150,8 @@ bool CheckConsistency(); + void UpdateTypeAndTitle(RenderFrameHost* host); + #if defined(OS_ANDROID) device::mojom::WakeLock* GetWakeLock(); #endif @@ -171,6 +173,8 @@ #endif RenderFrameHostImpl* handlers_frame_host_; bool current_frame_crashed_; + std::string type_; + std::string title_; // PlzNavigate
diff --git a/content/browser/download/download_item_impl.cc b/content/browser/download/download_item_impl.cc index 39fe5c8..77157b0 100644 --- a/content/browser/download/download_item_impl.cc +++ b/content/browser/download/download_item_impl.cc
@@ -166,6 +166,31 @@ DownloadItemImpl::RequestInfo::~RequestInfo() = default; +DownloadItemImpl::DestinationInfo::DestinationInfo( + const base::FilePath& target_path, + const base::FilePath& current_path, + int64_t received_bytes, + bool all_data_saved, + const std::string& hash, + base::Time end_time) + : target_path(target_path), + current_path(current_path), + received_bytes(received_bytes), + all_data_saved(all_data_saved), + hash(hash), + end_time(end_time) {} + +DownloadItemImpl::DestinationInfo::DestinationInfo( + TargetDisposition target_disposition) + : target_disposition(target_disposition) {} + +DownloadItemImpl::DestinationInfo::DestinationInfo() = default; + +DownloadItemImpl::DestinationInfo::DestinationInfo( + const DownloadItemImpl::DestinationInfo& other) = default; + +DownloadItemImpl::DestinationInfo::~DestinationInfo() = default; + // Constructor for reading from the history service. DownloadItemImpl::DownloadItemImpl( DownloadItemImplDelegate* delegate, @@ -208,7 +233,6 @@ start_time), guid_(base::ToUpperASCII(guid)), download_id_(download_id), - target_path_(target_path), mime_type_(mime_type), original_mime_type_(original_mime_type), total_bytes_(total_bytes), @@ -216,15 +240,16 @@ start_tick_(base::TimeTicks()), state_(ExternalToInternalState(state)), danger_type_(danger_type), - end_time_(end_time), delegate_(delegate), opened_(opened), last_access_time_(last_access_time), transient_(transient), - current_path_(current_path), - received_bytes_(received_bytes), - all_data_saved_(state == COMPLETE), - hash_(hash), + destination_info_(target_path, + current_path, + received_bytes, + state == COMPLETE, + hash, + end_time), last_modified_time_(last_modified), etag_(etag), received_slices_(received_slices), @@ -257,9 +282,6 @@ guid_(info.guid.empty() ? base::ToUpperASCII(base::GenerateGUID()) : info.guid), download_id_(download_id), - target_disposition_((info.save_info->prompt_for_save_location) - ? TARGET_DISPOSITION_PROMPT - : TARGET_DISPOSITION_OVERWRITE), response_headers_(info.response_headers), content_disposition_(info.content_disposition), mime_type_(info.mime_type), @@ -271,6 +293,9 @@ delegate_(delegate), is_temporary_(!info.transient && !info.save_info->file_path.empty()), transient_(info.transient), + destination_info_(info.save_info->prompt_for_save_location + ? TARGET_DISPOSITION_PROMPT + : TARGET_DISPOSITION_OVERWRITE), last_modified_time_(info.last_modified), etag_(info.etag), net_log_(net_log), @@ -301,13 +326,12 @@ is_save_package_download_(true), guid_(base::ToUpperASCII(base::GenerateGUID())), download_id_(download_id), - target_path_(path), mime_type_(mime_type), original_mime_type_(mime_type), start_tick_(base::TimeTicks::Now()), state_(IN_PROGRESS_INTERNAL), delegate_(delegate), - current_path_(path), + destination_info_(path, path, 0, false, std::string(), base::Time()), net_log_(net_log), weak_ptr_factory_(this) { job_ = @@ -390,9 +414,9 @@ base::Bind(&DownloadFileDetach, base::Passed(&download_file_)), callback); } else { - callback.Run(current_path_); + callback.Run(GetFullPath()); } - current_path_.clear(); + destination_info_.current_path.clear(); Remove(); // Download item has now been deleted. } else if (download_file_) { @@ -400,7 +424,7 @@ BrowserThread::FILE, FROM_HERE, base::Bind(&MakeCopyOfDownloadFile, download_file_.get()), callback); } else { - callback.Run(current_path_); + callback.Run(GetFullPath()); } } @@ -691,11 +715,11 @@ } const base::FilePath& DownloadItemImpl::GetFullPath() const { - return current_path_; + return destination_info_.current_path; } const base::FilePath& DownloadItemImpl::GetTargetFilePath() const { - return target_path_; + return destination_info_.target_path; } const base::FilePath& DownloadItemImpl::GetForcedFilePath() const { @@ -707,15 +731,15 @@ base::FilePath DownloadItemImpl::GetFileNameToReportUser() const { if (!display_name_.empty()) return display_name_; - return target_path_.BaseName(); + return GetTargetFilePath().BaseName(); } DownloadItem::TargetDisposition DownloadItemImpl::GetTargetDisposition() const { - return target_disposition_; + return destination_info_.target_disposition; } const std::string& DownloadItemImpl::GetHash() const { - return hash_; + return destination_info_.hash; } bool DownloadItemImpl::GetFileExternallyRemoved() const { @@ -732,7 +756,7 @@ base::WeakPtr<DownloadItemImpl>(), callback, false)); return; } - if (current_path_.empty() || file_externally_removed_) { + if (GetFullPath().empty() || file_externally_removed_) { // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, @@ -742,9 +766,9 @@ } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::FILE, FROM_HERE, - base::Bind(&DeleteDownloadedFile, current_path_), - base::Bind(&DeleteDownloadedFileDone, - weak_ptr_factory_.GetWeakPtr(), callback)); + base::Bind(&DeleteDownloadedFile, GetFullPath()), + base::Bind(&DeleteDownloadedFileDone, weak_ptr_factory_.GetWeakPtr(), + callback)); } bool DownloadItemImpl::IsDangerous() const { @@ -768,8 +792,8 @@ if (speed == 0) return false; - *remaining = base::TimeDelta::FromSeconds( - (total_bytes_ - received_bytes_) / speed); + *remaining = + base::TimeDelta::FromSeconds((total_bytes_ - GetReceivedBytes()) / speed); return true; } @@ -785,11 +809,11 @@ if (delegate_delayed_complete_ || total_bytes_ <= 0) return -1; - return static_cast<int>(received_bytes_ * 100.0 / total_bytes_); + return static_cast<int>(GetReceivedBytes() * 100.0 / total_bytes_); } bool DownloadItemImpl::AllDataSaved() const { - return all_data_saved_; + return destination_info_.all_data_saved; } int64_t DownloadItemImpl::GetTotalBytes() const { @@ -797,7 +821,7 @@ } int64_t DownloadItemImpl::GetReceivedBytes() const { - return received_bytes_; + return destination_info_.received_bytes; } const std::vector<DownloadItem::ReceivedSlice>& @@ -810,7 +834,7 @@ } base::Time DownloadItemImpl::GetEndTime() const { - return end_time_; + return destination_info_.end_time; } bool DownloadItemImpl::CanShowInFolder() { @@ -968,7 +992,7 @@ // We also can't continue if we don't have some verifier to make sure // we're getting the same file. bool restart_required = - (current_path_.empty() || (etag_.empty() && last_modified_time_.empty())); + (GetFullPath().empty() || (etag_.empty() && last_modified_time_.empty())); // We won't auto-restart if we've used up our attempts or the // download has been paused by user action. @@ -1076,13 +1100,13 @@ // HTTP_PRECONDITION_FAILED), then the download will automatically retried as // a full request rather than a partial. Full restarts clobber validators. int origin_state = 0; - bool is_partial = received_bytes_ > 0; + bool is_partial = GetReceivedBytes() > 0; if (chain_iter != new_create_info.url_chain.end()) origin_state |= ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS; if (etag_ != new_create_info.etag || last_modified_time_ != new_create_info.last_modified) { received_slices_.clear(); - received_bytes_ = 0; + destination_info_.received_bytes = 0; origin_state |= ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED; } if (content_disposition_ != new_create_info.content_disposition) @@ -1132,8 +1156,8 @@ int64_t total_bytes, std::unique_ptr<crypto::SecureHash> hash_state) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(!all_data_saved_); - all_data_saved_ = true; + DCHECK(!AllDataSaved()); + destination_info_.all_data_saved = true; SetTotalBytes(total_bytes); UpdateProgress(total_bytes, 0); received_slices_.clear(); @@ -1160,8 +1184,8 @@ void DownloadItemImpl::MarkAsComplete() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(all_data_saved_); - end_time_ = base::Time::Now(); + DCHECK(AllDataSaved()); + destination_info_.end_time = base::Time::Now(); TransitionTo(COMPLETE_INTERNAL); UpdateObservers(); } @@ -1190,7 +1214,7 @@ if (net_log_.IsCapturing()) { net_log_.AddEvent( net::NetLogEventType::DOWNLOAD_ITEM_UPDATED, - net::NetLog::Int64Callback("bytes_so_far", received_bytes_)); + net::NetLog::Int64Callback("bytes_so_far", GetReceivedBytes())); } UpdateObservers(); @@ -1240,7 +1264,7 @@ std::string file_name; if (download_type == SRC_HISTORY_IMPORT) { // target_path_ works for History and Save As versions. - file_name = target_path_.AsUTF8Unsafe(); + file_name = GetTargetFilePath().AsUTF8Unsafe(); } else { // See if it's set programmatically. file_name = GetForcedFilePath().AsUTF8Unsafe(); @@ -1301,7 +1325,7 @@ DCHECK(state_ == INITIAL_INTERNAL || state_ == RESUMING_INTERNAL); // If the state_ is INITIAL_INTERNAL, then the target path must be empty. - DCHECK(state_ != INITIAL_INTERNAL || target_path_.empty()); + DCHECK(state_ != INITIAL_INTERNAL || GetTargetFilePath().empty()); // If a resumption attempted failed, or if the download was DOA, then the // download should go back to being interrupted. @@ -1318,10 +1342,10 @@ ? new_create_info.save_info->hash_state->Clone() : nullptr; - current_path_ = new_create_info.save_info->file_path; - received_bytes_ = offset; + destination_info_.current_path = new_create_info.save_info->file_path; + destination_info_.received_bytes = offset; hash_state_ = std::move(hash_state); - hash_.clear(); + destination_info_.hash.clear(); deferred_interrupt_reason_ = new_create_info.result; received_slices_.clear(); TransitionTo(INTERRUPTED_TARGET_PENDING_INTERNAL); @@ -1352,7 +1376,7 @@ // If the download uses parallel requests, and choose not to create parallel // request during resumption, clear the received_slices_ vector. if (!IsParallelDownloadEnabled() && !received_slices_.empty()) { - received_bytes_ = + destination_info_.received_bytes = GetMaxContiguousDataBlockSizeFromBeginning(received_slices_); received_slices_.clear(); } @@ -1426,8 +1450,8 @@ return; } - target_path_ = target_path; - target_disposition_ = disposition; + destination_info_.target_path = target_path; + destination_info_.target_disposition = disposition; SetDangerType(danger_type); // This was an interrupted download that was looking for a filename. Resolve @@ -1451,7 +1475,7 @@ // The intermediate name may change from its original value during filename // determination on resumption, for example if the reason for the interruption // was the download target running out space, resulting in a user prompt. - if (intermediate_path == current_path_) { + if (intermediate_path == GetFullPath()) { OnDownloadRenamedToIntermediateName(DOWNLOAD_INTERRUPT_REASON_NONE, intermediate_path); return; @@ -1518,7 +1542,7 @@ TransitionTo(TARGET_RESOLVED_INTERNAL); if (DOWNLOAD_INTERRUPT_REASON_NONE != deferred_interrupt_reason_) { - InterruptWithPartialState(received_bytes_, std::move(hash_state_), + InterruptWithPartialState(GetReceivedBytes(), std::move(hash_state_), deferred_interrupt_reason_); deferred_interrupt_reason_ = DOWNLOAD_INTERRUPT_REASON_NONE; UpdateObservers(); @@ -1554,7 +1578,7 @@ // history handle, (validated or safe). DCHECK_EQ(IN_PROGRESS_INTERNAL, state_); DCHECK(!IsDangerous()); - DCHECK(all_data_saved_); + DCHECK(AllDataSaved()); OnDownloadCompleting(); } @@ -1613,9 +1637,9 @@ return; } - DCHECK(target_path_ == full_path); + DCHECK(GetTargetFilePath() == full_path); - if (full_path != current_path_) { + if (full_path != GetFullPath()) { // full_path is now the current and target file path. DCHECK(!full_path.empty()); SetFullPath(full_path); @@ -1653,10 +1677,10 @@ DVLOG(20) << __func__ << "() " << DebugString(false); - DCHECK(all_data_saved_); - end_time_ = base::Time::Now(); + DCHECK(AllDataSaved()); + destination_info_.end_time = base::Time::Now(); TransitionTo(COMPLETE_INTERNAL); - RecordDownloadCompleted(start_tick_, received_bytes_); + RecordDownloadCompleted(start_tick_, GetReceivedBytes()); if (!GetBrowserContext()->IsOffTheRecord()) { RecordDownloadCount(COMPLETED_COUNT_NORMAL_PROFILE); } @@ -1764,15 +1788,15 @@ return; last_reason_ = reason; - if (!current_path_.empty()) { + if (!GetFullPath().empty()) { // There is no download file and this is transitioning from INTERRUPTED // to CANCELLED. The intermediate file is no longer usable, and should // be deleted. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(base::IgnoreResult(&DeleteDownloadedFile), - current_path_)); - current_path_.clear(); + GetFullPath())); + destination_info_.current_path.clear(); } break; } @@ -1786,12 +1810,12 @@ // simply result in a null range request, which would generate a // DestinationCompleted() notification from the DownloadFile, which would // behave properly with setting all_data_saved_ to false here. - all_data_saved_ = false; + destination_info_.all_data_saved = false; - if (current_path_.empty()) { + if (GetFullPath().empty()) { hash_state_.reset(); - hash_.clear(); - received_bytes_ = 0; + destination_info_.hash.clear(); + destination_info_.received_bytes = 0; received_slices_.clear(); } else { UpdateProgress(bytes_so_far, 0); @@ -1820,11 +1844,11 @@ return; } - RecordDownloadInterrupted(reason, received_bytes_, total_bytes_, + RecordDownloadInterrupted(reason, GetReceivedBytes(), total_bytes_, job_ && job_->IsParallelizable(), IsParallelDownloadEnabled()); if (reason == DOWNLOAD_INTERRUPT_REASON_SERVER_CONTENT_LENGTH_MISMATCH) - received_bytes_at_length_mismatch = received_bytes_; + received_bytes_at_length_mismatch = GetReceivedBytes(); if (!GetWebContents()) RecordDownloadCount(INTERRUPTED_WITHOUT_WEBCONTENTS); @@ -1840,12 +1864,12 @@ void DownloadItemImpl::UpdateProgress( int64_t bytes_so_far, int64_t bytes_per_sec) { - received_bytes_ = bytes_so_far; + destination_info_.received_bytes = bytes_so_far; bytes_per_sec_ = bytes_per_sec; // If we've received more data than we were expecting (bad server info?), // revert to 'unknown size mode'. - if (received_bytes_ > total_bytes_) + if (bytes_so_far > total_bytes_) total_bytes_ = 0; } @@ -1853,14 +1877,14 @@ std::unique_ptr<crypto::SecureHash> hash_state) { hash_state_ = std::move(hash_state); if (!hash_state_) { - hash_.clear(); + destination_info_.hash.clear(); return; } std::unique_ptr<crypto::SecureHash> clone_of_hash_state(hash_state_->Clone()); std::vector<char> hash_value(clone_of_hash_state->GetHashLength()); clone_of_hash_state->Finish(&hash_value.front(), hash_value.size()); - hash_.assign(hash_value.begin(), hash_value.end()); + destination_info_.hash.assign(hash_value.begin(), hash_value.end()); } void DownloadItemImpl::ReleaseDownloadFile(bool destroy_file) { @@ -1874,7 +1898,7 @@ base::Bind(&DownloadFileCancel, base::Passed(&download_file_))); // Avoid attempting to reuse the intermediate file by clearing out // current_path_ and received slices. - current_path_.clear(); + destination_info_.current_path.clear(); received_slices_.clear(); } else { BrowserThread::PostTask( @@ -1911,9 +1935,9 @@ // target determination calls and the download is in progress, both the target // and current paths should be non-empty and they should point to the same // directory. - DCHECK(!target_path_.empty()); - DCHECK(!current_path_.empty()); - DCHECK(target_path_.DirName() == current_path_.DirName()); + DCHECK(!GetTargetFilePath().empty()); + DCHECK(!GetFullPath().empty()); + DCHECK(GetTargetFilePath().DirName() == GetFullPath().DirName()); // Give the delegate a chance to hold up a stop sign. It'll call // use back through the passed callback if it does and that state changes. @@ -1954,9 +1978,9 @@ break; case IN_PROGRESS_INTERNAL: - DCHECK(!current_path_.empty()) << "Current output path must be known."; - DCHECK(!target_path_.empty()) << "Target path must be known."; - DCHECK(current_path_.DirName() == target_path_.DirName()) + DCHECK(!GetFullPath().empty()) << "Current output path must be known."; + DCHECK(!GetTargetFilePath().empty()) << "Target path must be known."; + DCHECK(GetFullPath().DirName() == GetTargetFilePath().DirName()) << "Current output directory must match target directory."; DCHECK(download_file_) << "Output file must be owned by download item."; DCHECK(job_) << "Must have active download job."; @@ -1966,16 +1990,17 @@ break; case COMPLETING_INTERNAL: - DCHECK(all_data_saved_) << "All data must be saved prior to completion."; + DCHECK(AllDataSaved()) << "All data must be saved prior to completion."; DCHECK(!download_file_) << "Download file must be released prior to completion."; - DCHECK(!target_path_.empty()) << "Target path must be known."; - DCHECK(current_path_ == target_path_) + DCHECK(!GetTargetFilePath().empty()) << "Target path must be known."; + DCHECK(GetFullPath() == GetTargetFilePath()) << "Current output path must match target path."; net_log_.AddEvent( net::NetLogEventType::DOWNLOAD_ITEM_COMPLETING, - base::Bind(&ItemCompletingNetLogCallback, received_bytes_, &hash_)); + base::Bind(&ItemCompletingNetLogCallback, GetReceivedBytes(), + &destination_info_.hash)); break; case COMPLETE_INTERNAL: @@ -1989,20 +2014,20 @@ << "Download file must be released prior to interruption."; DCHECK_NE(last_reason_, DOWNLOAD_INTERRUPT_REASON_NONE); net_log_.AddEvent(net::NetLogEventType::DOWNLOAD_ITEM_INTERRUPTED, - base::Bind(&ItemInterruptedNetLogCallback, - last_reason_, received_bytes_)); + base::Bind(&ItemInterruptedNetLogCallback, last_reason_, + GetReceivedBytes())); break; case RESUMING_INTERNAL: net_log_.AddEvent(net::NetLogEventType::DOWNLOAD_ITEM_RESUMED, - base::Bind(&ItemResumingNetLogCallback, false, - last_reason_, received_bytes_)); + base::Bind(&ItemResumingNetLogCallback, false, + last_reason_, GetReceivedBytes())); break; case CANCELLED_INTERNAL: net_log_.AddEvent( net::NetLogEventType::DOWNLOAD_ITEM_CANCELED, - base::Bind(&ItemCanceledNetLogCallback, received_bytes_)); + base::Bind(&ItemCanceledNetLogCallback, GetReceivedBytes())); break; case MAX_DOWNLOAD_INTERNAL_STATE: @@ -2026,7 +2051,7 @@ // Resumption if (was_done && !is_done) { - std::string file_name(target_path_.BaseName().AsUTF8Unsafe()); + std::string file_name(GetTargetFilePath().BaseName().AsUTF8Unsafe()); net_log_.BeginEvent(net::NetLogEventType::DOWNLOAD_ITEM_ACTIVE, base::Bind(&ItemActivatedNetLogCallback, this, SRC_ACTIVE_DOWNLOAD, &file_name)); @@ -2060,11 +2085,11 @@ << DebugString(true); DCHECK(!new_path.empty()); - net_log_.AddEvent( - net::NetLogEventType::DOWNLOAD_ITEM_RENAMED, - base::Bind(&ItemRenamedNetLogCallback, ¤t_path_, &new_path)); + net_log_.AddEvent(net::NetLogEventType::DOWNLOAD_ITEM_RENAMED, + base::Bind(&ItemRenamedNetLogCallback, + &destination_info_.current_path, &new_path)); - current_path_ = new_path; + destination_info_.current_path = new_path; } void DownloadItemImpl::AutoResumeIfValid() { @@ -2097,11 +2122,11 @@ ResumeMode mode = GetResumeMode(); if (mode == RESUME_MODE_IMMEDIATE_RESTART || mode == RESUME_MODE_USER_RESTART) { - DCHECK(current_path_.empty()); - received_bytes_ = 0; + DCHECK(GetFullPath().empty()); + destination_info_.received_bytes = 0; last_modified_time_.clear(); etag_.clear(); - hash_.clear(); + destination_info_.hash.clear(); hash_state_.reset(); received_slices_.clear(); } @@ -2127,7 +2152,7 @@ } download_params->set_last_modified(GetLastModifiedTime()); download_params->set_etag(GetETag()); - download_params->set_hash_of_partial_file(hash_); + download_params->set_hash_of_partial_file(GetHash()); download_params->set_hash_state(std::move(hash_state_)); // Note that resumed downloads disallow redirects. Hence the referrer URL
diff --git a/content/browser/download/download_item_impl.h b/content/browser/download/download_item_impl.h index 9980ad00..c38e4419 100644 --- a/content/browser/download/download_item_impl.h +++ b/content/browser/download/download_item_impl.h
@@ -102,6 +102,54 @@ base::Time start_time; }; + // Information about the current state of the download destination. + struct CONTENT_EXPORT DestinationInfo { + DestinationInfo(const base::FilePath& target_path, + const base::FilePath& current_path, + int64_t received_bytes, + bool all_data_saved, + const std::string& hash, + base::Time end_time); + DestinationInfo(); + DestinationInfo(TargetDisposition target_disposition); + DestinationInfo(const DestinationInfo& other); + ~DestinationInfo(); + + // Whether the target should be overwritten, uniquified or prompted for. + TargetDisposition target_disposition = TARGET_DISPOSITION_OVERWRITE; + + // Target path of an in-progress download. We may be downloading to a + // temporary or intermediate file (specified by |current_path|). Once the + // download completes, we will rename the file to |target_path|. + base::FilePath target_path; + + // Full path to the downloaded or downloading file. This is the path to the + // physical file, if one exists. The final target path is specified by + // |target_path|. |current_path| can be empty if the in-progress path + // hasn't been determined. + base::FilePath current_path; + + // Current received bytes. + int64_t received_bytes = 0; + + // True if we've saved all the data for the download. If true, then the file + // at |current_path| contains |received_bytes|, which constitute the + // entirety of what we expect to save there. A digest of its contents can be + // found at |hash|. + bool all_data_saved = false; + + // SHA256 hash of the possibly partial content. The hash is updated each + // time the download is interrupted, and when the all the data has been + // transferred. |hash| contains the raw binary hash and is not hex encoded. + // + // While the download is in progress, and while resuming, |hash| will be + // empty. + std::string hash; + + // Time last update was written to target file. + base::Time end_time; + }; + // The maximum number of attempts we will make to resume automatically. static const int kMaxAutoResumeAttempts; @@ -587,17 +635,9 @@ uint32_t download_id_ = kInvalidId; // Display name for the download. If this is empty, then the display name is - // considered to be |target_path_.BaseName()|. + // considered to be |GetTargetFilePath().BaseName()|. base::FilePath display_name_; - // Target path of an in-progress download. We may be downloading to a - // temporary or intermediate file (specified by |current_path_|. Once the - // download completes, we will rename the file to |target_path_|. - base::FilePath target_path_; - - // Whether the target should be overwritten, uniquified or prompted for. - TargetDisposition target_disposition_ = TARGET_DISPOSITION_OVERWRITE; - // Information from the response. // The HTTP response headers. This contains a nullptr when the response has @@ -633,9 +673,6 @@ // The views of this item in the download shelf and download contents. base::ObserverList<Observer> observers_; - // Time the download completed. - base::Time end_time_; - // Our delegate. DownloadItemImplDelegate* delegate_ = nullptr; @@ -682,36 +719,16 @@ // the IN_PROGRESS state. std::unique_ptr<DownloadFile> download_file_; - // Full path to the downloaded or downloading file. This is the path to the - // physical file, if one exists. The final target path is specified by - // |target_path_|. |current_path_| can be empty if the in-progress path hasn't - // been determined. - base::FilePath current_path_; - - // Current received bytes. - int64_t received_bytes_ = 0; + // Information about |download_file_|. + DestinationInfo destination_info_; // Current speed. Calculated by the DownloadFile. int64_t bytes_per_sec_ = 0; - // True if we've saved all the data for the download. If true, then the file - // at |current_path_| contains |received_bytes_|, which constitute the - // entirety of what we expect to save there. A digest of its contents can be - // found at |hash_|. - bool all_data_saved_ = false; - // The number of times this download has been resumed automatically. Will be // reset to 0 if a resumption is performed in response to a Resume() call. int auto_resume_count_ = 0; - // SHA256 hash of the possibly partial content. The hash is updated each time - // the download is interrupted, and when the all the data has been - // transferred. |hash_| contains the raw binary hash and is not hex encoded. - // - // While the download is in progress, and while resuming, |hash_| will be - // empty. - std::string hash_; - // In the event of an interruption, the DownloadDestinationObserver interface // exposes the partial hash state. This state can be held by the download item // in case it's needed for resumption.
diff --git a/content/browser/download/download_item_impl_unittest.cc b/content/browser/download/download_item_impl_unittest.cc index 33033208..1d10e52 100644 --- a/content/browser/download/download_item_impl_unittest.cc +++ b/content/browser/download/download_item_impl_unittest.cc
@@ -119,7 +119,7 @@ MOCK_CONST_METHOD0(GetDownloadManager, DownloadManager*()); MOCK_CONST_METHOD0(PauseRequest, void()); MOCK_CONST_METHOD0(ResumeRequest, void()); - MOCK_CONST_METHOD0(CancelRequest, void()); + MOCK_CONST_METHOD1(CancelRequest, void(bool)); MOCK_CONST_METHOD0(DebugString, std::string()); }; @@ -1127,7 +1127,7 @@ base::MakeUnique<MockRequestHandle>(); EXPECT_CALL(*file, Cancel()); - EXPECT_CALL(*request_handle, CancelRequest()); + EXPECT_CALL(*request_handle, CancelRequest(_)); EXPECT_CALL(*file, Initialize(_, _, _, _)) .WillOnce(ScheduleCallbackWithParam( DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED)); @@ -2161,7 +2161,7 @@ // Expect that the download file and the request will be cancelled as a // result. EXPECT_CALL(*file_, Cancel()); - EXPECT_CALL(*request_handle_, CancelRequest()); + EXPECT_CALL(*request_handle_, CancelRequest(_)); base::RunLoop download_start_loop; DownloadFile::InitializeCallback initialize_callback; @@ -2205,7 +2205,7 @@ // Expect that the download file and the request will be cancelled as a // result. EXPECT_CALL(*file_, Cancel()); - EXPECT_CALL(*request_handle_, CancelRequest()); + EXPECT_CALL(*request_handle_, CancelRequest(_)); // Intermediate rename loop is not used immediately, but let's set up the // DownloadFile expectations since we are about to transfer its ownership to @@ -2271,7 +2271,7 @@ // DownloadFile will Detach()). It depends on the list of observations that // are given to us. EXPECT_CALL(*file_, Cancel()).Times(::testing::AnyNumber()); - EXPECT_CALL(*request_handle_, CancelRequest()).Times(::testing::AnyNumber()); + EXPECT_CALL(*request_handle_, CancelRequest(_)).Times(::testing::AnyNumber()); EXPECT_CALL(*file_, Detach()).Times(::testing::AnyNumber()); EXPECT_CALL(*file_, FullPath())
diff --git a/content/browser/download/download_job_impl.cc b/content/browser/download/download_job_impl.cc index 76527dc..de43764 100644 --- a/content/browser/download/download_job_impl.cc +++ b/content/browser/download/download_job_impl.cc
@@ -20,7 +20,7 @@ void DownloadJobImpl::Cancel(bool user_cancel) { if (request_handle_) - request_handle_->CancelRequest(); + request_handle_->CancelRequest(user_cancel); } void DownloadJobImpl::Pause() {
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index 238508c..d74755a 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -348,7 +348,7 @@ // If the download is no longer known to the DownloadManager, then it was // removed after it was resumed. Ignore. If the download is cancelled // while resuming, then also ignore the request. - info->request_handle->CancelRequest(); + info->request_handle->CancelRequest(true); if (!on_started.is_null()) on_started.Run(nullptr, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); // The ByteStreamReader lives and dies on the FILE thread.
diff --git a/content/browser/download/download_request_handle.cc b/content/browser/download/download_request_handle.cc index f5979b9..0cde1f84 100644 --- a/content/browser/download/download_request_handle.cc +++ b/content/browser/download/download_request_handle.cc
@@ -54,7 +54,7 @@ base::Bind(&DownloadResourceHandler::ResumeRequest, handler_)); } -void DownloadRequestHandle::CancelRequest() const { +void DownloadRequestHandle::CancelRequest(bool user_cancel) const { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&DownloadResourceHandler::CancelRequest, handler_));
diff --git a/content/browser/download/download_request_handle.h b/content/browser/download/download_request_handle.h index 090a25bb..8fbbc10 100644 --- a/content/browser/download/download_request_handle.h +++ b/content/browser/download/download_request_handle.h
@@ -34,7 +34,7 @@ virtual void ResumeRequest() const = 0; // Cancels the request. - virtual void CancelRequest() const = 0; + virtual void CancelRequest(bool user_cancel) const = 0; }; @@ -62,7 +62,7 @@ DownloadManager* GetDownloadManager() const override; void PauseRequest() const override; void ResumeRequest() const override; - void CancelRequest() const override; + void CancelRequest(bool user_cancel) const override; private: base::WeakPtr<DownloadResourceHandler> handler_;
diff --git a/content/browser/download/download_worker.cc b/content/browser/download/download_worker.cc index c1fea18..ce225f0 100644 --- a/content/browser/download/download_worker.cc +++ b/content/browser/download/download_worker.cc
@@ -58,6 +58,7 @@ length_(length), is_paused_(false), is_canceled_(false), + is_user_cancel_(false), weak_factory_(this) { DCHECK(delegate_); } @@ -87,10 +88,11 @@ request_handle_->ResumeRequest(); } -void DownloadWorker::Cancel() { +void DownloadWorker::Cancel(bool user_cancel) { is_canceled_ = true; + is_user_cancel_ = user_cancel; if (request_handle_) - request_handle_->CancelRequest(); + request_handle_->CancelRequest(user_cancel); } void DownloadWorker::OnUrlDownloaderStarted( @@ -103,7 +105,7 @@ // Destroy the request if user canceled. if (is_canceled_) { VLOG(kVerboseLevel) << "Byte stream arrived after user cancel the request."; - create_info->request_handle->CancelRequest(); + create_info->request_handle->CancelRequest(is_user_cancel_); return; }
diff --git a/content/browser/download/download_worker.h b/content/browser/download/download_worker.h index ecfb182..4fd3a951 100644 --- a/content/browser/download/download_worker.h +++ b/content/browser/download/download_worker.h
@@ -48,7 +48,7 @@ // Download operations. void Pause(); void Resume(); - void Cancel(); + void Cancel(bool user_cancel); private: // UrlDownloader::Delegate implementation. @@ -73,6 +73,7 @@ // States of the worker. bool is_paused_; bool is_canceled_; + bool is_user_cancel_; // Used to control the network request. Live on UI thread. std::unique_ptr<DownloadRequestHandleInterface> request_handle_;
diff --git a/content/browser/download/parallel_download_job.cc b/content/browser/download/parallel_download_job.cc index 19d809d..1f756ee 100644 --- a/content/browser/download/parallel_download_job.cc +++ b/content/browser/download/parallel_download_job.cc
@@ -52,7 +52,7 @@ } for (auto& worker : workers_) - worker.second->Cancel(); + worker.second->Cancel(user_cancel); } void ParallelDownloadJob::Pause() { @@ -103,7 +103,7 @@ auto it = workers_.find(offset); DCHECK(it != workers_.end()); - it->second->Cancel(); + it->second->Cancel(false); } void ParallelDownloadJob::BuildParallelRequestAfterDelay() { @@ -126,7 +126,7 @@ if (!success) { VLOG(kVerboseLevel) << "Byte stream arrived after download file is released."; - worker->Cancel(); + worker->Cancel(false); } }
diff --git a/content/browser/download/parallel_download_job_unittest.cc b/content/browser/download/parallel_download_job_unittest.cc index 41a3b791..2690ea47 100644 --- a/content/browser/download/parallel_download_job_unittest.cc +++ b/content/browser/download/parallel_download_job_unittest.cc
@@ -32,7 +32,7 @@ MOCK_CONST_METHOD0(GetDownloadManager, DownloadManager*()); MOCK_CONST_METHOD0(PauseRequest, void()); MOCK_CONST_METHOD0(ResumeRequest, void()); - MOCK_CONST_METHOD0(CancelRequest, void()); + MOCK_CONST_METHOD1(CancelRequest, void(bool)); MOCK_CONST_METHOD0(DebugString, std::string()); }; @@ -284,7 +284,7 @@ // built. TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeBuildRequests) { CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); - EXPECT_CALL(*mock_request_handle_, CancelRequest()); + EXPECT_CALL(*mock_request_handle_, CancelRequest(_)); // Job is canceled before building parallel requests. job_->Cancel(true); @@ -300,7 +300,7 @@ // canceled. TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeByteStreamReady) { CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); - EXPECT_CALL(*mock_request_handle_, CancelRequest()); + EXPECT_CALL(*mock_request_handle_, CancelRequest(_)); BuildParallelRequests(); VerifyWorker(50, 0); @@ -313,7 +313,7 @@ for (auto& worker : job_->workers()) { std::unique_ptr<MockDownloadRequestHandle> mock_handle = base::MakeUnique<MockDownloadRequestHandle>(); - EXPECT_CALL(*mock_handle.get(), CancelRequest()); + EXPECT_CALL(*mock_handle.get(), CancelRequest(_)); MakeWorkerReady(worker.second.get(), std::move(mock_handle)); }
diff --git a/content/browser/download/save_package.cc b/content/browser/download/save_package.cc index d52e6378..c299f67 100644 --- a/content/browser/download/save_package.cc +++ b/content/browser/download/save_package.cc
@@ -117,7 +117,7 @@ } // Request handle for SavePackage downloads. Currently doesn't support -// pause/resume/cancel, but returns a WebContents. +// pause/resume, but returns a WebContents. class SavePackageRequestHandle : public DownloadRequestHandleInterface { public: explicit SavePackageRequestHandle(base::WeakPtr<SavePackage> save_package) @@ -130,7 +130,10 @@ DownloadManager* GetDownloadManager() const override { return nullptr; } void PauseRequest() const override {} void ResumeRequest() const override {} - void CancelRequest() const override {} + void CancelRequest(bool user_cancel) const override { + if (save_package_.get() && !save_package_->canceled()) + save_package_->Cancel(user_cancel, false); + } private: base::WeakPtr<SavePackage> save_package_; @@ -222,14 +225,14 @@ return visible_entry ? visible_entry->GetURL() : GURL::EmptyGURL(); } -void SavePackage::Cancel(bool user_action) { +void SavePackage::Cancel(bool user_action, bool cancel_download_item) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!canceled()) { if (user_action) user_canceled_ = true; else disk_error_occurred_ = true; - Stop(); + Stop(cancel_download_item); } RecordSavePackageEvent(SAVE_PACKAGE_CANCELLED); } @@ -286,7 +289,6 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(item); download_ = item; - download_->AddObserver(this); // Confirm above didn't delete the tab out from under us. if (!download_created_callback.is_null()) download_created_callback.Run(download_); @@ -324,15 +326,7 @@ } wrote_to_completed_file_ = true; - // Hack to avoid touching download_ after user cancel. - // TODO(rdsmith/benjhayden): Integrate canceling on DownloadItem - // with SavePackage flow. - if (download_->GetState() == DownloadItem::IN_PROGRESS) { - // Must call OnAllDataSaved here in order for - // GDataDownloadObserver::ShouldUpload() to return true. - // ShouldCompleteDownload() may depend on the gdata uploader to finish. - download_->OnAllDataSaved(size, std::unique_ptr<crypto::SecureHash>()); - } + download_->OnAllDataSaved(size, std::unique_ptr<crypto::SecureHash>()); if (!download_manager_->GetDelegate()) { Finish(); @@ -604,7 +598,7 @@ // Stop all page saving jobs that are in progress and instruct the FILE thread // to delete all saved files. -void SavePackage::Stop() { +void SavePackage::Stop(bool cancel_download_item) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // If we haven't moved out of the initial state, there's nothing to cancel and // there won't be valid pointers for |file_manager_| or |download_|. @@ -644,7 +638,8 @@ // Inform the DownloadItem we have canceled whole save page job. if (download_) { - download_->Cancel(false); + if (cancel_download_item) + download_->Cancel(false); FinalizeDownloadEntry(); } } @@ -708,19 +703,14 @@ list_of_failed_save_item_ids)); if (download_) { - // Hack to avoid touching |download_| after user cancel. - // TODO(rdsmith/benjhayden): Integrate canceling on DownloadItem - // with SavePackage flow. - if (download_->GetState() == DownloadItem::IN_PROGRESS) { - if (save_type_ != SAVE_PAGE_TYPE_AS_MHTML) { - download_->DestinationUpdate( - all_save_items_count_, CurrentSpeed(), - std::vector<DownloadItem::ReceivedSlice>()); - download_->OnAllDataSaved(all_save_items_count_, - std::unique_ptr<crypto::SecureHash>()); - } - download_->MarkAsComplete(); + if (save_type_ != SAVE_PAGE_TYPE_AS_MHTML) { + download_->DestinationUpdate( + all_save_items_count_, CurrentSpeed(), + std::vector<DownloadItem::ReceivedSlice>()); + download_->OnAllDataSaved(all_save_items_count_, + std::unique_ptr<crypto::SecureHash>()); } + download_->MarkAsComplete(); FinalizeDownloadEntry(); } } @@ -744,10 +734,7 @@ // Inform the DownloadItem to update UI. // We use the received bytes as number of saved files. - // Hack to avoid touching download_ after user cancel. - // TODO(rdsmith/benjhayden): Integrate canceling on DownloadItem - // with SavePackage flow. - if (download_ && (download_->GetState() == DownloadItem::IN_PROGRESS)) { + if (download_) { download_->DestinationUpdate( completed_count(), CurrentSpeed(), std::vector<DownloadItem::ReceivedSlice>()); @@ -1231,10 +1218,7 @@ all_save_items_count_ = static_cast<int>(waiting_item_queue_.size()); // We use total bytes as the total number of files we want to save. - // Hack to avoid touching download_ after user cancel. - // TODO(rdsmith/benjhayden): Integrate canceling on DownloadItem - // with SavePackage flow. - if (download_ && (download_->GetState() == DownloadItem::IN_PROGRESS)) + if (download_) download_->SetTotalBytes(all_save_items_count_); if (all_save_items_count_) { @@ -1474,30 +1458,13 @@ Init(download_created_callback); } -void SavePackage::RemoveObservers() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); +void SavePackage::FinalizeDownloadEntry() { DCHECK(download_); DCHECK(download_manager_); - download_->RemoveObserver(this); + download_manager_->OnSavePackageSuccessfullyFinished(download_); download_ = nullptr; download_manager_ = nullptr; } -void SavePackage::OnDownloadDestroyed(DownloadItem* download) { - if (!canceled()) { - Cancel(false); - // Cancel() also calls RemoveObservers(). - } else { - RemoveObservers(); - } -} - -void SavePackage::FinalizeDownloadEntry() { - DCHECK(download_); - - download_manager_->OnSavePackageSuccessfullyFinished(download_); - RemoveObservers(); -} - } // namespace content
diff --git a/content/browser/download/save_package.h b/content/browser/download/save_package.h index d48ae523..b78c35e 100644 --- a/content/browser/download/save_package.h +++ b/content/browser/download/save_package.h
@@ -97,7 +97,7 @@ bool Init(const SavePackageDownloadCreatedCallback& cb); // Cancel all in progress request, might be called by user or internal error. - void Cancel(bool user_action); + void Cancel(bool user_action, bool cancel_download_item = true); void Finish(); @@ -165,7 +165,7 @@ // Notes from Init() above applies here as well. void InternalInit(); - void Stop(); + void Stop(bool cancel_download_item); void CheckFinish(); // Initiate a saving job of a specific URL. We send the request to @@ -181,15 +181,9 @@ bool OnMessageReceived(const IPC::Message& message, RenderFrameHost* render_frame_host) override; - // DownloadItem::Observer implementation. - void OnDownloadDestroyed(DownloadItem* download) override; - // Update the download history of this item upon completion. void FinalizeDownloadEntry(); - // Detach from DownloadManager. - void RemoveObservers(); - // Return max length of a path for a specific base directory. // This is needed on POSIX, which restrict the length of file names in // addition to the restriction on the length of path names.
diff --git a/content/browser/download/url_downloader.cc b/content/browser/download/url_downloader.cc index ee70480e..169e975 100644 --- a/content/browser/download/url_downloader.cc +++ b/content/browser/download/url_downloader.cc
@@ -50,7 +50,7 @@ downloader_task_runner_->PostTask( FROM_HERE, base::Bind(&UrlDownloader::ResumeRequest, downloader_)); } - void CancelRequest() const override { + void CancelRequest(bool user_cancel) const override { downloader_task_runner_->PostTask( FROM_HERE, base::Bind(&UrlDownloader::CancelRequest, downloader_)); }
diff --git a/content/browser/frame_host/navigation_controller_impl.cc b/content/browser/frame_host/navigation_controller_impl.cc index c133a633..1f07ec6 100644 --- a/content/browser/frame_host/navigation_controller_impl.cc +++ b/content/browser/frame_host/navigation_controller_impl.cc
@@ -1297,7 +1297,10 @@ } else { // When restoring a tab, the serialized NavigationEntry doesn't have the // SSL state. - entry->GetSSL() = handle->ssl_status(); + // Only copy in the restore case since this code path can be taken during + // navigation. See http://crbug.com/727892 + if (was_restored) + entry->GetSSL() = handle->ssl_status(); } } else { // This is renderer-initiated. The only kinds of renderer-initated
diff --git a/content/browser/frame_host/render_frame_host_manager_unittest.cc b/content/browser/frame_host/render_frame_host_manager_unittest.cc index 2b398185..b79232b51 100644 --- a/content/browser/frame_host/render_frame_host_manager_unittest.cc +++ b/content/browser/frame_host/render_frame_host_manager_unittest.cc
@@ -318,7 +318,7 @@ void set_webui_type(int type) { factory_.set_webui_type(type); } - void NavigateActiveAndCommit(const GURL& url) { + void NavigateActiveAndCommit(const GURL& url, bool dont_swap_out = false) { // Note: we navigate the active RenderFrameHost because previous navigations // won't have committed yet, so NavigateAndCommit does the wrong thing // for us. @@ -357,6 +357,8 @@ // Simulate the swap out ACK coming from the pending renderer. This should // either shut down the old RFH or leave it in a swapped out state. if (old_rfh != active_rfh) { + if (dont_swap_out) + return; old_rfh->OnSwappedOut(); EXPECT_TRUE(rfh_observer.deleted()); } @@ -574,14 +576,12 @@ // Navigate our first tab to a chrome url and then to the destination. NavigateActiveAndCommit(kChromeURL); TestRenderFrameHost* ntp_rfh = contents()->GetMainFrame(); - TestRenderViewHost* ntp_rvh = ntp_rfh->GetRenderViewHost(); // Send an update favicon message and make sure it works. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE(ntp_rfh->GetRenderViewHost()->GetWidget()->OnMessageReceived( - ViewHostMsg_UpdateFaviconURL( - ntp_rfh->GetRenderViewHost()->GetRoutingID(), icons))); + EXPECT_TRUE(ntp_rfh->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(ntp_rfh->GetRoutingID(), icons))); EXPECT_TRUE(observer.favicon_received()); } // Create one more frame in the same SiteInstance where ntp_rfh @@ -589,8 +589,8 @@ // site. ntp_rfh->GetSiteInstance()->IncrementActiveFrameCount(); - // Navigate to a cross-site URL. - NavigateActiveAndCommit(kDestUrl); + // Navigate to a cross-site URL (don't swap out to keep |ntp_rfh| alive). + NavigateActiveAndCommit(kDestUrl, true /* dont_swap_out */); TestRenderFrameHost* dest_rfh = contents()->GetMainFrame(); ASSERT_TRUE(dest_rfh); EXPECT_NE(ntp_rfh, dest_rfh); @@ -598,9 +598,8 @@ // The new RVH should be able to update its favicon. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE(dest_rfh->GetRenderViewHost()->GetWidget()->OnMessageReceived( - ViewHostMsg_UpdateFaviconURL( - dest_rfh->GetRenderViewHost()->GetRoutingID(), icons))); + EXPECT_TRUE(dest_rfh->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(dest_rfh->GetRoutingID(), icons))); EXPECT_TRUE(observer.favicon_received()); } @@ -608,17 +607,16 @@ // filtered out and not take effect. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE( - ntp_rvh->GetWidget()->OnMessageReceived(ViewHostMsg_UpdateFaviconURL( - dest_rfh->GetRenderViewHost()->GetRoutingID(), icons))); + EXPECT_TRUE(ntp_rfh->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(ntp_rfh->GetRoutingID(), icons))); EXPECT_FALSE(observer.favicon_received()); } } -// Test that the ViewHostMsg_UpdateFaviconURL IPC message is ignored if the +// Test that the FrameHostMsg_UpdateFaviconURL IPC message is ignored if the // renderer is in the STATE_PENDING_SWAP_OUT_STATE. The favicon code assumes -// that it only gets ViewHostMsg_UpdateFaviconURL messages for the most recently -// committed navigation for each WebContentsImpl. +// that it only gets FrameHostMsg_UpdateFaviconURL messages for the most +// recently committed navigation for each WebContentsImpl. TEST_F(RenderFrameHostManagerTest, UpdateFaviconURLWhilePendingSwapOut) { const GURL kChromeURL("chrome://foo"); const GURL kDestUrl("http://www.google.com/"); @@ -631,9 +629,8 @@ // Send an update favicon message and make sure it works. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE(rfh1->GetRenderViewHost()->GetWidget()->OnMessageReceived( - ViewHostMsg_UpdateFaviconURL(rfh1->GetRenderViewHost()->GetRoutingID(), - icons))); + EXPECT_TRUE(rfh1->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(rfh1->GetRoutingID(), icons))); EXPECT_TRUE(observer.favicon_received()); } @@ -655,9 +652,8 @@ // The new RVH should be able to update its favicons. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE(rfh2->GetRenderViewHost()->GetWidget()->OnMessageReceived( - ViewHostMsg_UpdateFaviconURL(rfh2->GetRenderViewHost()->GetRoutingID(), - icons))); + EXPECT_TRUE(rfh2->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(rfh2->GetRoutingID(), icons))); EXPECT_TRUE(observer.favicon_received()); } @@ -665,9 +661,8 @@ // be ignored. { PluginFaviconMessageObserver observer(contents()); - EXPECT_TRUE(rfh1->GetRenderViewHost()->GetWidget()->OnMessageReceived( - ViewHostMsg_UpdateFaviconURL(rfh1->GetRenderViewHost()->GetRoutingID(), - icons))); + EXPECT_TRUE(rfh1->OnMessageReceived( + FrameHostMsg_UpdateFaviconURL(rfh1->GetRoutingID(), icons))); EXPECT_FALSE(observer.favicon_received()); } }
diff --git a/content/browser/screen_orientation/screen_orientation_browsertest.cc b/content/browser/screen_orientation/screen_orientation_browsertest.cc index 253f167..08c3c6b 100644 --- a/content/browser/screen_orientation/screen_orientation_browsertest.cc +++ b/content/browser/screen_orientation/screen_orientation_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/macros.h" +#include "base/strings/stringprintf.h" #include "build/build_config.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/render_frame_host_impl.h" @@ -355,4 +356,45 @@ } } +#ifdef OS_ANDROID +// This test is disabled because th trybots run in system portrait lock, which +// prevents the test from changing the screen orientation. +IN_PROC_BROWSER_TEST_F(ScreenOrientationOOPIFBrowserTest, + DISABLED_ScreenOrientationLock) { + GURL main_url(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b)")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + WaitForResizeComplete(shell()->web_contents()); + + const char* types[] = {"portrait-primary", "portrait-secondary", + "landscape-primary", "landscape-secondary"}; + + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); + FrameTreeNode* child = root->child_at(0); + RenderFrameHostImpl* frames[] = {root->current_frame_host(), + child->current_frame_host()}; + + EXPECT_TRUE(ExecuteScript(root->current_frame_host(), + "document.body.webkitRequestFullscreen()")); + for (const char* type : types) { + std::string script = + base::StringPrintf("screen.orientation.lock('%s')", type); + EXPECT_TRUE(ExecuteScript(child->current_frame_host(), script)); + + for (auto* frame : frames) { + std::string orientation_type; + while (type != orientation_type) { + EXPECT_TRUE(ExecuteScriptAndExtractString( + frame, + "window.domAutomationController.send(screen.orientation.type)", + &orientation_type)); + } + } + + EXPECT_TRUE(ExecuteScript(child->current_frame_host(), + "screen.orientation.unlock()")); + } +} +#endif // OS_ANDROID + } // namespace content
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index d9681451..ffba46b 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -774,7 +774,6 @@ IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission, OnRequestPpapiBrokerPermission) #endif - IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL) IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage, OnShowValidationMessage) IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage, @@ -829,6 +828,7 @@ IPC_MESSAGE_HANDLER(FrameHostMsg_UpdatePageImportanceSignals, OnUpdatePageImportanceSignals) IPC_MESSAGE_HANDLER(FrameHostMsg_Find_Reply, OnFindReply) + IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateFaviconURL, OnUpdateFaviconURL) #if BUILDFLAG(ENABLE_PLUGINS) IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated, OnPepperInstanceCreated) @@ -1881,6 +1881,12 @@ GetScreenInfo(&screen_info); SendPageMessage(new PageMsg_UpdateScreenInfo(MSG_ROUTING_NONE, screen_info)); + // Send resize message to subframes. + for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) { + if (view != rfh->GetView()) + view->GetRenderWidgetHost()->WasResized(); + } + for (auto& observer : observers_) observer.MainFrameWasResized(width_changed); } @@ -4144,13 +4150,19 @@ #endif // BUILDFLAG(ENABLE_PLUGINS) void WebContentsImpl::OnUpdateFaviconURL( - RenderViewHostImpl* source, + RenderFrameHostImpl* source, const std::vector<FaviconURL>& candidates) { + // Ignore favicons for non-main frame. + if (source->GetParent()) { + NOTREACHED(); + return; + } + // We get updated favicon URLs after the page stops loading. If a cross-site // navigation occurs while a page is still loading, the initial page // may stop loading and send us updated favicon URLs after the navigation // for the new page has committed. - if (!source->is_active()) + if (!source->IsCurrent()) return; for (auto& observer : observers_)
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 85a1cce..6f3dcbd9 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -1122,7 +1122,7 @@ void OnBrowserPluginMessage(RenderFrameHost* render_frame_host, const IPC::Message& message); #endif // BUILDFLAG(ENABLE_PLUGINS) - void OnUpdateFaviconURL(RenderViewHostImpl* source, + void OnUpdateFaviconURL(RenderFrameHostImpl* source, const std::vector<FaviconURL>& candidates); void OnFirstVisuallyNonEmptyPaint(RenderViewHostImpl* source); void OnShowValidationMessage(RenderViewHostImpl* source,
diff --git a/content/browser/webrtc/webrtc_image_capture_browsertest.cc b/content/browser/webrtc/webrtc_image_capture_browsertest.cc index e296fb20..d5641934 100644 --- a/content/browser/webrtc/webrtc_image_capture_browsertest.cc +++ b/content/browser/webrtc/webrtc_image_capture_browsertest.cc
@@ -40,7 +40,7 @@ static struct TargetCamera { bool use_fake; } const kTestParameters[] = {{true}, -#if defined(OS_LINUX) || defined(OS_MACOSX) +#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_ANDROID) {false} #endif };
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 7077b9a..c8b01cb 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -34,6 +34,7 @@ #include "content/public/common/common_param_traits.h" #include "content/public/common/console_message_level.h" #include "content/public/common/context_menu_params.h" +#include "content/public/common/favicon_url.h" #include "content/public/common/file_chooser_file_info.h" #include "content/public/common/file_chooser_params.h" #include "content/public/common/frame_navigate_params.h" @@ -104,6 +105,8 @@ blink::WebFrameOwnerProperties::ScrollingMode::kLast) IPC_ENUM_TRAITS_MAX_VALUE(content::StopFindAction, content::STOP_FIND_ACTION_LAST) +IPC_ENUM_TRAITS_MAX_VALUE(content::FaviconURL::IconType, + content::FaviconURL::IconType::kMax) IPC_ENUM_TRAITS(blink::WebSandboxFlags) // Bitmask. IPC_ENUM_TRAITS_MAX_VALUE(blink::WebTreeScopeType, blink::WebTreeScopeType::kLast) @@ -171,6 +174,12 @@ IPC_STRUCT_TRAITS_MEMBER(link_followed) IPC_STRUCT_TRAITS_END() +IPC_STRUCT_TRAITS_BEGIN(content::FaviconURL) + IPC_STRUCT_TRAITS_MEMBER(icon_url) + IPC_STRUCT_TRAITS_MEMBER(icon_type) + IPC_STRUCT_TRAITS_MEMBER(icon_sizes) +IPC_STRUCT_TRAITS_END() + IPC_STRUCT_TRAITS_BEGIN(content::FrameOwnerProperties) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(scrolling_mode) @@ -1642,6 +1651,10 @@ // FrameMsg_RunFileChooserResponse message. IPC_MESSAGE_ROUTED1(FrameHostMsg_RunFileChooser, content::FileChooserParams) +// Notification that the urls for the favicon of a site has been determined. +IPC_MESSAGE_ROUTED1(FrameHostMsg_UpdateFaviconURL, + std::vector<content::FaviconURL> /* candidates */) + #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) // Message to show/hide a popup menu using native controls.
diff --git a/content/common/view_messages.h b/content/common/view_messages.h index 6b0b28f1..95746c6 100644 --- a/content/common/view_messages.h +++ b/content/common/view_messages.h
@@ -26,7 +26,6 @@ #include "content/common/text_input_state.h" #include "content/common/view_message_enums.h" #include "content/public/common/common_param_traits.h" -#include "content/public/common/favicon_url.h" #include "content/public/common/menu_item.h" #include "content/public/common/page_state.h" #include "content/public/common/page_zoom.h" @@ -94,7 +93,6 @@ blink::WebTextDirection::kWebTextDirectionLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebDisplayMode, blink::WebDisplayMode::kWebDisplayModeLast) -IPC_ENUM_TRAITS(content::FaviconURL::IconType) IPC_ENUM_TRAITS(content::MenuItem::Type) IPC_ENUM_TRAITS_MAX_VALUE(content::NavigationGesture, content::NavigationGestureLast) @@ -208,12 +206,6 @@ IPC_STRUCT_TRAITS_MEMBER(label) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(content::FaviconURL) - IPC_STRUCT_TRAITS_MEMBER(icon_url) - IPC_STRUCT_TRAITS_MEMBER(icon_type) - IPC_STRUCT_TRAITS_MEMBER(icon_sizes) -IPC_STRUCT_TRAITS_END() - IPC_STRUCT_TRAITS_BEGIN(content::RendererPreferences) IPC_STRUCT_TRAITS_MEMBER(can_accept_load_drops) IPC_STRUCT_TRAITS_MEMBER(should_antialias_text) @@ -836,10 +828,6 @@ gfx::Size, /* Size of zoomed image */ cc::SharedBitmapId /* id */) -// Notification that the urls for the favicon of a site has been determined. -IPC_MESSAGE_ROUTED1(ViewHostMsg_UpdateFaviconURL, - std::vector<content::FaviconURL> /* candidates */) - // Message sent from renderer to the browser when the element that is focused // has been touched. A bool is passed in this message which indicates if the // node is editable.
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index 4920ccd..157b26f 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -349,6 +349,7 @@ "java/src/org/chromium/content/browser/SpeechRecognition.java", "java/src/org/chromium/content/browser/TracingControllerAndroid.java", "java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityManager.java", + "java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java", "java/src/org/chromium/content/browser/androidoverlay/DialogOverlayImpl.java", "java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java", "java/src/org/chromium/content/browser/framehost/RenderFrameHostImpl.java",
diff --git a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java index 4adb149..b47aeb6 100644 --- a/content/public/android/java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/androidoverlay/AndroidOverlayProviderImpl.java
@@ -9,6 +9,8 @@ import android.os.HandlerThread; import org.chromium.base.ThreadUtils; +import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.JNINamespace; import org.chromium.media.mojom.AndroidOverlay; import org.chromium.media.mojom.AndroidOverlayClient; import org.chromium.media.mojom.AndroidOverlayConfig; @@ -21,6 +23,7 @@ * Default impl of AndroidOverlayProvider. Creates AndroidOverlayImpls. We're a singleton, in the * sense that all provider clients talk to the same instance in the browser. */ +@JNINamespace("content") public class AndroidOverlayProviderImpl implements AndroidOverlayProvider { private static final String TAG = "AndroidOverlayProvider"; @@ -102,6 +105,12 @@ @Override public void onConnectionError(MojoException e) {} + // Are overlays supported by the embedder? + @CalledByNative + private static boolean areOverlaysSupported() { + return true; + } + /** * Mojo factory. */
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 31b35c1..dbae369 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -22,6 +22,7 @@ visibility = [ "//content/*" ] sources = [ + "android/android_overlay_provider.h", "android/browser_media_player_manager_register.cc", "android/browser_media_player_manager_register.h", "android/compositor.h",
diff --git a/content/public/browser/android/android_overlay_provider.h b/content/public/browser/android/android_overlay_provider.h new file mode 100644 index 0000000..2d5983b --- /dev/null +++ b/content/public/browser/android/android_overlay_provider.h
@@ -0,0 +1,30 @@ +// 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 CONTENT_PUBLIC_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_H_ +#define CONTENT_PUBLIC_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_H_ + +#include "content/common/content_export.h" + +namespace content { + +class CONTENT_EXPORT AndroidOverlayProvider { + public: + /* + * Return the singleton provider instance. + */ + static AndroidOverlayProvider* GetInstance(); + + /** + * Return true if this overlays are supported on this device. + */ + virtual bool AreOverlaysSupported() const = 0; + + protected: + virtual ~AndroidOverlayProvider() {} +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_ANDROID_ANDROID_OVERLAY_PROVIDER_H_
diff --git a/content/public/common/favicon_url.cc b/content/public/common/favicon_url.cc index 80debff6..d727838 100644 --- a/content/public/common/favicon_url.cc +++ b/content/public/common/favicon_url.cc
@@ -6,9 +6,7 @@ namespace content { -FaviconURL::FaviconURL() - : icon_type(INVALID_ICON) { -} +FaviconURL::FaviconURL() : icon_type(IconType::kInvalid) {} FaviconURL::FaviconURL(const GURL& url, IconType type,
diff --git a/content/public/common/favicon_url.h b/content/public/common/favicon_url.h index 349fc878..e9cec54 100644 --- a/content/public/common/favicon_url.h +++ b/content/public/common/favicon_url.h
@@ -17,11 +17,12 @@ struct CONTENT_EXPORT FaviconURL { // The icon type in a page. The definition must be same as // favicon_base::IconType. - enum IconType { - INVALID_ICON = 0x0, - FAVICON = 1 << 0, - TOUCH_ICON = 1 << 1, - TOUCH_PRECOMPOSED_ICON = 1 << 2 + enum class IconType { + kInvalid, + kFavicon, + kTouchIcon, + kTouchPrecomposedIcon, + kMax = kTouchPrecomposedIcon, }; FaviconURL();
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 1195a70..e02b21b 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -79,6 +79,7 @@ #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/context_menu_params.h" +#include "content/public/common/favicon_url.h" #include "content/public/common/file_chooser_file_info.h" #include "content/public/common/file_chooser_params.h" #include "content/public/common/isolated_world_ids.h" @@ -677,6 +678,30 @@ return (time_ticks - base::TimeTicks()).InSecondsF(); } +FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) { + switch (type) { + case blink::WebIconURL::kTypeFavicon: + return FaviconURL::IconType::kFavicon; + case blink::WebIconURL::kTypeTouch: + return FaviconURL::IconType::kTouchIcon; + case blink::WebIconURL::kTypeTouchPrecomposed: + return FaviconURL::IconType::kTouchPrecomposedIcon; + case blink::WebIconURL::kTypeInvalid: + return FaviconURL::IconType::kInvalid; + } + NOTREACHED(); + return FaviconURL::IconType::kInvalid; +} + +std::vector<gfx::Size> ConvertToFaviconSizes( + const blink::WebVector<blink::WebSize>& web_sizes) { + std::vector<gfx::Size> result; + result.reserve(web_sizes.size()); + for (const blink::WebSize& web_size : web_sizes) + result.push_back(gfx::Size(web_size)); + return result; +} + } // namespace // The following methods are outside of the anonymous namespace to ensure that @@ -3789,8 +3814,28 @@ } void RenderFrameImpl::DidChangeIcon(blink::WebIconURL::Type icon_type) { - // TODO(nasko): Investigate wheather implementation should move here. - render_view_->didChangeIcon(frame_, icon_type); + SendUpdateFaviconURL(icon_type); +} + +void RenderFrameImpl::SendUpdateFaviconURL( + blink::WebIconURL::Type icon_types_mask) { + if (frame_->Parent()) + return; + + WebVector<blink::WebIconURL> icon_urls = frame_->IconURLs(icon_types_mask); + if (icon_urls.empty()) + return; + + std::vector<FaviconURL> urls; + urls.reserve(icon_urls.size()); + for (const blink::WebIconURL& icon_url : icon_urls) { + urls.push_back(FaviconURL(icon_url.GetIconURL(), + ToFaviconType(icon_url.IconType()), + ConvertToFaviconSizes(icon_url.Sizes()))); + } + DCHECK_EQ(icon_urls.size(), urls.size()); + + Send(new FrameHostMsg_UpdateFaviconURL(GetRoutingID(), urls)); } void RenderFrameImpl::DidFinishDocumentLoad() { @@ -5045,6 +5090,13 @@ // this state anymore. history_subframe_unique_names_.clear(); + blink::WebIconURL::Type icon_types_mask = + static_cast<blink::WebIconURL::Type>( + blink::WebIconURL::kTypeFavicon | + blink::WebIconURL::kTypeTouchPrecomposed | + blink::WebIconURL::kTypeTouch); + SendUpdateFaviconURL(icon_types_mask); + render_view_->FrameDidStopLoading(frame_); Send(new FrameHostMsg_DidStopLoading(routing_id_)); }
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 60b1cd5f..2e488e0 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -75,6 +75,7 @@ #include "third_party/WebKit/public/web/WebFrameLoadType.h" #include "third_party/WebKit/public/web/WebFrameSerializerClient.h" #include "third_party/WebKit/public/web/WebHistoryCommitType.h" +#include "third_party/WebKit/public/web/WebIconURL.h" #include "third_party/WebKit/public/web/WebMeaningfulLayout.h" #include "third_party/WebKit/public/web/WebScriptExecutionCallback.h" #include "ui/gfx/range/range.h" @@ -1116,6 +1117,8 @@ // Ask the host to send our AndroidOverlay routing token to us. void RequestOverlayRoutingTokenFromHost(); + void SendUpdateFaviconURL(blink::WebIconURL::Type icon_types_mask); + // Stores the WebLocalFrame we are associated with. This is null from the // constructor until BindToWebFrame is called, and it is null after // frameDetached is called until destruction (which is asynchronous in the
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 868a9c16..e5ca796 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -1911,7 +1911,7 @@ "</head>" "</html>"); EXPECT_TRUE(render_thread_->sink().GetFirstMessageMatching( - ViewHostMsg_UpdateFaviconURL::ID)); + FrameHostMsg_UpdateFaviconURL::ID)); render_thread_->sink().ClearMessages(); // An event should not be sent if no favicon url exists. This is an assumption @@ -1921,7 +1921,7 @@ "</head>" "</html>"); EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching( - ViewHostMsg_UpdateFaviconURL::ID)); + FrameHostMsg_UpdateFaviconURL::ID)); } TEST_F(RenderViewImplTest, FocusElementCallsFocusedNodeChanged) {
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 9967866..44f62f7 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -60,7 +60,6 @@ #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" -#include "content/public/common/favicon_url.h" #include "content/public/common/page_importance_signals.h" #include "content/public/common/page_state.h" #include "content/public/common/page_zoom.h" @@ -220,7 +219,6 @@ using blink::WebHistoryItem; using blink::WebHTTPBody; using blink::WebHitTestResult; -using blink::WebIconURL; using blink::WebImage; using blink::WebInputElement; using blink::WebInputEvent; @@ -347,29 +345,6 @@ return DeviceScaleEnsuresTextQuality(device_scale_factor); } -static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) { - switch (type) { - case blink::WebIconURL::kTypeFavicon: - return FaviconURL::FAVICON; - case blink::WebIconURL::kTypeTouch: - return FaviconURL::TOUCH_ICON; - case blink::WebIconURL::kTypeTouchPrecomposed: - return FaviconURL::TOUCH_PRECOMPOSED_ICON; - case blink::WebIconURL::kTypeInvalid: - return FaviconURL::INVALID_ICON; - } - return FaviconURL::INVALID_ICON; -} - -static void ConvertToFaviconSizes( - const blink::WebVector<blink::WebSize>& web_sizes, - std::vector<gfx::Size>* sizes) { - DCHECK(sizes->empty()); - sizes->reserve(web_sizes.size()); - for (size_t i = 0; i < web_sizes.size(); ++i) - sizes->push_back(gfx::Size(web_sizes[i])); -} - /////////////////////////////////////////////////////////////////////////////// namespace { @@ -1549,7 +1524,6 @@ return; frames_in_progress_--; if (frames_in_progress_ == 0) { - DidStopLoadingIcons(); for (auto& observer : observers_) observer.DidStopLoading(); } @@ -1908,22 +1882,6 @@ return has_added_input_handler_; } -void RenderViewImpl::didChangeIcon(WebLocalFrame* frame, - WebIconURL::Type icon_type) { - if (frame->Parent()) - return; - - WebVector<WebIconURL> icon_urls = frame->IconURLs(icon_type); - std::vector<FaviconURL> urls; - for (size_t i = 0; i < icon_urls.size(); i++) { - std::vector<gfx::Size> sizes; - ConvertToFaviconSizes(icon_urls[i].Sizes(), &sizes); - urls.push_back(FaviconURL(icon_urls[i].GetIconURL(), - ToFaviconType(icon_urls[i].IconType()), sizes)); - } - SendUpdateFaviconURL(urls); -} - void RenderViewImpl::CheckPreferredSize() { // We don't always want to send the change messages over IPC, only if we've // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode| @@ -2591,35 +2549,6 @@ observer.DidCommitCompositorFrame(); } -void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) { - if (!urls.empty()) - Send(new ViewHostMsg_UpdateFaviconURL(GetRoutingID(), urls)); -} - -void RenderViewImpl::DidStopLoadingIcons() { - int icon_types = WebIconURL::kTypeFavicon | - WebIconURL::kTypeTouchPrecomposed | WebIconURL::kTypeTouch; - - // Favicons matter only for the top-level frame. If it is a WebRemoteFrame, - // just return early. - if (webview()->MainFrame()->IsWebRemoteFrame()) - return; - - WebVector<WebIconURL> icon_urls = - webview()->MainFrame()->IconURLs(icon_types); - - std::vector<FaviconURL> urls; - for (size_t i = 0; i < icon_urls.size(); i++) { - WebURL url = icon_urls[i].GetIconURL(); - std::vector<gfx::Size> sizes; - ConvertToFaviconSizes(icon_urls[i].Sizes(), &sizes); - if (!url.IsEmpty()) - urls.push_back( - FaviconURL(url, ToFaviconType(icon_urls[i].IconType()), sizes)); - } - SendUpdateFaviconURL(urls); -} - void RenderViewImpl::UpdateWebViewWithDeviceScaleFactor() { if (!webview()) return;
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 3e0a8e7..030950e 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -50,7 +50,6 @@ #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" -#include "third_party/WebKit/public/web/WebIconURL.h" #include "third_party/WebKit/public/web/WebNavigationType.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebViewClient.h" @@ -74,7 +73,6 @@ class WebDataSource; class WebDateTimeChooserCompletion; class WebGestureEvent; -class WebIconURL; class WebMouseEvent; class WebSpeechRecognizer; class WebStorageNamespace; @@ -99,7 +97,6 @@ class RenderViewObserver; class RenderViewTest; class SpeechRecognitionDispatcher; -struct FaviconURL; struct FileChooserParams; struct ResizeParams; @@ -493,8 +490,6 @@ // still live here and are called from RenderFrameImpl. These implementations // are to be moved to RenderFrameImpl <http://crbug.com/361761>. - void didChangeIcon(blink::WebLocalFrame*, blink::WebIconURL::Type); - static Referrer GetReferrerFromRequest( blink::WebFrame* frame, const blink::WebURLRequest& request); @@ -593,13 +588,6 @@ // If |url| is empty, show |fallback_url|. void UpdateTargetURL(const GURL& url, const GURL& fallback_url); - // Tells the browser what the new list of favicons for the webpage is. - void SendUpdateFaviconURL(const std::vector<FaviconURL>& urls); - - // Invoked from DidStopLoading(). Sends the current list of loaded favicons to - // the browser. - void DidStopLoadingIcons(); - // Coordinate conversion ----------------------------------------------------- gfx::RectF ClientRectToPhysicalWindowRect(const gfx::RectF& rect) const;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 406891c..7e1d5393 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1753,6 +1753,7 @@ } if (is_android) { sources += [ + "../browser/android/android_overlay_provider_impl_unittest.cc", "../browser/android/java/gin_java_method_invocation_helper_unittest.cc", "../browser/android/java/java_type_unittest.cc", "../browser/android/java/jni_helper_unittest.cc",
diff --git a/content/test/data/media/image_capture_test.html b/content/test/data/media/image_capture_test.html index ec39281f..3fddb19 100644 --- a/content/test/data/media/image_capture_test.html +++ b/content/test/data/media/image_capture_test.html
@@ -60,7 +60,9 @@ return capturer.grabFrame(); }) .then(imageBitmap => { - assertEquals(WIDTH, imageBitmap.width); + // On Android, depending on the device orientation, |imageBitmap| might + // appear rotated. + assertTrue(WIDTH == imageBitmap.width || WIDTH == imageBitmap.height); reportTestSuccess(); })
diff --git a/docs/threading_and_tasks.md b/docs/threading_and_tasks.md index a61973011..befa534 100644 --- a/docs/threading_and_tasks.md +++ b/docs/threading_and_tasks.md
@@ -48,7 +48,26 @@ * [COM Single Threaded](#Posting-Tasks-to-a-COM-Single-Thread-Apartment-STA_Thread-Windows_): A variant of single threaded with COM initialized. -The discussion below covers all of these ways to execute tasks. +### Prefer Sequences to Threads + +**Sequenced execution mode is far prefered to Single Threaded** in scenarios +that require mere thread-safety as it opens up scheduling paradigms that +wouldn't be possible otherwise (sequences can hop threads instead of being stuck +behind unrelated work on a dedicated thread). Ability to hop threads also means +the thread count can dynamically adapt to the machine's true resource +availability (faster on bigger machines, avoids trashing on slower machines). + +Many core APIs were recently made sequence-friendly (classes are rarely +thread-affine -- i.e. only when using thread-local-storage or third-party APIs +that do). But the codebase has long evolved assuming single-threaded contexts... +If your class could run on a sequence but is blocked by an overzealous use of +ThreadChecker/ThreadTaskRunnerHandle/SingleThreadTaskRunner in a leaf +dependency, consider fixing that dependency for everyone's benefit (or at the +very least file a blocking bug against https://crbug.com/675631 and flag your +use of base::CreateSingleThreadTaskRunnerWithTraits() with a TODO against your +bug to use base::CreateSequencedTaskRunnerWithTraits() when fixed). + +The discussion below covers all of these ways to execute tasks in details. ## Posting a Parallel Task
diff --git a/extensions/browser/api/cast_channel/cast_channel_api.cc b/extensions/browser/api/cast_channel/cast_channel_api.cc index b645aed..5e5c4b6 100644 --- a/extensions/browser/api/cast_channel/cast_channel_api.cc +++ b/extensions/browser/api/cast_channel/cast_channel_api.cc
@@ -178,8 +178,8 @@ bool CastChannelAsyncApiFunction::PrePrepare() { cast_socket_service_ = - api::cast_channel::CastSocketServiceFactory::GetInstance() - ->GetForBrowserContext(browser_context()); + api::cast_channel::CastSocketServiceFactory::GetForBrowserContext( + browser_context()); DCHECK(cast_socket_service_); return true; } @@ -188,27 +188,6 @@ return GetError().empty(); } -CastSocket* CastChannelAsyncApiFunction::GetSocketOrCompleteWithError( - int channel_id) { - CastSocket* socket = GetSocket(channel_id); - if (!socket) { - SetResultFromError(channel_id, - cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID); - AsyncWorkCompleted(); - } - return socket; -} - -int CastChannelAsyncApiFunction::AddSocket(std::unique_ptr<CastSocket> socket) { - auto* sockets = cast_socket_service_->GetOrCreateSocketRegistry(); - return sockets->AddSocket(std::move(socket)); -} - -void CastChannelAsyncApiFunction::RemoveSocket(int channel_id) { - auto* sockets = cast_socket_service_->GetOrCreateSocketRegistry(); - sockets->RemoveSocket(channel_id); -} - void CastChannelAsyncApiFunction::SetResultFromSocket( const CastSocket& socket) { ChannelInfo channel_info; @@ -235,11 +214,6 @@ SetError("Channel error = " + base::IntToString(error)); } -CastSocket* CastChannelAsyncApiFunction::GetSocket(int channel_id) const { - auto* sockets = cast_socket_service_->GetOrCreateSocketRegistry(); - return sockets->GetSocket(channel_id); -} - void CastChannelAsyncApiFunction::SetResultFromChannelInfo( const ChannelInfo& channel_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -324,7 +298,7 @@ connect_info.capabilities.get() ? *connect_info.capabilities : CastDeviceCapability::NONE); } - new_channel_id_ = AddSocket(base::WrapUnique(socket)); + new_channel_id_ = cast_socket_service_->AddSocket(base::WrapUnique(socket)); // Construct read delegates. std::unique_ptr<CastTransport::Delegate> delegate( @@ -357,7 +331,7 @@ // rather than relying on the extension to call close(). This can be done by // calling RemoveSocket() and api_->GetLogger()->ClearLastErrors(channel_id). if (result != ChannelError::UNKNOWN) { - CastSocket* socket = GetSocket(new_channel_id_); + CastSocket* socket = cast_socket_service_->GetSocket(new_channel_id_); CHECK(socket); SetResultFromSocket(*socket); } else { @@ -399,7 +373,8 @@ } void CastChannelSendFunction::AsyncWorkStart() { - CastSocket* socket = GetSocket(params_->channel.channel_id); + CastSocket* socket = + cast_socket_service_->GetSocket(params_->channel.channel_id); if (!socket) { SetResultFromError(params_->channel.channel_id, cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID); @@ -420,7 +395,7 @@ void CastChannelSendFunction::OnSend(int result) { DCHECK_CURRENTLY_ON(BrowserThread::IO); int channel_id = params_->channel.channel_id; - CastSocket* socket = GetSocket(channel_id); + CastSocket* socket = cast_socket_service_->GetSocket(channel_id); if (result < 0 || !socket) { SetResultFromError(channel_id, cast_channel::CHANNEL_ERROR_SOCKET_ERROR); @@ -446,7 +421,8 @@ } void CastChannelCloseFunction::AsyncWorkStart() { - CastSocket* socket = GetSocket(params_->channel.channel_id); + CastSocket* socket = + cast_socket_service_->GetSocket(params_->channel.channel_id); if (!socket) { SetResultFromError(params_->channel.channel_id, cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID); @@ -460,14 +436,14 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); VLOG(1) << "CastChannelCloseFunction::OnClose result = " << result; int channel_id = params_->channel.channel_id; - CastSocket* socket = GetSocket(channel_id); + CastSocket* socket = cast_socket_service_->GetSocket(channel_id); if (result < 0 || !socket) { SetResultFromError(channel_id, cast_channel::CHANNEL_ERROR_SOCKET_ERROR); } else { SetResultFromSocket(*socket); // This will delete |socket|. - RemoveSocket(channel_id); + cast_socket_service_->RemoveSocket(channel_id); api_->GetLogger()->ClearLastErrors(channel_id); } AsyncWorkCompleted();
diff --git a/extensions/browser/api/cast_channel/cast_channel_api.h b/extensions/browser/api/cast_channel/cast_channel_api.h index b97faea1..21db4b45 100644 --- a/extensions/browser/api/cast_channel/cast_channel_api.h +++ b/extensions/browser/api/cast_channel/cast_channel_api.h
@@ -110,19 +110,6 @@ bool PrePrepare() override; bool Respond() override; - // Returns the socket corresponding to |channel_id| if one exists. Otherwise, - // sets the function result with CHANNEL_ERROR_INVALID_CHANNEL_ID, completes - // the function, and returns null. - cast_channel::CastSocket* GetSocketOrCompleteWithError(int channel_id); - - // Adds |socket| to |manager_| and returns the new channel_id. |manager_| - // assumes ownership of |socket|. - int AddSocket(std::unique_ptr<cast_channel::CastSocket> socket); - - // Removes the CastSocket corresponding to |channel_id| from the resource - // manager. - void RemoveSocket(int channel_id); - // Sets the function result to a ChannelInfo obtained from the state of // |socket|. void SetResultFromSocket(const cast_channel::CastSocket& socket); @@ -131,16 +118,12 @@ // |error|. void SetResultFromError(int channel_id, cast_channel::ChannelError error); - // Returns the socket corresponding to |channel_id| if one exists, or null - // otherwise. - cast_channel::CastSocket* GetSocket(int channel_id) const; + // Manages creating and removing Cast sockets. + scoped_refptr<api::cast_channel::CastSocketService> cast_socket_service_; private: // Sets the function result from |channel_info|. void SetResultFromChannelInfo(const cast_channel::ChannelInfo& channel_info); - - // Manages creating and removing cast sockets. - api::cast_channel::CastSocketService* cast_socket_service_; }; class CastChannelOpenFunction : public CastChannelAsyncApiFunction {
diff --git a/extensions/browser/api/cast_channel/cast_socket_service.cc b/extensions/browser/api/cast_channel/cast_socket_service.cc index bbf05422..e6fc923 100644 --- a/extensions/browser/api/cast_channel/cast_socket_service.cc +++ b/extensions/browser/api/cast_channel/cast_socket_service.cc
@@ -5,20 +5,27 @@ #include "extensions/browser/api/cast_channel/cast_socket_service.h" #include "base/memory/ptr_util.h" +#include "content/public/browser/browser_thread.h" + +using content::BrowserThread; namespace extensions { namespace api { namespace cast_channel { -int CastSocketRegistry::last_channel_id_ = 0; +int CastSocketService::last_channel_id_ = 0; -CastSocketRegistry::CastSocketRegistry() = default; +CastSocketService::CastSocketService() + : RefcountedKeyedService( + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)) { + DETACH_FROM_THREAD(thread_checker_); +} -CastSocketRegistry::~CastSocketRegistry() { +CastSocketService::~CastSocketService() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); } -int CastSocketRegistry::AddSocket(std::unique_ptr<CastSocket> socket) { +int CastSocketService::AddSocket(std::unique_ptr<CastSocket> socket) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(socket); int id = ++last_channel_id_; @@ -27,7 +34,7 @@ return id; } -std::unique_ptr<CastSocket> CastSocketRegistry::RemoveSocket(int channel_id) { +std::unique_ptr<CastSocket> CastSocketService::RemoveSocket(int channel_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(channel_id > 0); auto socket_it = sockets_.find(channel_id); @@ -40,22 +47,14 @@ return socket; } -CastSocket* CastSocketRegistry::GetSocket(int channel_id) const { +CastSocket* CastSocketService::GetSocket(int channel_id) const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(channel_id > 0); const auto& socket_it = sockets_.find(channel_id); return socket_it == sockets_.end() ? nullptr : socket_it->second.get(); } -CastSocketService::CastSocketService() = default; -CastSocketService::~CastSocketService() = default; - -CastSocketRegistry* CastSocketService::GetOrCreateSocketRegistry() { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - if (!sockets_) - sockets_.reset(new CastSocketRegistry()); - return sockets_.get(); -} +void CastSocketService::ShutdownOnUIThread() {} } // namespace cast_channel } // namespace api
diff --git a/extensions/browser/api/cast_channel/cast_socket_service.h b/extensions/browser/api/cast_channel/cast_socket_service.h index 6765c15..13b1887 100644 --- a/extensions/browser/api/cast_channel/cast_socket_service.h +++ b/extensions/browser/api/cast_channel/cast_socket_service.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/threading/thread_checker.h" -#include "components/keyed_service/core/keyed_service.h" +#include "components/keyed_service/core/refcounted_keyed_service.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/cast_channel/cast_socket.h" @@ -20,11 +20,11 @@ // This class adds, removes, and returns cast sockets created by CastChannelAPI // to underlying storage. -// This class is not thread safe. All methods must be called from the IO thread. -class CastSocketRegistry { +// Instance of this class is created on the UI thread and destroyed on the IO +// thread. All public API must be called from the IO thread. +class CastSocketService : public RefcountedKeyedService { public: - CastSocketRegistry(); - ~CastSocketRegistry(); + CastSocketService(); // Adds |socket| to |sockets_| and returns the new channel_id. Takes ownership // of |socket|. @@ -39,6 +39,11 @@ CastSocket* GetSocket(int channel_id) const; private: + ~CastSocketService() override; + + // RefcountedKeyedService implementation. + void ShutdownOnUIThread() override; + // Used to generate CastSocket id. static int last_channel_id_; @@ -47,26 +52,6 @@ THREAD_CHECKER(thread_checker_); - DISALLOW_COPY_AND_ASSIGN(CastSocketRegistry); -}; - -// This class associates underlying CastSocketRegistry instance with -// BrowserContext and makes sure CastSocketRegistry instance is created and -// destroyed on the IO thread. -// Instance of this class is created and destroyed on the UI thread. -class CastSocketService : public KeyedService { - public: - CastSocketService(); - ~CastSocketService() override; - - // Creates CastSocketRegistry instance if none exists. Should be called on the - // IO thread. - CastSocketRegistry* GetOrCreateSocketRegistry(); - - private: - std::unique_ptr<CastSocketRegistry, content::BrowserThread::DeleteOnIOThread> - sockets_; - DISALLOW_COPY_AND_ASSIGN(CastSocketService); };
diff --git a/extensions/browser/api/cast_channel/cast_socket_service_factory.cc b/extensions/browser/api/cast_channel/cast_socket_service_factory.cc index cb062a0..88e1893 100644 --- a/extensions/browser/api/cast_channel/cast_socket_service_factory.cc +++ b/extensions/browser/api/cast_channel/cast_socket_service_factory.cc
@@ -20,13 +20,13 @@ } // namespace // static -CastSocketService* CastSocketServiceFactory::GetForBrowserContext( +scoped_refptr<CastSocketService> CastSocketServiceFactory::GetForBrowserContext( BrowserContext* context) { DCHECK(context); // GetServiceForBrowserContext returns a KeyedService hence the static_cast<> - // to return a pointer to CastSocketService. + // to construct a temporary scoped_refptr on the stack for the return value. return static_cast<CastSocketService*>( - service_factory.Get().GetServiceForBrowserContext(context, true)); + service_factory.Get().GetServiceForBrowserContext(context, true).get()); } // static @@ -35,7 +35,7 @@ } CastSocketServiceFactory::CastSocketServiceFactory() - : BrowserContextKeyedServiceFactory( + : RefcountedBrowserContextKeyedServiceFactory( "CastSocketService", BrowserContextDependencyManager::GetInstance()) {} @@ -46,9 +46,10 @@ return context; } -KeyedService* CastSocketServiceFactory::BuildServiceInstanceFor( +scoped_refptr<RefcountedKeyedService> +CastSocketServiceFactory::BuildServiceInstanceFor( BrowserContext* context) const { - return new CastSocketService(); + return make_scoped_refptr(new CastSocketService()); } } // namespace cast_channel
diff --git a/extensions/browser/api/cast_channel/cast_socket_service_factory.h b/extensions/browser/api/cast_channel/cast_socket_service_factory.h index e9e3348eb..32b44a2f 100644 --- a/extensions/browser/api/cast_channel/cast_socket_service_factory.h +++ b/extensions/browser/api/cast_channel/cast_socket_service_factory.h
@@ -7,7 +7,7 @@ #include "base/lazy_instance.h" #include "base/macros.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/content/refcounted_browser_context_keyed_service_factory.h" namespace extensions { namespace api { @@ -17,11 +17,12 @@ // TODO(crbug.com/725717): CastSocket created by one profile (browser context) // could be shared with other profiles. -class CastSocketServiceFactory : public BrowserContextKeyedServiceFactory { +class CastSocketServiceFactory + : public RefcountedBrowserContextKeyedServiceFactory { public: // Caller needs to make sure that it passes in the same |context| instance to // this function for both normal profile and incognito profile. - static CastSocketService* GetForBrowserContext( + static scoped_refptr<CastSocketService> GetForBrowserContext( content::BrowserContext* context); static CastSocketServiceFactory* GetInstance(); @@ -36,7 +37,7 @@ content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; - KeyedService* BuildServiceInstanceFor( + scoped_refptr<RefcountedKeyedService> BuildServiceInstanceFor( content::BrowserContext* context) const override; DISALLOW_COPY_AND_ASSIGN(CastSocketServiceFactory);
diff --git a/extensions/browser/api/cast_channel/cast_socket_service_unittest.cc b/extensions/browser/api/cast_channel/cast_socket_service_unittest.cc index 08e2e08..1ac4b76 100644 --- a/extensions/browser/api/cast_channel/cast_socket_service_unittest.cc +++ b/extensions/browser/api/cast_channel/cast_socket_service_unittest.cc
@@ -18,21 +18,20 @@ class CastSocketServiceTest : public testing::Test { public: CastSocketServiceTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {} + : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + cast_socket_service_(new CastSocketService()) {} protected: content::TestBrowserThreadBundle thread_bundle_; - CastSocketService cast_socket_service_; + scoped_refptr<CastSocketService> cast_socket_service_; }; TEST_F(CastSocketServiceTest, TestAddSocket) { - auto* registry = cast_socket_service_.GetOrCreateSocketRegistry(); - int channel_id_1 = 0; auto socket1 = base::MakeUnique<MockCastSocket>(); EXPECT_CALL(*socket1, set_id(_)).WillOnce(SaveArg<0>(&channel_id_1)); - int channel_id = registry->AddSocket(std::move(socket1)); + int channel_id = cast_socket_service_->AddSocket(std::move(socket1)); EXPECT_EQ(channel_id_1, channel_id); EXPECT_NE(0, channel_id_1); @@ -41,38 +40,37 @@ EXPECT_CALL(*socket2, set_id(_)).WillOnce(SaveArg<0>(&channel_id_2)); auto* socket_ptr = socket2.get(); - channel_id = registry->AddSocket(std::move(socket2)); + channel_id = cast_socket_service_->AddSocket(std::move(socket2)); EXPECT_EQ(channel_id_2, channel_id); EXPECT_NE(channel_id_1, channel_id_2); - auto removed_socket = registry->RemoveSocket(channel_id); + auto removed_socket = cast_socket_service_->RemoveSocket(channel_id); EXPECT_EQ(socket_ptr, removed_socket.get()); int channel_id_3 = 0; auto socket3 = base::MakeUnique<MockCastSocket>(); EXPECT_CALL(*socket3, set_id(_)).WillOnce(SaveArg<0>(&channel_id_3)); - channel_id = registry->AddSocket(std::move(socket3)); + channel_id = cast_socket_service_->AddSocket(std::move(socket3)); EXPECT_EQ(channel_id_3, channel_id); EXPECT_NE(channel_id_1, channel_id_3); EXPECT_NE(channel_id_2, channel_id_3); } TEST_F(CastSocketServiceTest, TestRemoveAndGetSocket) { - auto* registry = cast_socket_service_.GetOrCreateSocketRegistry(); int channel_id = 1; - auto* socket_ptr = registry->GetSocket(channel_id); + auto* socket_ptr = cast_socket_service_->GetSocket(channel_id); EXPECT_FALSE(socket_ptr); - auto socket = registry->RemoveSocket(channel_id); + auto socket = cast_socket_service_->RemoveSocket(channel_id); EXPECT_FALSE(socket); auto mock_socket = base::MakeUnique<MockCastSocket>(); EXPECT_CALL(*mock_socket, set_id(_)); auto* mock_socket_ptr = mock_socket.get(); - channel_id = registry->AddSocket(std::move(mock_socket)); - EXPECT_EQ(mock_socket_ptr, registry->GetSocket(channel_id)); - socket = registry->RemoveSocket(channel_id); + channel_id = cast_socket_service_->AddSocket(std::move(mock_socket)); + EXPECT_EQ(mock_socket_ptr, cast_socket_service_->GetSocket(channel_id)); + socket = cast_socket_service_->RemoveSocket(channel_id); EXPECT_TRUE(socket); }
diff --git a/extensions/browser/event_listener_map.cc b/extensions/browser/event_listener_map.cc index 89855e3..b60e5bf 100644 --- a/extensions/browser/event_listener_map.cc +++ b/extensions/browser/event_listener_map.cc
@@ -12,6 +12,7 @@ #include "base/values.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/event_router.h" +#include "extensions/common/constants.h" #include "ipc/ipc_message.h" #include "url/gurl.h" #include "url/origin.h" @@ -29,7 +30,8 @@ content::RenderProcessHost* process, std::unique_ptr<base::DictionaryValue> filter) { return base::WrapUnique(new EventListener(event_name, extension_id, GURL(), - process, std::move(filter))); + process, kNonWorkerThreadId, + std::move(filter))); } // static @@ -42,9 +44,20 @@ // for chrome://settings/accounts, to avoid multiple events being triggered // for the same process. See crbug.com/536858 for details. // TODO(devlin): If // we dispatched events to processes more intelligently this could be avoided. - return base::WrapUnique(new EventListener(event_name, "", - url::Origin(listener_url).GetURL(), - process, std::move(filter))); + return base::WrapUnique(new EventListener( + event_name, ExtensionId(), url::Origin(listener_url).GetURL(), process, + kNonWorkerThreadId, std::move(filter))); +} + +std::unique_ptr<EventListener> EventListener::ForExtensionServiceWorker( + const std::string& event_name, + const std::string& extension_id, + content::RenderProcessHost* process, + int worker_thread_id, + std::unique_ptr<base::DictionaryValue> filter) { + return base::WrapUnique(new EventListener(event_name, extension_id, GURL(), + process, worker_thread_id, + std::move(filter))); } EventListener::~EventListener() {} @@ -56,6 +69,7 @@ return event_name_ == other->event_name_ && extension_id_ == other->extension_id_ && listener_url_ == other->listener_url_ && process_ == other->process_ && + worker_thread_id_ == other->worker_thread_id_ && ((!!filter_.get()) == (!!other->filter_.get())) && (!filter_.get() || filter_->Equals(other->filter_.get())); } @@ -64,16 +78,21 @@ std::unique_ptr<DictionaryValue> filter_copy; if (filter_) filter_copy = filter_->CreateDeepCopy(); - return base::WrapUnique(new EventListener(event_name_, extension_id_, - listener_url_, process_, - std::move(filter_copy))); + return base::WrapUnique( + new EventListener(event_name_, extension_id_, listener_url_, process_, + worker_thread_id_, std::move(filter_copy))); } bool EventListener::IsLazy() const { return !process_; } +bool EventListener::IsForServiceWorker() const { + return worker_thread_id_ != kNonWorkerThreadId; +} + void EventListener::MakeLazy() { + DCHECK_EQ(worker_thread_id_, kNonWorkerThreadId); process_ = nullptr; } @@ -85,11 +104,13 @@ const std::string& extension_id, const GURL& listener_url, content::RenderProcessHost* process, + int worker_thread_id, std::unique_ptr<DictionaryValue> filter) : event_name_(event_name), extension_id_(extension_id), listener_url_(listener_url), process_(process), + worker_thread_id_(worker_thread_id), filter_(std::move(filter)), matcher_id_(-1) {} @@ -174,12 +195,15 @@ bool EventListenerMap::HasProcessListener( content::RenderProcessHost* process, + int worker_thread_id, const std::string& extension_id) const { for (const auto& it : listeners_) { for (const auto& listener : it.second) { if (listener->process() == process && - listener->extension_id() == extension_id) + listener->extension_id() == extension_id && + listener->worker_thread_id() == worker_thread_id) { return true; + } } } return false; @@ -224,6 +248,8 @@ const DictionaryValue* filter = nullptr; if (!filter_list->GetDictionary(i, &filter)) continue; + // Currently this is only used for lazy background page events. + // TODO(lazyboy): Add extension SW lazy events. AddListener( EventListener::ForExtension(it.key(), extension_id, nullptr, base::WrapUnique(filter->DeepCopy())));
diff --git a/extensions/browser/event_listener_map.h b/extensions/browser/event_listener_map.h index cd694ac..ea25ea6 100644 --- a/extensions/browser/event_listener_map.h +++ b/extensions/browser/event_listener_map.h
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "extensions/common/event_filter.h" +#include "extensions/common/extension_id.h" #include "url/gurl.h" namespace base { @@ -58,6 +59,16 @@ const GURL& listener_url, content::RenderProcessHost* process, std::unique_ptr<base::DictionaryValue> filter); + // Constructs EventListener for an Extension service worker. + // Similar to ForExtension above with the only difference that + // |worker_thread_id_| contains a valid worker thread, as opposed to + // kNonWorkerThreadId. + static std::unique_ptr<EventListener> ForExtensionServiceWorker( + const std::string& event_name, + const std::string& extension_id, + content::RenderProcessHost* process, + int worker_thread_id, + std::unique_ptr<base::DictionaryValue> filter); ~EventListener(); @@ -65,9 +76,14 @@ std::unique_ptr<EventListener> Copy() const; - // Returns true in the case of a lazy background page, and thus no process. + // Returns true if the listener is for a lazy context: e.g. a background page + // or an extension service worker. This listener does not have |process_|. bool IsLazy() const; + // Returns true if this listener was registered for an extension service + // worker. + bool IsForServiceWorker() const; + // Modifies this listener to be a lazy listener, clearing process references. void MakeLazy(); @@ -82,18 +98,21 @@ base::DictionaryValue* filter() const { return filter_.get(); } EventFilter::MatcherID matcher_id() const { return matcher_id_; } void set_matcher_id(EventFilter::MatcherID id) { matcher_id_ = id; } + int worker_thread_id() const { return worker_thread_id_; } private: EventListener(const std::string& event_name, const std::string& extension_id, const GURL& listener_url, content::RenderProcessHost* process, + int worker_thread_id, std::unique_ptr<base::DictionaryValue> filter); const std::string event_name_; const std::string extension_id_; const GURL listener_url_; content::RenderProcessHost* process_; + const int worker_thread_id_; std::unique_ptr<base::DictionaryValue> filter_; EventFilter::MatcherID matcher_id_; // -1 if unset. @@ -150,7 +169,10 @@ bool HasListener(const EventListener* listener) const; // Returns true if there is a listener for |extension_id| in |process|. + // |worker_thread_id| is the thread id of the service worker the listener is + // for, or kNonWorkerThreadId if the listener is not for a service worker. bool HasProcessListener(content::RenderProcessHost* process, + int worker_thread_id, const std::string& extension_id) const; // Removes any listeners that |extension_id| has added, both lazy and regular.
diff --git a/extensions/browser/event_router.cc b/extensions/browser/event_router.cc index 96faf6c..74d623a 100644 --- a/extensions/browser/event_router.cc +++ b/extensions/browser/event_router.cc
@@ -68,10 +68,13 @@ } // namespace -const char EventRouter::kRegisteredEvents[] = "events"; +const char EventRouter::kRegisteredLazyEvents[] = "events"; +const char EventRouter::kRegisteredServiceWorkerEvents[] = + "serviceworkerevents"; // static void EventRouter::DispatchExtensionMessage(IPC::Sender* ipc_sender, + int worker_thread_id, void* browser_context_id, const std::string& extension_id, int event_id, @@ -83,6 +86,7 @@ *event_args); ExtensionMsg_DispatchEvent_Params params; + params.worker_thread_id = worker_thread_id; params.extension_id = extension_id; params.event_name = event_name; params.event_id = event_id; @@ -128,7 +132,10 @@ event_name)); } - DispatchExtensionMessage(ipc_sender, browser_context_id, extension_id, + DispatchExtensionMessage(ipc_sender, + // TODO(lazyboy): |kNonWorkerThreadId| means these + // will not work for extension SW. + kNonWorkerThreadId, browser_context_id, extension_id, event_id, event_name, event_args.get(), user_gesture, info); } @@ -151,30 +158,50 @@ void EventRouter::AddEventListener(const std::string& event_name, content::RenderProcessHost* process, const std::string& extension_id) { - listeners_.AddListener(EventListener::ForExtension( - event_name, extension_id, process, std::unique_ptr<DictionaryValue>())); + listeners_.AddListener( + EventListener::ForExtension(event_name, extension_id, process, nullptr)); +} + +void EventRouter::AddServiceWorkerEventListener( + const std::string& event_name, + content::RenderProcessHost* process, + const ExtensionId& extension_id, + int worker_thread_id) { + listeners_.AddListener(EventListener::ForExtensionServiceWorker( + event_name, extension_id, process, worker_thread_id, nullptr)); } void EventRouter::RemoveEventListener(const std::string& event_name, content::RenderProcessHost* process, const std::string& extension_id) { - std::unique_ptr<EventListener> listener = EventListener::ForExtension( - event_name, extension_id, process, std::unique_ptr<DictionaryValue>()); + std::unique_ptr<EventListener> listener = + EventListener::ForExtension(event_name, extension_id, process, nullptr); + listeners_.RemoveListener(listener.get()); +} + +void EventRouter::RemoveServiceWorkerEventListener( + const std::string& event_name, + content::RenderProcessHost* process, + const ExtensionId& extension_id, + int worker_thread_id) { + std::unique_ptr<EventListener> listener = + EventListener::ForExtensionServiceWorker( + event_name, extension_id, process, worker_thread_id, nullptr); listeners_.RemoveListener(listener.get()); } void EventRouter::AddEventListenerForURL(const std::string& event_name, content::RenderProcessHost* process, const GURL& listener_url) { - listeners_.AddListener(EventListener::ForURL( - event_name, listener_url, process, std::unique_ptr<DictionaryValue>())); + listeners_.AddListener( + EventListener::ForURL(event_name, listener_url, process, nullptr)); } void EventRouter::RemoveEventListenerForURL(const std::string& event_name, content::RenderProcessHost* process, const GURL& listener_url) { - std::unique_ptr<EventListener> listener = EventListener::ForURL( - event_name, listener_url, process, std::unique_ptr<DictionaryValue>()); + std::unique_ptr<EventListener> listener = + EventListener::ForURL(event_name, listener_url, process, nullptr); listeners_.RemoveListener(listener.get()); } @@ -238,32 +265,30 @@ } void EventRouter::AddLazyEventListener(const std::string& event_name, - const std::string& extension_id) { - bool is_new = listeners_.AddListener(EventListener::ForExtension( - event_name, extension_id, NULL, std::unique_ptr<DictionaryValue>())); - - if (is_new) { - std::set<std::string> events = GetRegisteredEvents(extension_id); - bool prefs_is_new = events.insert(event_name).second; - if (prefs_is_new) - SetRegisteredEvents(extension_id, events); - } + const ExtensionId& extension_id) { + AddLazyEventListenerImpl(event_name, extension_id, kNonWorkerThreadId); } void EventRouter::RemoveLazyEventListener(const std::string& event_name, - const std::string& extension_id) { - std::unique_ptr<EventListener> listener = EventListener::ForExtension( - event_name, extension_id, NULL, std::unique_ptr<DictionaryValue>()); - bool did_exist = listeners_.RemoveListener(listener.get()); - - if (did_exist) { - std::set<std::string> events = GetRegisteredEvents(extension_id); - bool prefs_did_exist = events.erase(event_name) > 0; - DCHECK(prefs_did_exist); - SetRegisteredEvents(extension_id, events); - } + const ExtensionId& extension_id) { + RemoveLazyEventListenerImpl(event_name, extension_id, kNonWorkerThreadId); } +void EventRouter::AddLazyServiceWorkerEventListener( + const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id) { + AddLazyEventListenerImpl(event_name, extension_id, worker_thread_id); +} + +void EventRouter::RemoveLazyServiceWorkerEventListener( + const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id) { + RemoveLazyEventListenerImpl(event_name, extension_id, worker_thread_id); +} + +// TODO(lazyboy): Support filters for extension SW events. void EventRouter::AddFilteredEventListener(const std::string& event_name, content::RenderProcessHost* process, const std::string& extension_id, @@ -283,6 +308,7 @@ AddFilterToEvent(event_name, extension_id, &filter); } +// TODO(lazyboy): Support filters for extension SW events. void EventRouter::RemoveFilteredEventListener( const std::string& event_name, content::RenderProcessHost* process, @@ -315,13 +341,16 @@ } std::set<std::string> EventRouter::GetRegisteredEvents( - const std::string& extension_id) const { + const std::string& extension_id, + RegisteredEventType type) const { std::set<std::string> events; const ListValue* events_value = NULL; - if (!extension_prefs_ || - !extension_prefs_->ReadPrefAsList( - extension_id, kRegisteredEvents, &events_value)) { + const char* pref_key = type == RegisteredEventType::kLazy + ? kRegisteredLazyEvents + : kRegisteredServiceWorkerEvents; + if (!extension_prefs_ || !extension_prefs_->ReadPrefAsList( + extension_id, pref_key, &events_value)) { return events; } @@ -333,6 +362,14 @@ return events; } +void EventRouter::ClearRegisteredEventsForTest( + const ExtensionId& extension_id) { + SetRegisteredEvents(extension_id, std::set<std::string>(), + RegisteredEventType::kLazy); + SetRegisteredEvents(extension_id, std::set<std::string>(), + RegisteredEventType::kServiceWorker); +} + void EventRouter::RemoveFilterFromEvent(const std::string& event_name, const std::string& extension_id, const DictionaryValue* filter) { @@ -391,7 +428,6 @@ DCHECK(!event->restrict_to_browser_context || ExtensionsBrowserClient::Get()->IsSameContext( browser_context_, event->restrict_to_browser_context)); - std::set<const EventListener*> listeners( listeners_.GetEventListeners(*event)); @@ -406,7 +442,8 @@ for (const EventListener* listener : listeners) { if (restrict_to_extension_id.empty() || restrict_to_extension_id == listener->extension_id()) { - if (listener->IsLazy()) { + // TODO(lazyboy): Support lazy listeners for extension SW events. + if (listener->IsLazy() && !listener->IsForServiceWorker()) { DispatchLazyEvent(listener->extension_id(), event, &already_dispatched, listener->filter()); } @@ -418,12 +455,13 @@ restrict_to_extension_id == listener->extension_id()) { if (listener->process()) { EventDispatchIdentifier dispatch_id(listener->GetBrowserContext(), - listener->extension_id()); + listener->extension_id(), + listener->worker_thread_id()); if (!base::ContainsKey(already_dispatched, dispatch_id)) { DispatchEventToProcess(listener->extension_id(), listener->listener_url(), listener->process(), - event, listener->filter(), - false /* did_enqueue */); + listener->worker_thread_id(), event, + listener->filter(), false /* did_enqueue */); } } } @@ -446,7 +484,8 @@ if (MaybeLoadLazyBackgroundPageToDispatchEvent(browser_context_, extension, event, listener_filter)) { - already_dispatched->insert(std::make_pair(browser_context_, extension_id)); + already_dispatched->insert( + std::make_tuple(browser_context_, extension_id, kNonWorkerThreadId)); } ExtensionsBrowserClient* browser_client = ExtensionsBrowserClient::Get(); @@ -457,7 +496,7 @@ if (MaybeLoadLazyBackgroundPageToDispatchEvent(incognito_context, extension, event, listener_filter)) { already_dispatched->insert( - std::make_pair(incognito_context, extension_id)); + std::make_tuple(incognito_context, extension_id, kNonWorkerThreadId)); } } } @@ -466,6 +505,7 @@ const std::string& extension_id, const GURL& listener_url, content::RenderProcessHost* process, + int worker_thread_id, const linked_ptr<Event>& event, const base::DictionaryValue* listener_filter, bool did_enqueue) { @@ -533,9 +573,10 @@ } int event_id = g_extension_event_id.GetNext(); - DispatchExtensionMessage(process, listener_context, extension_id, event_id, - event->event_name, event->event_args.get(), - event->user_gesture, event->filter_info); + DispatchExtensionMessage(process, worker_thread_id, listener_context, + extension_id, event_id, event->event_name, + event->event_args.get(), event->user_gesture, + event->filter_info); if (extension) { ReportEvent(event->histogram_value, extension, did_enqueue); @@ -706,21 +747,26 @@ return; if (listeners_.HasProcessListener(host->render_process_host(), + kNonWorkerThreadId, host->extension()->id())) { DispatchEventToProcess(host->extension()->id(), host->GetURL(), - host->render_process_host(), event, nullptr, - true /* did_enqueue */); + host->render_process_host(), kNonWorkerThreadId, + event, nullptr, true /* did_enqueue */); } } void EventRouter::SetRegisteredEvents(const std::string& extension_id, - const std::set<std::string>& events) { + const std::set<std::string>& events, + RegisteredEventType type) { auto events_value = base::MakeUnique<base::ListValue>(); for (std::set<std::string>::const_iterator iter = events.begin(); iter != events.end(); ++iter) { events_value->AppendString(*iter); } - extension_prefs_->UpdateExtensionPref(extension_id, kRegisteredEvents, + const char* pref_key = type == RegisteredEventType::kLazy + ? kRegisteredLazyEvents + : kRegisteredServiceWorkerEvents; + extension_prefs_->UpdateExtensionPref(extension_id, pref_key, std::move(events_value)); } @@ -744,9 +790,11 @@ void EventRouter::OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) { // Add all registered lazy listeners to our cache. + // TODO(lazyboy): Load extension SW lazy events. std::set<std::string> registered_events = - GetRegisteredEvents(extension->id()); + GetRegisteredEvents(extension->id(), RegisteredEventType::kLazy); listeners_.LoadUnfilteredLazyListeners(extension->id(), registered_events); + // TODO(lazyboy): Load extension SW filtered events when they are available. const DictionaryValue* filtered_events = GetFilteredEvents(extension->id()); if (filtered_events) listeners_.LoadFilteredLazyListeners(extension->id(), *filtered_events); @@ -759,6 +807,51 @@ listeners_.RemoveListenersForExtension(extension->id()); } +void EventRouter::AddLazyEventListenerImpl(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id) { + bool is_for_service_worker = worker_thread_id != kNonWorkerThreadId; + bool is_new = listeners_.AddListener( + is_for_service_worker + ? EventListener::ForExtensionServiceWorker( + event_name, extension_id, nullptr, worker_thread_id, nullptr) + : EventListener::ForExtension(event_name, extension_id, nullptr, + nullptr)); + + if (is_new) { + RegisteredEventType type = is_for_service_worker + ? RegisteredEventType::kServiceWorker + : RegisteredEventType::kLazy; + std::set<std::string> events = GetRegisteredEvents(extension_id, type); + bool prefs_is_new = events.insert(event_name).second; + if (prefs_is_new) + SetRegisteredEvents(extension_id, events, type); + } +} + +void EventRouter::RemoveLazyEventListenerImpl(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id) { + bool is_for_service_worker = worker_thread_id != kNonWorkerThreadId; + std::unique_ptr<EventListener> listener = + is_for_service_worker + ? EventListener::ForExtensionServiceWorker( + event_name, extension_id, nullptr, worker_thread_id, nullptr) + : EventListener::ForExtension(event_name, extension_id, nullptr, + nullptr); + bool did_exist = listeners_.RemoveListener(listener.get()); + + if (did_exist) { + RegisteredEventType type = is_for_service_worker + ? RegisteredEventType::kServiceWorker + : RegisteredEventType::kLazy; + std::set<std::string> events = GetRegisteredEvents(extension_id, type); + bool prefs_did_exist = events.erase(event_name) > 0; + DCHECK(prefs_did_exist); + SetRegisteredEvents(extension_id, events, type); + } +} + Event::Event(events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> event_args)
diff --git a/extensions/browser/event_router.h b/extensions/browser/event_router.h index fc8d3ef..8cc397ce 100644 --- a/extensions/browser/event_router.h +++ b/extensions/browser/event_router.h
@@ -23,6 +23,7 @@ #include "extensions/browser/events/lazy_event_dispatch_util.h" #include "extensions/browser/extension_event_histogram_value.h" #include "extensions/browser/extension_registry_observer.h" +#include "extensions/common/constants.h" #include "extensions/common/event_filtering_info.h" #include "ipc/ipc_sender.h" #include "url/gurl.h" @@ -43,6 +44,8 @@ struct Event; struct EventListenerInfo; +// TODO(lazyboy): Document how extension events work, including how listeners +// are registered and how listeners are tracked in renderer and browser process. class EventRouter : public KeyedService, public ExtensionRegistryObserver, public EventListenerMap::Delegate, @@ -58,7 +61,10 @@ // The pref key for the list of event names for which an extension has // registered from its lazy background page. - static const char kRegisteredEvents[]; + static const char kRegisteredLazyEvents[]; + // The pref key for the list of event names for which an extension has + // registered from its service worker. + static const char kRegisteredServiceWorkerEvents[]; // Observers register interest in events with a particular name and are // notified when a listener is added or removed. Observers are matched by @@ -109,10 +115,18 @@ // mode extension. void AddEventListener(const std::string& event_name, content::RenderProcessHost* process, - const std::string& extension_id); + const ExtensionId& extension_id); + void AddServiceWorkerEventListener(const std::string& event_name, + content::RenderProcessHost* process, + const ExtensionId& extension_id, + int worker_thread_id); void RemoveEventListener(const std::string& event_name, content::RenderProcessHost* process, - const std::string& extension_id); + const ExtensionId& extension_id); + void RemoveServiceWorkerEventListener(const std::string& event_name, + content::RenderProcessHost* process, + const ExtensionId& extension_id, + int worker_thread_id); // Add or remove a URL as an event listener for |event_name|. void AddEventListenerForURL(const std::string& event_name, @@ -137,9 +151,17 @@ // remembered even after the process goes away. We use this list to decide // which extension pages to load when dispatching an event. void AddLazyEventListener(const std::string& event_name, - const std::string& extension_id); + const ExtensionId& extension_id); void RemoveLazyEventListener(const std::string& event_name, - const std::string& extension_id); + const ExtensionId& extension_id); + // Similar to Add/RemoveLazyEventListener, but applies to extension service + // workers. + void AddLazyServiceWorkerEventListener(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id); + void RemoveLazyServiceWorkerEventListener(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id); // If |add_lazy_listener| is true also add the lazy version of this listener. void AddFilteredEventListener(const std::string& event_name, @@ -184,13 +206,12 @@ // Returns whether or not the given extension has any registered events. bool HasRegisteredEvents(const ExtensionId& extension_id) const { - return !GetRegisteredEvents(extension_id).empty(); + return !GetRegisteredEvents(extension_id, RegisteredEventType::kLazy) + .empty(); } // Clears registered events for testing purposes. - void ClearRegisteredEventsForTest(const ExtensionId& extension_id) { - SetRegisteredEvents(extension_id, std::set<std::string>()); - } + void ClearRegisteredEventsForTest(const ExtensionId& extension_id); // Reports UMA for an event dispatched to |extension| with histogram value // |histogram_value|. Must be called on the UI thread. @@ -209,14 +230,20 @@ friend class EventRouterFilterTest; friend class EventRouterTest; + enum class RegisteredEventType { + kLazy, + kServiceWorker, + }; + // An identifier for an event dispatch that is used to prevent double dispatch // due to race conditions between the direct and lazy dispatch paths. - typedef std::pair<const content::BrowserContext*, std::string> + typedef std::tuple<const content::BrowserContext*, std::string, int> EventDispatchIdentifier; // TODO(gdk): Document this. static void DispatchExtensionMessage( IPC::Sender* ipc_sender, + int worker_thread_id, void* browser_context_id, const std::string& extension_id, int event_id, @@ -227,10 +254,11 @@ // Returns or sets the list of events for which the given extension has // registered. - std::set<std::string> GetRegisteredEvents( - const std::string& extension_id) const; + std::set<std::string> GetRegisteredEvents(const std::string& extension_id, + RegisteredEventType type) const; void SetRegisteredEvents(const std::string& extension_id, - const std::set<std::string>& events); + const std::set<std::string>& events, + RegisteredEventType type); // ExtensionRegistryObserver implementation. void OnExtensionLoaded(content::BrowserContext* browser_context, @@ -239,6 +267,13 @@ const Extension* extension, UnloadedExtensionReason reason) override; + void AddLazyEventListenerImpl(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id); + void RemoveLazyEventListenerImpl(const std::string& event_name, + const ExtensionId& extension_id, + int worker_thread_id); + // Shared by all event dispatch methods. If |restrict_to_extension_id| is // empty, the event is broadcast. An event that just came off the pending // list may not be delayed again. @@ -259,6 +294,7 @@ void DispatchEventToProcess(const std::string& extension_id, const GURL& listener_url, content::RenderProcessHost* process, + int worker_thread_id, const linked_ptr<Event>& event, const base::DictionaryValue* listener_filter, bool did_enqueue);
diff --git a/extensions/browser/extension_message_filter.cc b/extensions/browser/extension_message_filter.cc index 6bdfac0..91c46ac 100644 --- a/extensions/browser/extension_message_filter.cc +++ b/extensions/browser/extension_message_filter.cc
@@ -142,7 +142,8 @@ void ExtensionMessageFilter::OnExtensionAddListener( const std::string& extension_id, const GURL& listener_url, - const std::string& event_name) { + const std::string& event_name, + int worker_thread_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_context_) return; @@ -151,10 +152,16 @@ if (!process) return; + EventRouter* event_router = GetEventRouter(); if (crx_file::id_util::IdIsValid(extension_id)) { - GetEventRouter()->AddEventListener(event_name, process, extension_id); + if (worker_thread_id != kNonWorkerThreadId) { + event_router->AddServiceWorkerEventListener( + event_name, process, extension_id, worker_thread_id); + } else { + event_router->AddEventListener(event_name, process, extension_id); + } } else if (listener_url.is_valid()) { - GetEventRouter()->AddEventListenerForURL(event_name, process, listener_url); + event_router->AddEventListenerForURL(event_name, process, listener_url); } else { NOTREACHED() << "Tried to add an event listener without a valid " << "extension ID nor listener URL"; @@ -164,7 +171,8 @@ void ExtensionMessageFilter::OnExtensionRemoveListener( const std::string& extension_id, const GURL& listener_url, - const std::string& event_name) { + const std::string& event_name, + int worker_thread_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_context_) return; @@ -174,7 +182,12 @@ return; if (crx_file::id_util::IdIsValid(extension_id)) { - GetEventRouter()->RemoveEventListener(event_name, process, extension_id); + if (worker_thread_id != kNonWorkerThreadId) { + GetEventRouter()->RemoveServiceWorkerEventListener( + event_name, process, extension_id, worker_thread_id); + } else { + GetEventRouter()->RemoveEventListener(event_name, process, extension_id); + } } else if (listener_url.is_valid()) { GetEventRouter()->RemoveEventListenerForURL(event_name, process, listener_url); @@ -185,21 +198,35 @@ } void ExtensionMessageFilter::OnExtensionAddLazyListener( - const std::string& extension_id, const std::string& event_name) { + const std::string& extension_id, + const std::string& event_name, + int worker_thread_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_context_) return; - GetEventRouter()->AddLazyEventListener(event_name, extension_id); + if (worker_thread_id == kNonWorkerThreadId) { + GetEventRouter()->AddLazyEventListener(event_name, extension_id); + } else { + GetEventRouter()->AddLazyServiceWorkerEventListener( + event_name, extension_id, worker_thread_id); + } } void ExtensionMessageFilter::OnExtensionRemoveLazyListener( - const std::string& extension_id, const std::string& event_name) { + const std::string& extension_id, + const std::string& event_name, + int worker_thread_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_context_) return; - GetEventRouter()->RemoveLazyEventListener(event_name, extension_id); + if (worker_thread_id == kNonWorkerThreadId) { + GetEventRouter()->RemoveLazyEventListener(event_name, extension_id); + } else { + GetEventRouter()->RemoveLazyServiceWorkerEventListener( + event_name, extension_id, worker_thread_id); + } } void ExtensionMessageFilter::OnExtensionAddFilteredListener(
diff --git a/extensions/browser/extension_message_filter.h b/extensions/browser/extension_message_filter.h index cfc687a6..5859a97 100644 --- a/extensions/browser/extension_message_filter.h +++ b/extensions/browser/extension_message_filter.h
@@ -54,14 +54,18 @@ // Message handlers on the UI thread. void OnExtensionAddListener(const std::string& extension_id, const GURL& listener_url, - const std::string& event_name); + const std::string& event_name, + int worker_thread_id); void OnExtensionRemoveListener(const std::string& extension_id, const GURL& listener_url, - const std::string& event_name); + const std::string& event_name, + int worker_thread_id); void OnExtensionAddLazyListener(const std::string& extension_id, - const std::string& event_name); + const std::string& event_name, + int worker_thread_id); void OnExtensionRemoveLazyListener(const std::string& extension_id, - const std::string& event_name); + const std::string& event_name, + int worker_thread_id); void OnExtensionAddFilteredListener(const std::string& extension_id, const std::string& event_name, const base::DictionaryValue& filter,
diff --git a/extensions/browser/extension_prefs.cc b/extensions/browser/extension_prefs.cc index b3388cd..5ce0945 100644 --- a/extensions/browser/extension_prefs.cc +++ b/extensions/browser/extension_prefs.cc
@@ -1926,7 +1926,8 @@ extension_dict->Remove(kDelayedInstallInfo, NULL); // Clear state that may be registered from a previous install. - extension_dict->Remove(EventRouter::kRegisteredEvents, NULL); + extension_dict->Remove(EventRouter::kRegisteredLazyEvents, nullptr); + extension_dict->Remove(EventRouter::kRegisteredServiceWorkerEvents, nullptr); // FYI, all code below here races on sudden shutdown because |extension_dict|, // |app_sorting|, |extension_pref_value_map_|, and (potentially) observers
diff --git a/extensions/common/constants.cc b/extensions/common/constants.cc index 7770085..98bc6f1 100644 --- a/extensions/common/constants.cc +++ b/extensions/common/constants.cc
@@ -83,6 +83,8 @@ const size_t kWebstoreSignaturesPublicKeySize = arraysize(kWebstoreSignaturesPublicKey); +const int kNonWorkerThreadId = 0; + const char kMimeTypeJpeg[] = "image/jpeg"; const char kMimeTypePng[] = "image/png";
diff --git a/extensions/common/constants.h b/extensions/common/constants.h index 06f7f6f..dc9d5d2f 100644 --- a/extensions/common/constants.h +++ b/extensions/common/constants.h
@@ -113,6 +113,12 @@ extern const uint8_t kWebstoreSignaturesPublicKey[]; extern const size_t kWebstoreSignaturesPublicKeySize; +// A thread identifier used in extension events where the thread id in question +// does not belong to a worker thread. +// This is the default thread id used for extension event listeners registered +// from a non-service worker context +extern const int kNonWorkerThreadId; + // Enumeration of possible app launch sources. // This should be kept in sync with LaunchSource in // extensions/common/api/app_runtime.idl, and GetLaunchSourceEnum() in
diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index 456bff1..c4aeb68 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h
@@ -120,6 +120,10 @@ IPC_STRUCT_END() IPC_STRUCT_BEGIN(ExtensionMsg_DispatchEvent_Params) + // If this event is for a service worker, then this is the worker thread + // id. Otherwise, this is 0. + IPC_STRUCT_MEMBER(int, worker_thread_id) + // The id of the extension to dispatch the event to. IPC_STRUCT_MEMBER(std::string, extension_id) @@ -679,29 +683,33 @@ ExtensionHostMsg_Request_Params) // Notify the browser that the given extension added a listener to an event. -IPC_MESSAGE_CONTROL3(ExtensionHostMsg_AddListener, +IPC_MESSAGE_CONTROL4(ExtensionHostMsg_AddListener, std::string /* extension_id */, GURL /* listener_url */, - std::string /* name */) + std::string /* name */, + int /* worker_thread_id */) // Notify the browser that the given extension removed a listener from an // event. -IPC_MESSAGE_CONTROL3(ExtensionHostMsg_RemoveListener, +IPC_MESSAGE_CONTROL4(ExtensionHostMsg_RemoveListener, std::string /* extension_id */, GURL /* listener_url */, - std::string /* name */) + std::string /* name */, + int /* worker_thread_id */) // Notify the browser that the given extension added a listener to an event from // a lazy background page. -IPC_MESSAGE_CONTROL2(ExtensionHostMsg_AddLazyListener, +IPC_MESSAGE_CONTROL3(ExtensionHostMsg_AddLazyListener, std::string /* extension_id */, - std::string /* name */) + std::string /* name */, + int /* worker_thread_id */) // Notify the browser that the given extension is no longer interested in // receiving the given event from a lazy background page. -IPC_MESSAGE_CONTROL2(ExtensionHostMsg_RemoveLazyListener, +IPC_MESSAGE_CONTROL3(ExtensionHostMsg_RemoveLazyListener, std::string /* extension_id */, - std::string /* name */) + std::string /* name */, + int /* worker_thread_id */) // Notify the browser that the given extension added a listener to instances of // the named event that satisfy the filter.
diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index 3594171..16551ab 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc
@@ -217,6 +217,9 @@ const base::DictionaryValue* filter, bool was_manual) { bool lazy = ExtensionFrameHelper::IsContextForEventPage(context); + // TODO(lazyboy): For service workers, use worker specific IPC::Sender + // instead of |render_thread|. + const int worker_thread_id = content::WorkerThread::GetCurrentId(); std::string extension_id = context->GetExtensionID(); content::RenderThread* render_thread = content::RenderThread::Get(); @@ -232,18 +235,18 @@ } else { if (changed == binding::EventListenersChanged::HAS_LISTENERS) { render_thread->Send(new ExtensionHostMsg_AddListener( - extension_id, context->url(), event_name)); + extension_id, context->url(), event_name, worker_thread_id)); if (lazy) { - render_thread->Send( - new ExtensionHostMsg_AddLazyListener(extension_id, event_name)); + render_thread->Send(new ExtensionHostMsg_AddLazyListener( + extension_id, event_name, worker_thread_id)); } } else { DCHECK_EQ(binding::EventListenersChanged::NO_LISTENERS, changed); render_thread->Send(new ExtensionHostMsg_RemoveListener( - extension_id, context->url(), event_name)); + extension_id, context->url(), event_name, worker_thread_id)); if (lazy && was_manual) { - render_thread->Send( - new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name)); + render_thread->Send(new ExtensionHostMsg_RemoveLazyListener( + extension_id, event_name, worker_thread_id)); } } } @@ -472,7 +475,7 @@ if (ExtensionsClient::Get()->ExtensionAPIEnabledInExtensionServiceWorkers()) { WorkerThreadDispatcher::Get()->AddWorkerData(service_worker_version_id, - &source_map_); + context, &source_map_); // TODO(lazyboy): Make sure accessing |source_map_| in worker thread is // safe. @@ -893,6 +896,9 @@ } bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) { + if (WorkerThreadDispatcher::Get()->OnControlMessageReceived(message)) + return true; + bool handled = true; IPC_BEGIN_MESSAGE_MAP(Dispatcher, message) IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
diff --git a/extensions/renderer/event_bindings.cc b/extensions/renderer/event_bindings.cc index 5e8d41a..0363543 100644 --- a/extensions/renderer/event_bindings.cc +++ b/extensions/renderer/event_bindings.cc
@@ -18,12 +18,15 @@ #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" +#include "extensions/common/constants.h" #include "extensions/common/event_filter.h" #include "extensions/common/extension.h" #include "extensions/common/extension_messages.h" #include "extensions/common/value_counter.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/script_context.h" +#include "extensions/renderer/service_worker_request_sender.h" +#include "extensions/renderer/worker_thread_dispatcher.h" #include "url/gurl.h" namespace extensions { @@ -200,18 +203,23 @@ // chrome/test/data/extensions/api_test/events/background.js. attached_event_names_.insert(event_name); + const int worker_thread_id = content::WorkerThread::GetCurrentId(); const std::string& extension_id = context()->GetExtensionID(); + IPC::Sender* sender = GetIPCSender(); if (IncrementEventListenerCount(context(), event_name) == 1) { - content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener( - extension_id, context()->url(), event_name)); + sender->Send(new ExtensionHostMsg_AddListener( + extension_id, context()->url(), event_name, worker_thread_id)); } // This is called the first time the page has added a listener. Since // the background page is the only lazy page, we know this is the first // time this listener has been registered. - if (ExtensionFrameHelper::IsContextForEventPage(context())) { - content::RenderThread::Get()->Send( - new ExtensionHostMsg_AddLazyListener(extension_id, event_name)); + bool is_lazy_context = + ExtensionFrameHelper::IsContextForEventPage(context()) || + context()->context_type() == Feature::SERVICE_WORKER_CONTEXT; + if (is_lazy_context) { + sender->Send(new ExtensionHostMsg_AddLazyListener(extension_id, event_name, + worker_thread_id)); } } @@ -227,20 +235,27 @@ // See comment in AttachEvent(). attached_event_names_.erase(event_name); + int worker_thread_id = content::WorkerThread::GetCurrentId(); + IPC::Sender* sender = GetIPCSender(); const std::string& extension_id = context()->GetExtensionID(); if (DecrementEventListenerCount(context(), event_name) == 0) { - content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener( - extension_id, context()->url(), event_name)); + sender->Send(new ExtensionHostMsg_RemoveListener( + extension_id, context()->url(), event_name, worker_thread_id)); } // DetachEvent is called when the last listener for the context is - // removed. If the context is the background page, and it removes the - // last listener manually, then we assume that it is no longer interested - // in being awakened for this event. - if (is_manual && ExtensionFrameHelper::IsContextForEventPage(context())) { - content::RenderThread::Get()->Send( - new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name)); + // removed. If the context is the background page or service worker, and it + // removes the last listener manually, then we assume that it is no longer + // interested in being awakened for this event. + if (is_manual) { + bool is_lazy_context = + ExtensionFrameHelper::IsContextForEventPage(context()) || + context()->context_type() == Feature::SERVICE_WORKER_CONTEXT; + if (is_lazy_context) { + sender->Send(new ExtensionHostMsg_RemoveLazyListener( + extension_id, event_name, worker_thread_id)); + } } } @@ -351,6 +366,16 @@ std::move(filter), context()->GetRenderFrame()->GetRoutingID()); } +IPC::Sender* EventBindings::GetIPCSender() { + const bool is_service_worker_context = + context()->context_type() == Feature::SERVICE_WORKER_CONTEXT; + DCHECK_EQ(is_service_worker_context, + content::WorkerThread::GetCurrentId() != kNonWorkerThreadId); + return is_service_worker_context + ? static_cast<IPC::Sender*>(WorkerThreadDispatcher::Get()) + : static_cast<IPC::Sender*>(content::RenderThread::Get()); +} + void EventBindings::OnInvalidated() { // Detach all attached events that weren't attached. Iterate over a copy // because it will be mutated.
diff --git a/extensions/renderer/event_bindings.h b/extensions/renderer/event_bindings.h index f2d1ad7..72bb7f6d 100644 --- a/extensions/renderer/event_bindings.h +++ b/extensions/renderer/event_bindings.h
@@ -13,6 +13,10 @@ #include "extensions/renderer/object_backed_native_handler.h" #include "v8/include/v8.h" +namespace IPC { +class Sender; +} + namespace base { class DictionaryValue; } @@ -73,6 +77,8 @@ std::unique_ptr<EventMatcher> ParseEventMatcher( std::unique_ptr<base::DictionaryValue> filter); + IPC::Sender* GetIPCSender(); + // Called when our context, and therefore us, is invalidated. Run any cleanup. void OnInvalidated();
diff --git a/extensions/renderer/service_worker_data.cc b/extensions/renderer/service_worker_data.cc index 8764496..d2e9084 100644 --- a/extensions/renderer/service_worker_data.cc +++ b/extensions/renderer/service_worker_data.cc
@@ -11,8 +11,10 @@ ServiceWorkerData::ServiceWorkerData( int64_t service_worker_version_id, + ScriptContext* context, std::unique_ptr<ExtensionBindingsSystem> bindings_system) : service_worker_version_id_(service_worker_version_id), + context_(context), v8_schema_registry_(new V8SchemaRegistry), bindings_system_(std::move(bindings_system)) {}
diff --git a/extensions/renderer/service_worker_data.h b/extensions/renderer/service_worker_data.h index e9bbabb..ec415bf 100644 --- a/extensions/renderer/service_worker_data.h +++ b/extensions/renderer/service_worker_data.h
@@ -20,6 +20,7 @@ class ServiceWorkerData { public: ServiceWorkerData(int64_t service_worker_version_id, + ScriptContext* context, std::unique_ptr<ExtensionBindingsSystem> bindings_system); ~ServiceWorkerData(); @@ -28,9 +29,11 @@ int64_t service_worker_version_id() const { return service_worker_version_id_; } + ScriptContext* context() const { return context_; } private: const int64_t service_worker_version_id_; + ScriptContext* const context_; std::unique_ptr<V8SchemaRegistry> v8_schema_registry_; std::unique_ptr<ExtensionBindingsSystem> bindings_system_;
diff --git a/extensions/renderer/worker_thread_dispatcher.cc b/extensions/renderer/worker_thread_dispatcher.cc index f3385752..3a671bbc 100644 --- a/extensions/renderer/worker_thread_dispatcher.cc +++ b/extensions/renderer/worker_thread_dispatcher.cc
@@ -10,8 +10,10 @@ #include "base/values.h" #include "content/public/child/worker_thread.h" #include "content/public/renderer/render_thread.h" +#include "extensions/common/constants.h" #include "extensions/common/extension_messages.h" #include "extensions/common/feature_switch.h" +#include "extensions/renderer/dispatcher.h" #include "extensions/renderer/extension_bindings_system.h" #include "extensions/renderer/js_extension_bindings_system.h" #include "extensions/renderer/native_extension_bindings_system.h" @@ -86,7 +88,8 @@ // static bool WorkerThreadDispatcher::HandlesMessageOnWorkerThread( const IPC::Message& message) { - return message.type() == ExtensionMsg_ResponseWorker::ID; + return message.type() == ExtensionMsg_ResponseWorker::ID || + message.type() == ExtensionMsg_DispatchEvent::ID; } // static @@ -100,8 +103,12 @@ const IPC::Message& message) { if (HandlesMessageOnWorkerThread(message)) { int worker_thread_id = base::kInvalidThreadId; + // TODO(lazyboy): Route |message| directly to the child thread using routed + // IPC. Probably using mojo? bool found = base::PickleIterator(message).ReadInt(&worker_thread_id); - CHECK(found && worker_thread_id > 0); + CHECK(found); + if (worker_thread_id == kNonWorkerThreadId) + return false; base::TaskRunner* runner = GetTaskRunnerFor(worker_thread_id); bool task_posted = runner->PostTask( FROM_HERE, base::Bind(&WorkerThreadDispatcher::ForwardIPC, @@ -119,6 +126,7 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(WorkerThreadDispatcher, message) IPC_MESSAGE_HANDLER(ExtensionMsg_ResponseWorker, OnResponseWorker) + IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchEvent, OnDispatchEvent) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() CHECK(handled); @@ -149,8 +157,18 @@ error); } +void WorkerThreadDispatcher::OnDispatchEvent( + const ExtensionMsg_DispatchEvent_Params& params, + const base::ListValue& event_args) { + ServiceWorkerData* data = g_data_tls.Pointer()->Get(); + DCHECK(data); + data->bindings_system()->DispatchEventInContext( + params.event_name, &event_args, ¶ms.filtering_info, data->context()); +} + void WorkerThreadDispatcher::AddWorkerData( int64_t service_worker_version_id, + ScriptContext* context, ResourceBundleSourceMap* source_map) { ServiceWorkerData* data = g_data_tls.Pointer()->Get(); if (!data) { @@ -164,7 +182,7 @@ this, service_worker_version_id)); } ServiceWorkerData* new_data = new ServiceWorkerData( - service_worker_version_id, std::move(bindings_system)); + service_worker_version_id, context, std::move(bindings_system)); g_data_tls.Pointer()->Set(new_data); }
diff --git a/extensions/renderer/worker_thread_dispatcher.h b/extensions/renderer/worker_thread_dispatcher.h index 4a876b1..b329ccf8 100644 --- a/extensions/renderer/worker_thread_dispatcher.h +++ b/extensions/renderer/worker_thread_dispatcher.h
@@ -6,6 +6,8 @@ #define EXTENSIONS_RENDERER_WORKER_THREAD_DISPATCHER_H_ #include "base/synchronization/lock.h" +#include "base/threading/platform_thread.h" +#include "content/public/child/worker_thread.h" #include "content/public/renderer/render_thread_observer.h" #include "ipc/ipc_sync_message_filter.h" @@ -17,9 +19,11 @@ class RenderThread; } +struct ExtensionMsg_DispatchEvent_Params; namespace extensions { class ExtensionBindingsSystem; class ResourceBundleSourceMap; +class ScriptContext; class ServiceWorkerRequestSender; class V8SchemaRegistry; @@ -29,7 +33,8 @@ // 1) A content::WorkerThreadMessageFilter, so that we can receive IPC directly // on worker thread. // 2) A content::ThreadSafeSender, so we can safely send IPC from worker thread. -class WorkerThreadDispatcher : public content::RenderThreadObserver { +class WorkerThreadDispatcher : public content::RenderThreadObserver, + public IPC::Sender { public: WorkerThreadDispatcher(); ~WorkerThreadDispatcher() override; @@ -41,18 +46,22 @@ static V8SchemaRegistry* GetV8SchemaRegistry(); void Init(content::RenderThread* render_thread); - bool Send(IPC::Message* message); + + // IPC::Sender: + bool Send(IPC::Message* message) override; + void AddWorkerData(int64_t service_worker_version_id, + ScriptContext* context, ResourceBundleSourceMap* source_map); void RemoveWorkerData(int64_t service_worker_version_id); + // content::RenderThreadObserver: + bool OnControlMessageReceived(const IPC::Message& message) override; + private: static bool HandlesMessageOnWorkerThread(const IPC::Message& message); static void ForwardIPC(int worker_thread_id, const IPC::Message& message); - // content::RenderThreadObserver: - bool OnControlMessageReceived(const IPC::Message& message) override; - void OnMessageReceivedOnWorkerThread(int worker_thread_id, const IPC::Message& message); @@ -64,6 +73,8 @@ bool succeeded, const base::ListValue& response, const std::string& error); + void OnDispatchEvent(const ExtensionMsg_DispatchEvent_Params& params, + const base::ListValue& event_args); // IPC sender. Belongs to the render thread, but thread safe. scoped_refptr<IPC::SyncMessageFilter> message_filter_;
diff --git a/gpu/config/gpu_driver_bug_list.json b/gpu/config/gpu_driver_bug_list.json index 77629e4..869f5366 100644 --- a/gpu/config/gpu_driver_bug_list.json +++ b/gpu/config/gpu_driver_bug_list.json
@@ -1,6 +1,6 @@ { "name": "gpu driver bug list", - "version": "10.10", + "version": "10.11", "entries": [ { "id": 1, @@ -2495,6 +2495,18 @@ "features": [ "disable_larger_than_screen_overlays" ] + }, + { + "id": 230, + "description": "Disable use of Direct3D 11 on Intel Cherryview due to visual glitches.", + "os": { + "type": "win" + }, + "vendor_id": "0x8086", + "device_id": ["0x22B0", "0x22B1", "0x22B2", "0x22B3"], + "features": [ + "disable_d3d11" + ] } ], "comment": [
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm index 0b2f3c1..814e302 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm
@@ -49,12 +49,6 @@ @property(nonatomic, strong) NSMutableDictionary<NSNumber*, EditorField*>* fieldsMap; -// The reference to the autofill::CREDIT_CARD_EXP_MONTH field. -@property(nonatomic, strong) EditorField* creditCardExpMonthField; - -// The reference to the autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR field. -@property(nonatomic, strong) EditorField* creditCardExpYearField; - @end @implementation CreditCardEditViewControllerMediator @@ -65,8 +59,6 @@ @synthesize paymentRequest = _paymentRequest; @synthesize creditCard = _creditCard; @synthesize fieldsMap = _fieldsMap; -@synthesize creditCardExpMonthField = _creditCardExpMonthField; -@synthesize creditCardExpYearField = _creditCardExpYearField; - (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest creditCard:(autofill::CreditCard*)creditCard { @@ -91,10 +83,7 @@ - (void)setConsumer:(id<PaymentRequestEditConsumer>)consumer { _consumer = consumer; - [self.consumer setEditorFields:[self createEditorFields]]; - [self loadMonths]; - [self loadYears]; } - (void)setBillingProfile:(autofill::AutofillProfile*)billingProfile { @@ -166,55 +155,6 @@ #pragma mark - Helper methods -// Queries the month numbers. -- (void)loadMonths { - NSMutableArray<NSString*>* months = [[NSMutableArray alloc] init]; - - for (int month = 1; month <= 12; month++) { - NSString* monthString = [NSString stringWithFormat:@"%02d", month]; - [months addObject:monthString]; - } - - // Notify the view controller asynchronously to allow for the view to update. - __weak CreditCardEditViewControllerMediator* weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.consumer setOptions:months - forEditorField:weakSelf.creditCardExpMonthField]; - }); -} - -// Queries the year numbers. -- (void)loadYears { - NSMutableArray<NSString*>* years = [[NSMutableArray alloc] init]; - - NSDateComponents* dateComponents = - [[NSCalendar currentCalendar] components:NSCalendarUnitYear - fromDate:[NSDate date]]; - - int currentYear = [dateComponents year]; - bool foundCardExpirationYear = false; - for (int year = currentYear; year < currentYear + 10; year++) { - NSString* yearString = [NSString stringWithFormat:@"%04d", year]; - if ([yearString isEqualToString:_creditCardExpYearField.value]) - foundCardExpirationYear = true; - [years addObject:yearString]; - } - - // Ensure that the expiration year on a user's saved card is - // always available as one of the options to select from. This is - // useful in the case that the user's card is expired. - if (!foundCardExpirationYear) { - [years insertObject:_creditCardExpYearField.value atIndex:0]; - } - - // Notify the view controller asynchronously to allow for the view to update. - __weak CreditCardEditViewControllerMediator* weakSelf = self; - dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.consumer setOptions:years - forEditorField:weakSelf.creditCardExpYearField]; - }); -} - - (NSArray<EditorField*>*)createEditorFields { NSMutableArray<EditorField*>* fields = [[NSMutableArray alloc] init]; @@ -280,16 +220,11 @@ } [fields addObject:creditCardNameField]; - NSDateComponents* dateComponents = [[NSCalendar currentCalendar] - components:NSCalendarUnitMonth | NSCalendarUnitYear - fromDate:[NSDate date]]; - // Expiration month field. - int currentMonth = [dateComponents month]; NSString* creditCardExpMonth = _creditCard ? [NSString stringWithFormat:@"%02d", _creditCard->expiration_month()] - : [NSString stringWithFormat:@"%02d", currentMonth]; + : nil; fieldKey = [NSNumber numberWithInt:AutofillUITypeCreditCardExpMonth]; EditorField* expirationMonthField = self.fieldsMap[fieldKey]; if (!expirationMonthField) { @@ -301,15 +236,13 @@ required:YES]; [self.fieldsMap setObject:expirationMonthField forKey:fieldKey]; } - self.creditCardExpMonthField = expirationMonthField; [fields addObject:expirationMonthField]; // Expiration year field. - int currentYear = [dateComponents year]; NSString* creditCardExpYear = _creditCard ? [NSString stringWithFormat:@"%04d", _creditCard->expiration_year()] - : [NSString stringWithFormat:@"%04d", currentYear]; + : nil; fieldKey = [NSNumber numberWithInt:AutofillUITypeCreditCardExpYear]; EditorField* expirationYearField = self.fieldsMap[fieldKey]; if (!expirationYearField) { @@ -321,7 +254,6 @@ required:YES]; [self.fieldsMap setObject:expirationYearField forKey:fieldKey]; } - self.creditCardExpYearField = expirationYearField; [fields addObject:expirationYearField]; // The billing address field appears after the expiration year field.
diff --git a/ios/chrome/browser/variations/ios_chrome_variations_service_client.cc b/ios/chrome/browser/variations/ios_chrome_variations_service_client.cc index 3953743..279f53b 100644 --- a/ios/chrome/browser/variations/ios_chrome_variations_service_client.cc +++ b/ios/chrome/browser/variations/ios_chrome_variations_service_client.cc
@@ -9,7 +9,6 @@ #include "components/version_info/version_info.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/common/channel_info.h" -#include "ios/web/public/web_thread.h" namespace { @@ -31,10 +30,6 @@ return GetApplicationContext()->GetApplicationLocale(); } -base::SequencedWorkerPool* IOSChromeVariationsServiceClient::GetBlockingPool() { - return web::WebThread::GetBlockingPool(); -} - base::Callback<base::Version()> IOSChromeVariationsServiceClient::GetVersionForSimulationCallback() { return base::Bind(&GetVersionForSimulation);
diff --git a/ios/chrome/browser/variations/ios_chrome_variations_service_client.h b/ios/chrome/browser/variations/ios_chrome_variations_service_client.h index 6f6a3150..e4fbfe3 100644 --- a/ios/chrome/browser/variations/ios_chrome_variations_service_client.h +++ b/ios/chrome/browser/variations/ios_chrome_variations_service_client.h
@@ -19,7 +19,6 @@ private: // variations::VariationsServiceClient implementation. std::string GetApplicationLocale() override; - base::SequencedWorkerPool* GetBlockingPool() override; base::Callback<base::Version()> GetVersionForSimulationCallback() override; net::URLRequestContextGetter* GetURLRequestContext() override; network_time::NetworkTimeTracker* GetNetworkTimeTracker() override;
diff --git a/media/capture/video/android/java/src/org/chromium/media/VideoCaptureCamera2.java b/media/capture/video/android/java/src/org/chromium/media/VideoCaptureCamera2.java index 5919ed1..05cc66e 100644 --- a/media/capture/video/android/java/src/org/chromium/media/VideoCaptureCamera2.java +++ b/media/capture/video/android/java/src/org/chromium/media/VideoCaptureCamera2.java
@@ -25,6 +25,7 @@ import android.os.Build; import android.os.Handler; import android.os.HandlerThread; +import android.os.Looper; import android.os.SystemClock; import android.util.Range; import android.util.Size; @@ -33,7 +34,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.JNINamespace; import java.nio.ByteBuffer; @@ -214,6 +214,7 @@ private Handler mMainHandler; private Handler mBackgroundHandler; + private final Looper mLooper; private ImageReader mPreviewReader; private ImageReader mPhotoReader; @@ -616,6 +617,7 @@ VideoCaptureCamera2(int id, long nativeVideoCaptureDeviceAndroid) { super(id, nativeVideoCaptureDeviceAndroid); + mLooper = Looper.myLooper(); final CameraCharacteristics cameraCharacteristics = getCameraCharacteristics(id); if (cameraCharacteristics != null) { mMaxZoom = cameraCharacteristics.get( @@ -626,7 +628,7 @@ @Override public boolean allocate(int width, int height, int frameRate) { Log.d(TAG, "allocate: requested (%d x %d) @%dfps", width, height, frameRate); - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; synchronized (mCameraStateLock) { if (mCameraState == CameraState.OPENING || mCameraState == CameraState.CONFIGURING) { Log.e(TAG, "allocate() invoked while Camera is busy opening/configuring."); @@ -682,7 +684,7 @@ @Override public boolean startCapture() { - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; changeCameraStateAndNotify(CameraState.OPENING); final CameraManager manager = (CameraManager) ContextUtils.getApplicationContext().getSystemService( @@ -715,7 +717,7 @@ @Override public boolean stopCapture() { - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; // With Camera2 API, the capture is started asynchronously, which will cause problem if // stopCapture comes too quickly. Without stopping the previous capture properly, the next @@ -749,7 +751,7 @@ @Override public PhotoCapabilities getPhotoCapabilities() { - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; final CameraCharacteristics cameraCharacteristics = getCameraCharacteristics(mId); PhotoCapabilities.Builder builder = new PhotoCapabilities.Builder(); @@ -946,7 +948,7 @@ boolean hasRedEyeReduction, boolean redEyeReduction, int fillLightMode, boolean hasTorch, boolean torch, double colorTemperature) { Log.d(TAG, "setPhotoOptions()"); - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; final CameraCharacteristics cameraCharacteristics = getCameraCharacteristics(mId); final Rect canvas = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); @@ -1027,7 +1029,7 @@ @Override public boolean takePhoto(final long callbackId) { Log.d(TAG, "takePhoto()"); - ThreadUtils.assertOnUiThread(); + assert mLooper == Looper.myLooper() : "called on wrong thread"; final CrPhotoReaderListener photoReaderListener = new CrPhotoReaderListener(callbackId); mPhotoReader.setOnImageAvailableListener(photoReaderListener, mBackgroundHandler);
diff --git a/media/midi/midi_manager_win.cc b/media/midi/midi_manager_win.cc index de73e13..95e2eb652 100644 --- a/media/midi/midi_manager_win.cc +++ b/media/midi/midi_manager_win.cc
@@ -660,9 +660,7 @@ &MidiManagerWin::ReceiveMidiData, base::Unretained(manager), index, data, manager->port_manager()->CalculateInEventTime(index, param2))); } - manager->PostTask(base::Bind(&MidiManagerWin::PortManager::RestoreInBuffer, - base::Unretained(manager->port_manager()), - index)); + manager->port_manager()->RestoreInBuffer(index); } }
diff --git a/remoting/ios/app/BUILD.gn b/remoting/ios/app/BUILD.gn index 02c5963..735f79f5 100644 --- a/remoting/ios/app/BUILD.gn +++ b/remoting/ios/app/BUILD.gn
@@ -35,6 +35,8 @@ "pin_entry_view.mm", "remoting_settings_view_controller.h", "remoting_settings_view_controller.mm", + "remoting_theme.h", + "remoting_theme.mm", "remoting_view_controller.h", "remoting_view_controller.mm", ]
diff --git a/remoting/ios/app/client_connection_view_controller.mm b/remoting/ios/app/client_connection_view_controller.mm index 657ccf9..1bb8f96 100644 --- a/remoting/ios/app/client_connection_view_controller.mm +++ b/remoting/ios/app/client_connection_view_controller.mm
@@ -14,6 +14,7 @@ #import "ios/third_party/material_components_ios/src/components/NavigationBar/src/MaterialNavigationBar.h" #import "remoting/ios/app/host_view_controller.h" #import "remoting/ios/app/pin_entry_view.h" +#import "remoting/ios/app/remoting_theme.h" #import "remoting/ios/domain/client_session_details.h" #import "remoting/ios/domain/host_info.h" #import "remoting/ios/facade/remoting_authentication.h" @@ -86,7 +87,7 @@ _navBar = [[MDCNavigationBar alloc] initWithFrame:CGRectZero]; [_navBar observeNavigationItem:self.navigationItem]; - [_navBar setBackgroundColor:[UIColor blackColor]]; + [_navBar setBackgroundColor:RemotingTheme.connectionViewBackgroundColor]; MDCNavigationBarTextColorAccessibilityMutator* mutator = [[MDCNavigationBarTextColorAccessibilityMutator alloc] init]; [mutator mutate:_navBar]; @@ -111,7 +112,7 @@ - (void)loadView { [super loadView]; - self.view.backgroundColor = [UIColor blackColor]; + self.view.backgroundColor = RemotingTheme.connectionViewBackgroundColor; _activityIndicator = [[MDCActivityIndicator alloc] initWithFrame:CGRectZero]; [self.view addSubview:_activityIndicator]; @@ -132,7 +133,7 @@ _iconView.contentMode = UIViewContentModeCenter; _iconView.alpha = 0.87f; - _iconView.backgroundColor = UIColor.lightGrayColor; + _iconView.backgroundColor = RemotingTheme.onlineHostColor; _iconView.layer.cornerRadius = kIconRadius; _iconView.layer.masksToBounds = YES; _iconView.image = [UIImage imageNamed:@"ic_desktop"]; @@ -140,7 +141,7 @@ _activityIndicator.radius = kActivityIndicatorRadius; _activityIndicator.trackEnabled = YES; _activityIndicator.strokeWidth = kActivityIndicatorStrokeWidth; - _activityIndicator.cycleColors = @[ [UIColor whiteColor] ]; + _activityIndicator.cycleColors = @[ UIColor.whiteColor ]; _statusLabel.numberOfLines = 1; _statusLabel.lineBreakMode = NSLineBreakByTruncatingTail; @@ -228,6 +229,7 @@ _pinEntryView.frame.size.height + kPadding); if (overlap < 0) { f.origin.y = overlap; + // TODO(yuweih): This may push the navigation bar off screen. self.view.frame = f; } }]; @@ -281,6 +283,9 @@ [_activityIndicator stopAnimating]; _activityIndicator.hidden = YES; _pinEntryView.hidden = NO; + + // TODO(yuweih): This may be called before viewDidAppear and miss the keyboard + // callback. [_pinEntryView becomeFirstResponder]; }
diff --git a/remoting/ios/app/host_collection_view_cell.mm b/remoting/ios/app/host_collection_view_cell.mm index 1b8c33d..cd876291 100644 --- a/remoting/ios/app/host_collection_view_cell.mm +++ b/remoting/ios/app/host_collection_view_cell.mm
@@ -11,6 +11,7 @@ #import "remoting/ios/app/host_collection_view_cell.h" #import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h" +#import "remoting/ios/app/remoting_theme.h" #import "remoting/ios/domain/host_info.h" static const CGFloat kLinePadding = 2.f; @@ -49,7 +50,7 @@ _imageView.translatesAutoresizingMaskIntoConstraints = NO; _imageView.contentMode = UIViewContentModeCenter; _imageView.alpha = 0.87f; - _imageView.backgroundColor = UIColor.lightGrayColor; + _imageView.backgroundColor = RemotingTheme.offlineHostColor; _imageView.layer.cornerRadius = kHostCardIconSize / 2.f; _imageView.layer.masksToBounds = YES; [self.contentView addSubview:_imageView]; @@ -131,13 +132,11 @@ _imageView.image = [UIImage imageNamed:@"ic_desktop"]; - // TODO(nicholss): These colors are incorrect for the final product. - // Need to update to the values in the mocks. if ([_hostInfo.status isEqualToString:@"ONLINE"]) { - _imageView.backgroundColor = UIColor.greenColor; + _imageView.backgroundColor = RemotingTheme.onlineHostColor; _statusLabel.text = @"Online"; } else { - _imageView.backgroundColor = UIColor.lightGrayColor; + _imageView.backgroundColor = RemotingTheme.offlineHostColor; _statusLabel.text = [NSString stringWithFormat:@"Last online: %@", hostInfo.updatedTime]; }
diff --git a/remoting/ios/app/host_view_controller.mm b/remoting/ios/app/host_view_controller.mm index 4aa780f..7a94b3c 100644 --- a/remoting/ios/app/host_view_controller.mm +++ b/remoting/ios/app/host_view_controller.mm
@@ -10,14 +10,14 @@ #include <memory> -#import <GLKit/GLKit.h> - #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" #import "remoting/ios/client_gestures.h" #import "remoting/ios/client_keyboard.h" +#import "remoting/ios/display/eagl_view.h" #import "remoting/ios/session/remoting_client.h" #include "base/strings/sys_string_conversions.h" +#include "remoting/client/chromoting_client_runtime.h" #include "remoting/client/gesture_interpreter.h" #include "remoting/client/input/keyboard_interpreter.h" @@ -48,7 +48,10 @@ #pragma mark - UIViewController - (void)loadView { - self.view = [[GLKView alloc] initWithFrame:CGRectZero]; + EAGLView* glView = [[EAGLView alloc] initWithFrame:CGRectZero]; + glView.displayTaskRunner = + remoting::ChromotingClientRuntime::GetInstance()->display_task_runner(); + self.view = glView; } - (void)viewDidLoad { @@ -77,9 +80,7 @@ - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; - GLKView* glView = (GLKView*)self.view; - glView.context = [_client.displayHandler GetEAGLContext]; - [_client.displayHandler onSurfaceCreated:glView]; + [_client.displayHandler onSurfaceCreated:(EAGLView*)self.view]; // viewDidLayoutSubviews may be called before viewDidAppear, in which case // the surface is not ready to handle the transformation matrix. @@ -93,7 +94,7 @@ - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; - [(GLKView*)self.view deleteDrawable]; + [(EAGLView*)self.view stop]; } - (void)viewWillAppear:(BOOL)animated { @@ -126,7 +127,7 @@ - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; - if (((GLKView*)self.view).context != nil) { + if (self.view.window != nil) { // If the context is not set yet, the view size will be set in // viewDidAppear. [_client surfaceChanged:self.view.bounds]; @@ -264,8 +265,9 @@ style:UIAlertActionStyleDefault handler:disconnectHandler]]; + __weak UIAlertController* weakAlert = alert; void (^cancelHandler)(UIAlertAction*) = ^(UIAlertAction*) { - [alert dismissViewControllerAnimated:YES completion:nil]; + [weakAlert dismissViewControllerAnimated:YES completion:nil]; }; [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
diff --git a/remoting/ios/app/pin_entry_view.mm b/remoting/ios/app/pin_entry_view.mm index 7660ffa..906f6312 100644 --- a/remoting/ios/app/pin_entry_view.mm +++ b/remoting/ios/app/pin_entry_view.mm
@@ -46,7 +46,8 @@ _pinButton = [MDCFloatingButton floatingButtonWithShape:MDCFloatingButtonShapeMini]; - [_pinButton setTitle:@"+" forState:UIControlStateNormal]; + [_pinButton setBackgroundColor:UIColor.whiteColor + forState:UIControlStateNormal]; // TODO(nicholss): Update "->" to the arrow icon. [_pinButton setTitle:@"->" forState:UIControlStateNormal];
diff --git a/remoting/ios/app/remoting_theme.h b/remoting/ios/app/remoting_theme.h new file mode 100644 index 0000000..176adad0 --- /dev/null +++ b/remoting/ios/app/remoting_theme.h
@@ -0,0 +1,20 @@ +// 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 REMOTING_IOS_APP_REMOTING_THEME_H_ +#define REMOTING_IOS_APP_REMOTING_THEME_H_ + +#import <UIKit/UIKit.h> + +// Styles to be used when rendering the iOS client's UI. +@interface RemotingTheme : NSObject + +@property(class, nonatomic, readonly) UIColor* hostListBackgroundColor; +@property(class, nonatomic, readonly) UIColor* connectionViewBackgroundColor; +@property(class, nonatomic, readonly) UIColor* onlineHostColor; +@property(class, nonatomic, readonly) UIColor* offlineHostColor; + +@end + +#endif // REMOTING_IOS_APP_REMOTING_THEME_H_
diff --git a/remoting/ios/app/remoting_theme.mm b/remoting/ios/app/remoting_theme.mm new file mode 100644 index 0000000..06c269e --- /dev/null +++ b/remoting/ios/app/remoting_theme.mm
@@ -0,0 +1,49 @@ +// Copyright 2016 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. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/ios/app/remoting_theme.h" + +@implementation RemotingTheme + ++ (UIColor*)hostListBackgroundColor { + static UIColor* color; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + color = [UIColor colorWithRed:0.11f green:0.23f blue:0.66f alpha:1.f]; + }); + return color; +} + ++ (UIColor*)connectionViewBackgroundColor { + static UIColor* color; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + color = [UIColor colorWithRed:0.06f green:0.12f blue:0.33f alpha:1.f]; + }); + return color; +} + ++ (UIColor*)onlineHostColor { + static UIColor* color; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + color = [UIColor colorWithRed:0.20f green:0.70f blue:0.20f alpha:1.f]; + }); + return color; +} + ++ (UIColor*)offlineHostColor { + static UIColor* color; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + color = [UIColor colorWithRed:0.75f green:0.75f blue:0.75f alpha:1.f]; + }); + return color; +} + +@end
diff --git a/remoting/ios/app/remoting_view_controller.mm b/remoting/ios/app/remoting_view_controller.mm index 268820b..d7ba752 100644 --- a/remoting/ios/app/remoting_view_controller.mm +++ b/remoting/ios/app/remoting_view_controller.mm
@@ -17,6 +17,7 @@ #import "remoting/ios/app/host_collection_view_controller.h" #import "remoting/ios/app/host_view_controller.h" #import "remoting/ios/app/remoting_settings_view_controller.h" +#import "remoting/ios/app/remoting_theme.h" #import "remoting/ios/domain/client_session_details.h" #import "remoting/ios/facade/remoting_authentication.h" #import "remoting/ios/facade/remoting_service.h" @@ -27,9 +28,6 @@ static CGFloat kHostInset = 5.f; -static UIColor* kChromotingBlueBackground = - [UIColor colorWithRed:0.11f green:0.23f blue:0.66f alpha:1.f]; - @interface RemotingViewController ()<HostCollectionViewControllerDelegate, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate> { @@ -85,8 +83,9 @@ self.navigationItem.rightBarButtonItem = refreshButton; _appBar.headerViewController.headerView.backgroundColor = - kChromotingBlueBackground; - _appBar.navigationBar.backgroundColor = kChromotingBlueBackground; + RemotingTheme.hostListBackgroundColor; + _appBar.navigationBar.backgroundColor = + RemotingTheme.hostListBackgroundColor; MDCNavigationBarTextColorAccessibilityMutator* mutator = [[MDCNavigationBarTextColorAccessibilityMutator alloc] init]; [mutator mutate:_appBar.navigationBar]; @@ -197,6 +196,7 @@ return; } + [MDCSnackbarManager dismissAndCallCompletionBlocksWithCategory:nil]; ClientConnectionViewController* clientConnectionViewController = [[ClientConnectionViewController alloc] initWithHostInfo:cell.hostInfo]; [self.navigationController pushViewController:clientConnectionViewController
diff --git a/remoting/ios/app/resources/Assets.xcassets/Background.imageset/Contents.json b/remoting/ios/app/resources/Assets.xcassets/Background.imageset/Contents.json index 85dc959..486721f 100644 --- a/remoting/ios/app/resources/Assets.xcassets/Background.imageset/Contents.json +++ b/remoting/ios/app/resources/Assets.xcassets/Background.imageset/Contents.json
@@ -9,6 +9,10 @@ "idiom" : "universal", "filename" : "bkg1_2x.jpg", "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" } ], "info" : {
diff --git a/remoting/ios/display/BUILD.gn b/remoting/ios/display/BUILD.gn index a1e2a3ba..5b24ebb7 100644 --- a/remoting/ios/display/BUILD.gn +++ b/remoting/ios/display/BUILD.gn
@@ -18,6 +18,8 @@ source_set("display") { sources = [ + "eagl_view.h", + "eagl_view.mm", "gl_demo_screen.h", "gl_demo_screen.mm", "gl_display_handler.h",
diff --git a/remoting/ios/display/eagl_view.h b/remoting/ios/display/eagl_view.h new file mode 100644 index 0000000..6673e83 --- /dev/null +++ b/remoting/ios/display/eagl_view.h
@@ -0,0 +1,31 @@ +// 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 REMOTING_IOS_DISPAY_EAGL_VIEW_H_ +#define REMOTING_IOS_DISPAY_EAGL_VIEW_H_ + +#import <UIKit/UIKit.h> + +#include "base/memory/ref_counted.h" +#include "base/single_thread_task_runner.h" + +// This is an OpenGL view implementation that allows and guarantees the content +// to be rendered and modified on a non-UI thread. Methods can be called from +// any thread. +@interface EAGLView : UIView + +- (instancetype)initWithFrame:(CGRect)frame; + +// |context| must be the current EAGLContext of |displayTaskRunner|'s thread. +- (void)startWithContext:(EAGLContext*)context; + +- (void)stop; + +// The thread to render the content. Must be set once immediately after the view +// is initialized. +@property(nonatomic) scoped_refptr<base::SingleThreadTaskRunner> + displayTaskRunner; +@end + +#endif // REMOTING_IOS_DISPAY_EAGL_VIEW_H_
diff --git a/remoting/ios/display/eagl_view.mm b/remoting/ios/display/eagl_view.mm new file mode 100644 index 0000000..83476c1b --- /dev/null +++ b/remoting/ios/display/eagl_view.mm
@@ -0,0 +1,188 @@ +// 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. + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "remoting/ios/display/eagl_view.h" + +#include <memory> + +#import <OpenGLES/ES2/gl.h> + +#import "base/mac/bind_objc_block.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/logging.h" +#include "base/threading/thread_checker.h" +#include "base/threading/thread_task_runner_handle.h" + +namespace { + +// The core that runs on the display thread. +class EAGLViewCore { + public: + EAGLViewCore(CAEAGLLayer* layer); + ~EAGLViewCore(); + + void Start(EAGLContext* context); + void Stop(); + + void ReshapeFramebuffer(CGFloat width, CGFloat height); + + private: + bool IsStarted() const; + + EAGLContext* context_; + CAEAGLLayer* eagl_layer_; + GLuint view_frame_buffer_; + GLuint view_render_buffer_; + + THREAD_CHECKER(thread_checker_); +}; + +EAGLViewCore::EAGLViewCore(CAEAGLLayer* layer) { + DETACH_FROM_THREAD(thread_checker_); + eagl_layer_ = layer; +} + +EAGLViewCore::~EAGLViewCore() { + Stop(); +} + +void EAGLViewCore::Start(EAGLContext* context) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + if (IsStarted()) { + Stop(); + } + + context_ = context; + + glGenFramebuffers(1, &view_frame_buffer_); + glGenRenderbuffers(1, &view_render_buffer_); + glBindFramebuffer(GL_FRAMEBUFFER, view_frame_buffer_); + glBindRenderbuffer(GL_RENDERBUFFER, view_render_buffer_); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_RENDERBUFFER, view_render_buffer_); +} + +void EAGLViewCore::Stop() { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + if (!IsStarted()) { + return; + } + + glBindRenderbuffer(GL_RENDERBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteRenderbuffers(1, &view_render_buffer_); + glDeleteFramebuffers(1, &view_frame_buffer_); + context_ = nil; +} + +void EAGLViewCore::ReshapeFramebuffer(CGFloat width, CGFloat height) { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + + // Allocate GL color buffer backing, matching the current layer size + [context_ renderbufferStorage:GL_RENDERBUFFER fromDrawable:eagl_layer_]; + + glViewport(0, 0, width, height); +} + +bool EAGLViewCore::IsStarted() const { + DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); + return context_ != nil; +} + +} // namespace + +#pragma mark - EAGLView + +@interface EAGLView () { + std::unique_ptr<EAGLViewCore> _core; +} +@end + +@implementation EAGLView + +@synthesize displayTaskRunner = _displayTaskRunner; + ++ (Class)layerClass { + return [CAEAGLLayer class]; +} + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.contentScaleFactor = [UIScreen mainScreen].scale; + CAEAGLLayer* eaglLayer = (CAEAGLLayer*)self.layer; + eaglLayer.opaque = YES; + eaglLayer.drawableProperties = @{ + kEAGLDrawablePropertyRetainedBacking : @NO, + kEAGLDrawablePropertyColorFormat : kEAGLColorFormatRGBA8, + }; + _core.reset(new EAGLViewCore(eaglLayer)); + } + return self; +} + +- (void)dealloc { + DCHECK(_displayTaskRunner); + if (!_displayTaskRunner->BelongsToCurrentThread()) { + _displayTaskRunner->DeleteSoon(FROM_HERE, _core.release()); + } + // If the current thread is the display thread, _core will be freed by + // unique_ptr's destructor. +} + +- (void)startWithContext:(EAGLContext*)context { + [self + runOnDisplayThread:(base::Bind(&EAGLViewCore::Start, + base::Unretained(_core.get()), context))]; + [self reshapeFrameBuffer]; +} + +- (void)stop { + [self runOnDisplayThread:(base::Bind(&EAGLViewCore::Stop, + base::Unretained(_core.get())))]; +} + +#pragma mark - View + +- (void)layoutSubviews { + [self reshapeFrameBuffer]; +} + +#pragma mark - Properties + +- (void)setDisplayTaskRunner: + (scoped_refptr<base::SingleThreadTaskRunner>)displayTaskRunner { + DCHECK(!_displayTaskRunner) << "displayTaskRunner is already set."; + _displayTaskRunner = displayTaskRunner; +} + +#pragma mark - Private + +// Runs a closure directly if current thread is the display thread. Otherwise +// post a task to do so. +- (void)runOnDisplayThread:(const base::Closure&)closure { + DCHECK(_displayTaskRunner) << "displayTaskRunner has not been set."; + if (_displayTaskRunner->BelongsToCurrentThread()) { + closure.Run(); + return; + } + _displayTaskRunner->PostTask(FROM_HERE, closure); +} + +- (void)reshapeFrameBuffer { + CGFloat scaleFactor = self.contentScaleFactor; + [self runOnDisplayThread:(base::Bind( + &EAGLViewCore::ReshapeFramebuffer, + base::Unretained(_core.get()), + scaleFactor * CGRectGetWidth(self.bounds), + scaleFactor * CGRectGetHeight(self.bounds)))]; +} + +@end
diff --git a/remoting/ios/display/gl_display_handler.h b/remoting/ios/display/gl_display_handler.h index 045cf46..530b1d4 100644 --- a/remoting/ios/display/gl_display_handler.h +++ b/remoting/ios/display/gl_display_handler.h
@@ -5,8 +5,8 @@ #ifndef REMOTING_IOS_DISPLAY_GL_DISPLAY_HANDLER_H_ #define REMOTING_IOS_DISPLAY_GL_DISPLAY_HANDLER_H_ +#import <CoreGraphics/CoreGraphics.h> #import <Foundation/Foundation.h> -#import <GLKit/GLKit.h> #import "remoting/client/display/sys_opengl.h" @@ -25,6 +25,8 @@ } // namespace protocol } // namespace remoting +@class EAGLView; + // This protocol is for receiving notifications from the renderer when its state // changes. Implementations can use this to reposition viewport, process // animations, etc. @@ -43,7 +45,7 @@ - (void)stop; // Called once the GLKView created. -- (void)onSurfaceCreated:(GLKView*)view; +- (void)onSurfaceCreated:(EAGLView*)view; // Called every time the GLKView dimension is initialized or changed. - (void)onSurfaceChanged:(const CGRect&)frame; @@ -53,8 +55,6 @@ - (std::unique_ptr<remoting::protocol::VideoRenderer>)CreateVideoRenderer; - (std::unique_ptr<remoting::protocol::CursorShapeStub>)CreateCursorShapeStub; -- (EAGLContext*)GetEAGLContext; - // This is write-only but @property doesn't support write-only modifier. @property id<GlDisplayHandlerDelegate> delegate; - (id<GlDisplayHandlerDelegate>)delegate UNAVAILABLE_ATTRIBUTE;
diff --git a/remoting/ios/display/gl_display_handler.mm b/remoting/ios/display/gl_display_handler.mm index bedc32b..e50a3d24 100644 --- a/remoting/ios/display/gl_display_handler.mm +++ b/remoting/ios/display/gl_display_handler.mm
@@ -12,6 +12,7 @@ #import "base/mac/bind_objc_block.h" #import "remoting/client/display/sys_opengl.h" +#import "remoting/ios/display/eagl_view.h" #import "remoting/ios/display/gl_demo_screen.h" #include "base/bind.h" @@ -56,11 +57,10 @@ void OnFrameReceived(std::unique_ptr<webrtc::DesktopFrame> frame, const base::Closure& done); void Stop(); - void SurfaceCreated(GLKView* view); + void SurfaceCreated(EAGLView* view); void SurfaceChanged(int width, int height); std::unique_ptr<protocol::FrameConsumer> GrabFrameConsumer(); - EAGLContext* GetEAGLContext(); base::WeakPtr<Core> GetWeakPtr(); private: @@ -189,11 +189,11 @@ // demo_screen_ = nil; } -void Core::SurfaceCreated(GLKView* view) { +void Core::SurfaceCreated(EAGLView* view) { DCHECK(runtime_->display_task_runner()->BelongsToCurrentThread()); + DCHECK(eagl_context_); - // Bind the view's framebuffer object to OpenGL. - [view bindDrawable]; + [view startWithContext:eagl_context_]; renderer_->OnSurfaceCreated( base::MakeUnique<GlCanvas>(static_cast<int>([eagl_context_ API]))); @@ -210,10 +210,6 @@ renderer_->OnSurfaceChanged(width, height); } -EAGLContext* Core::GetEAGLContext() { - return eagl_context_; -} - base::WeakPtr<remoting::GlDisplayHandler::Core> Core::GetWeakPtr() { return weak_ptr_; } @@ -264,11 +260,7 @@ _core->GetWeakPtr(), _runtime->display_task_runner()); } -- (EAGLContext*)GetEAGLContext { - return _core->GetEAGLContext(); -} - -- (void)onSurfaceCreated:(GLKView*)view { +- (void)onSurfaceCreated:(EAGLView*)view { _runtime->display_task_runner()->PostTask( FROM_HERE, base::Bind(&remoting::GlDisplayHandler::Core::SurfaceCreated, _core->GetWeakPtr(), view));
diff --git a/remoting/ios/session/remoting_client.h b/remoting/ios/session/remoting_client.h index 6f0dbad..b8dd100f 100644 --- a/remoting/ios/session/remoting_client.h +++ b/remoting/ios/session/remoting_client.h
@@ -5,6 +5,7 @@ #ifndef REMOTING_IOS_SESSION_REMOTING_CLIENT_H_ #define REMOTING_IOS_SESSION_REMOTING_CLIENT_H_ +#import <CoreGraphics/CoreGraphics.h> #import <Foundation/Foundation.h> #import "remoting/ios/display/gl_display_handler.h"
diff --git a/services/ui/ws/event_dispatcher.cc b/services/ui/ws/event_dispatcher.cc index 8be6504..43dd93a1 100644 --- a/services/ui/ws/event_dispatcher.cc +++ b/services/ui/ws/event_dispatcher.cc
@@ -79,7 +79,7 @@ void EventDispatcher::SetMousePointerDisplayLocation( const gfx::Point& display_location, - const int64_t display_id) { + int64_t display_id) { DCHECK(pointer_targets_.empty()); SetMousePointerLocation(display_location, display_id); UpdateCursorProviderByLastKnownLocation(); @@ -221,34 +221,21 @@ void EventDispatcher::UpdateNonClientAreaForCurrentWindow() { if (mouse_cursor_source_window_) { - LocationTarget location_target = event_targeter_->FindTargetForLocation( - mouse_pointer_last_location_, mouse_pointer_display_id_); - if (location_target.deepest_window.window == mouse_cursor_source_window_) { - mouse_cursor_in_non_client_area_ = - mouse_cursor_source_window_ - ? location_target.deepest_window.in_non_client_area - : false; - } - SetMousePointerLocation(location_target.location_in_root, - location_target.display_id); + event_targeter_->FindTargetForLocation( + mouse_pointer_last_location_, mouse_pointer_display_id_, + base::BindOnce( + &EventDispatcher::UpdateNonClientAreaForCurrentWindowOnFoundWindow, + base::Unretained(this))); } } void EventDispatcher::UpdateCursorProviderByLastKnownLocation() { if (!mouse_button_down_) { - LocationTarget location_target = event_targeter_->FindTargetForLocation( - mouse_pointer_last_location_, mouse_pointer_display_id_); - SetMouseCursorSourceWindow(location_target.deepest_window.window); - if (mouse_cursor_source_window_) { - mouse_cursor_in_non_client_area_ = - location_target.deepest_window.in_non_client_area; - } else { - SetMouseCursorSourceWindow(delegate_->GetRootWindowContaining( - &mouse_pointer_last_location_, &mouse_pointer_display_id_)); - mouse_cursor_in_non_client_area_ = true; - } - SetMousePointerLocation(location_target.location_in_root, - location_target.display_id); + event_targeter_->FindTargetForLocation( + mouse_pointer_last_location_, mouse_pointer_display_id_, + base::BindOnce(&EventDispatcher:: + UpdateCursorProviderByLastKnownLocationOnFoundWindow, + base::Unretained(this))); } } @@ -280,8 +267,12 @@ accelerators_.erase(it); } +bool EventDispatcher::IsProcessingEvent() const { + return event_targeter_->IsHitTestInFlight(); +} + void EventDispatcher::ProcessEvent(const ui::Event& event, - const int64_t display_id, + int64_t display_id, AcceleratorMatchPhase match_phase) { #if !defined(NDEBUG) if (match_phase == AcceleratorMatchPhase::POST_ONLY) { @@ -314,8 +305,10 @@ } DCHECK(event.IsPointerEvent()); - ProcessPointerEvent(*event.AsPointerEvent()); - return; + event_targeter_->FindTargetForLocation( + event.AsPointerEvent()->root_location(), event_display_id_, + base::BindOnce(&EventDispatcher::ProcessPointerEventOnFoundTarget, + base::Unretained(this), *event.AsPointerEvent())); } ServerWindow* EventDispatcher::GetRootWindowContaining( @@ -324,6 +317,10 @@ return delegate_->GetRootWindowContaining(location_in_display, display_id); } +void EventDispatcher::ProcessNextAvailableEvent() { + delegate_->ProcessNextAvailableEvent(); +} + void EventDispatcher::SetMouseCursorSourceWindow(ServerWindow* window) { if (mouse_cursor_source_window_ == window) return; @@ -368,12 +365,10 @@ EventDispatcherDelegate::AcceleratorPhase::POST); } -void EventDispatcher::ProcessPointerEvent(const ui::PointerEvent& event) { - DCHECK(event.IsPointerEvent()); - +void EventDispatcher::ProcessPointerEventOnFoundTarget( + const ui::PointerEvent& event, + const LocationTarget& location_target) { PointerTarget pointer_target; - LocationTarget location_target = event_targeter_->FindTargetForLocation( - event.root_location(), event_display_id_); pointer_target.window = modal_window_controller_.GetTargetForWindow( location_target.deepest_window.window); pointer_target.is_mouse_event = event.IsMousePointerEvent(); @@ -462,7 +457,7 @@ // before we perform dispatch because the Delegate is going to read this // information from us. if (is_pointer_going_up && is_mouse_event) - UpdateCursorProviderByLastKnownLocation(); + UpdateCursorProviderByLastKnownLocationOnFoundWindow(location_target); DispatchToPointerTarget(pointer_targets_[pointer_id], *cloned_event->AsPointerEvent()); @@ -477,6 +472,41 @@ } } +void EventDispatcher::UpdateNonClientAreaForCurrentWindowOnFoundWindow( + const LocationTarget& location_target) { + if (!mouse_cursor_source_window_) + return; + + if (location_target.deepest_window.window == mouse_cursor_source_window_) { + mouse_cursor_in_non_client_area_ = + mouse_cursor_source_window_ + ? location_target.deepest_window.in_non_client_area + : false; + } + SetMousePointerLocation(location_target.location_in_root, + location_target.display_id); + delegate_->UpdateNativeCursorFromDispatcher(); +} + +void EventDispatcher::UpdateCursorProviderByLastKnownLocationOnFoundWindow( + const LocationTarget& location_target) { + if (mouse_button_down_) + return; + + SetMouseCursorSourceWindow(location_target.deepest_window.window); + if (mouse_cursor_source_window_) { + mouse_cursor_in_non_client_area_ = + location_target.deepest_window.in_non_client_area; + } else { + SetMouseCursorSourceWindow(delegate_->GetRootWindowContaining( + &mouse_pointer_last_location_, &mouse_pointer_display_id_)); + mouse_cursor_in_non_client_area_ = true; + } + SetMousePointerLocation(location_target.location_in_root, + location_target.display_id); + delegate_->UpdateNativeCursorFromDispatcher(); +} + void EventDispatcher::StartTrackingPointer( int32_t pointer_id, const PointerTarget& pointer_target) {
diff --git a/services/ui/ws/event_dispatcher.h b/services/ui/ws/event_dispatcher.h index 8d075b2..3cd80e92 100644 --- a/services/ui/ws/event_dispatcher.h +++ b/services/ui/ws/event_dispatcher.h
@@ -63,7 +63,7 @@ void Reset(); void SetMousePointerDisplayLocation(const gfx::Point& display_location, - const int64_t display_id); + int64_t display_id); const gfx::Point& mouse_pointer_last_location() const { return mouse_pointer_last_location_; } @@ -142,18 +142,24 @@ void RemoveAccelerator(uint32_t id); + // True if we are actively finding a target for an event, false otherwise. + bool IsProcessingEvent() const; + // Processes the supplied event, informing the delegate as approriate. This // may result in generating any number of events. If |match_phase| is // ANY and there is a matching accelerator with PRE_TARGET found, than only // OnAccelerator() is called. The expectation is after the PRE_TARGET has been // handled this is again called with an AcceleratorMatchPhase of POST_ONLY. + // This may be asynchronous if we need to find the target window for |event| + // asynchronously. void ProcessEvent(const ui::Event& event, - const int64_t display_id, + int64_t display_id, AcceleratorMatchPhase match_phase); // EventTargeterDelegate: ServerWindow* GetRootWindowContaining(gfx::Point* location_in_display, int64_t* display_id) override; + void ProcessNextAvailableEvent() override; private: friend class test::EventDispatcherTestApi; @@ -208,7 +214,17 @@ // when no buttons on the mouse are down. // This also generates exit events as appropriate. For example, if the mouse // moves between one window to another an exit is generated on the first. - void ProcessPointerEvent(const ui::PointerEvent& event); + // |pointer_target| is the PointerTarget for |event| based on the + // |deepest_window|, the deepest visible window for the root_location + // of the |event|. |location_in_display| and |display_id| are updated values + // for root_location and |event_display_id_| (e.g. during drag-n-drop). + void ProcessPointerEventOnFoundTarget(const ui::PointerEvent& event, + const LocationTarget& location_target); + + void UpdateNonClientAreaForCurrentWindowOnFoundWindow( + const LocationTarget& location_target); + void UpdateCursorProviderByLastKnownLocationOnFoundWindow( + const LocationTarget& location_target); // Adds |pointer_target| to |pointer_targets_|. void StartTrackingPointer(int32_t pointer_id,
diff --git a/services/ui/ws/event_dispatcher_delegate.h b/services/ui/ws/event_dispatcher_delegate.h index 28a2a0a1..9a25ecc 100644 --- a/services/ui/ws/event_dispatcher_delegate.h +++ b/services/ui/ws/event_dispatcher_delegate.h
@@ -31,13 +31,13 @@ }; virtual void OnAccelerator(uint32_t accelerator, - const int64_t display_id, + int64_t display_id, const ui::Event& event, AcceleratorPhase phase) = 0; virtual void SetFocusedWindowFromEventDispatcher(ServerWindow* window) = 0; virtual ServerWindow* GetFocusedWindowForEventDispatcher( - const int64_t display_id) = 0; + int64_t display_id) = 0; // Called when capture should be set on the native display. |window| is the // window capture is being set on. @@ -58,15 +58,18 @@ ServerWindow* old_capture) = 0; virtual void OnMouseCursorLocationChanged(const gfx::Point& point, - const int64_t display_id) = 0; + int64_t display_id) = 0; // Dispatches an event to the specific client. virtual void DispatchInputEventToWindow(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator) = 0; + // Starts processing the next event in the event queue. + virtual void ProcessNextAvailableEvent() = 0; + // Returns the id of the client to send events to. |in_nonclient_area| is // true if the event occurred in the non-client area of the window. virtual ClientSpecificId GetEventTargetClientId(const ServerWindow* window, @@ -86,7 +89,7 @@ // Called when event dispatch could not find a target. OnAccelerator may still // be called. virtual void OnEventTargetNotFound(const ui::Event& event, - const int64_t display_id) = 0; + int64_t display_id) = 0; protected: virtual ~EventDispatcherDelegate() {}
diff --git a/services/ui/ws/event_dispatcher_unittest.cc b/services/ui/ws/event_dispatcher_unittest.cc index 7888872..9c213007 100644 --- a/services/ui/ws/event_dispatcher_unittest.cc +++ b/services/ui/ws/event_dispatcher_unittest.cc
@@ -9,9 +9,12 @@ #include <queue> +#include "base/command_line.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" +#include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "services/ui/common/accelerator_util.h" #include "services/ui/ws/accelerator.h" #include "services/ui/ws/event_dispatcher_delegate.h" @@ -106,7 +109,7 @@ private: // EventDispatcherDelegate: void OnAccelerator(uint32_t accelerator, - const int64_t display_id, + int64_t display_id, const ui::Event& event, AcceleratorPhase phase) override { EXPECT_EQ(0u, last_accelerator_); @@ -114,7 +117,7 @@ last_accelerator_phase_ = phase; } ServerWindow* GetFocusedWindowForEventDispatcher( - const int64_t display_id) override { + int64_t display_id) override { return focused_window_; } void SetNativeCapture(ServerWindow* window) override {} @@ -128,10 +131,10 @@ lost_capture_window_ = old_capture_window; } void OnMouseCursorLocationChanged(const gfx::Point& point, - const int64_t display_id) override {} + int64_t display_id) override {} void DispatchInputEventToWindow(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator) override { std::unique_ptr<DispatchedEventDetails> details(new DispatchedEventDetails); @@ -141,6 +144,7 @@ details->accelerator = accelerator; dispatched_event_queue_.push(std::move(details)); } + void ProcessNextAvailableEvent() override {} ClientSpecificId GetEventTargetClientId(const ServerWindow* window, bool in_nonclient_area) override { return in_nonclient_area ? kNonclientAreaId : kClientAreaId; @@ -150,7 +154,7 @@ return root_; } void OnEventTargetNotFound(const ui::Event& event, - const int64_t display_id) override { + int64_t display_id) override { last_event_target_not_found_ = ui::Event::Clone(event); } @@ -198,16 +202,97 @@ ASSERT_EQ(location, details->event->AsLocatedEvent()->location()); } -void RunMouseEventTests(EventDispatcher* dispatcher, - TestEventDispatcherDelegate* dispatcher_delegate, - MouseEventTest* tests, - size_t test_count) { +} // namespace + +// Test fixture for EventDispatcher with friend access to verify the internal +// state. Setup creates a TestServerWindowDelegate, a visible root ServerWindow, +// a TestEventDispatcher and the EventDispatcher for testing. +class EventDispatcherTest : public testing::TestWithParam<bool>, + public TestEventDispatcherDelegate::Delegate { + public: + EventDispatcherTest() {} + ~EventDispatcherTest() override {} + + ServerWindow* root_window() { return root_window_.get(); } + TestEventDispatcherDelegate* test_event_dispatcher_delegate() { + return test_event_dispatcher_delegate_.get(); + } + EventDispatcher* event_dispatcher() { return event_dispatcher_.get(); } + + void DispatchEvent(EventDispatcher* dispatcher, + const ui::Event& event, + int64_t display_id, + EventDispatcher::AcceleratorMatchPhase match_phase); + void SetMousePointerDisplayLocation(EventDispatcher* dispatcher, + const gfx::Point& display_location, + int64_t display_id); + void RunMouseEventTests(EventDispatcher* dispatcher, + TestEventDispatcherDelegate* dispatcher_delegate, + MouseEventTest* tests, + size_t test_count); + bool AreAnyPointersDown() const; + // Deletes everything created during SetUp() + void ClearSetup(); + std::unique_ptr<ServerWindow> CreateChildWindowWithParent( + const WindowId& id, + ServerWindow* parent); + // Creates a window which is a child of |root_window_|. + std::unique_ptr<ServerWindow> CreateChildWindow(const WindowId& id); + bool IsMouseButtonDown() const; + bool IsWindowPointerTarget(const ServerWindow* window) const; + int NumberPointerTargetsForWindow(ServerWindow* window) const; + ServerWindow* GetActiveSystemModalWindow() const; + + protected: + // testing::TestWithParam<bool>: + void SetUp() override; + + private: + // TestEventDispatcherDelegate::Delegate: + void ReleaseCapture() override { + event_dispatcher_->SetCaptureWindow(nullptr, kInvalidClientId); + } + + void RunTasks(); + + std::unique_ptr<TestServerWindowDelegate> window_delegate_; + std::unique_ptr<ServerWindow> root_window_; + std::unique_ptr<TestEventDispatcherDelegate> test_event_dispatcher_delegate_; + std::unique_ptr<EventDispatcher> event_dispatcher_; + + base::test::ScopedTaskEnvironment scoped_task_environment_; + + DISALLOW_COPY_AND_ASSIGN(EventDispatcherTest); +}; + +void EventDispatcherTest::DispatchEvent( + EventDispatcher* dispatcher, + const ui::Event& event, + int64_t display_id, + EventDispatcher::AcceleratorMatchPhase match_phase) { + dispatcher->ProcessEvent(event, display_id, match_phase); + RunTasks(); +} + +void EventDispatcherTest::SetMousePointerDisplayLocation( + EventDispatcher* dispatcher, + const gfx::Point& display_location, + int64_t display_id) { + dispatcher->SetMousePointerDisplayLocation(display_location, display_id); + RunTasks(); +} + +void EventDispatcherTest::RunMouseEventTests( + EventDispatcher* dispatcher, + TestEventDispatcherDelegate* dispatcher_delegate, + MouseEventTest* tests, + size_t test_count) { for (size_t i = 0; i < test_count; ++i) { const MouseEventTest& test = tests[i]; ASSERT_FALSE(dispatcher_delegate->has_queued_events()) << " unexpected queued events before running " << i; - dispatcher->ProcessEvent(ui::PointerEvent(test.input_event), 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, ui::PointerEvent(test.input_event), 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); @@ -225,54 +310,6 @@ } } -} // namespace - -// Test fixture for EventDispatcher with friend access to verify the internal -// state. Setup creates a TestServerWindowDelegate, a visible root ServerWindow, -// a TestEventDispatcher and the EventDispatcher for testing. -class EventDispatcherTest : public testing::Test, - public TestEventDispatcherDelegate::Delegate { - public: - EventDispatcherTest() {} - ~EventDispatcherTest() override {} - - ServerWindow* root_window() { return root_window_.get(); } - TestEventDispatcherDelegate* test_event_dispatcher_delegate() { - return test_event_dispatcher_delegate_.get(); - } - EventDispatcher* event_dispatcher() { return event_dispatcher_.get(); } - - bool AreAnyPointersDown() const; - // Deletes everything created during SetUp() - void ClearSetup(); - std::unique_ptr<ServerWindow> CreateChildWindowWithParent( - const WindowId& id, - ServerWindow* parent); - // Creates a window which is a child of |root_window_|. - std::unique_ptr<ServerWindow> CreateChildWindow(const WindowId& id); - bool IsMouseButtonDown() const; - bool IsWindowPointerTarget(const ServerWindow* window) const; - int NumberPointerTargetsForWindow(ServerWindow* window) const; - ServerWindow* GetActiveSystemModalWindow() const; - - protected: - // testing::Test: - void SetUp() override; - - private: - // TestEventDispatcherDelegate::Delegate: - void ReleaseCapture() override { - event_dispatcher_->SetCaptureWindow(nullptr, kInvalidClientId); - } - - std::unique_ptr<TestServerWindowDelegate> window_delegate_; - std::unique_ptr<ServerWindow> root_window_; - std::unique_ptr<TestEventDispatcherDelegate> test_event_dispatcher_delegate_; - std::unique_ptr<EventDispatcher> event_dispatcher_; - - DISALLOW_COPY_AND_ASSIGN(EventDispatcherTest); -}; - bool EventDispatcherTest::AreAnyPointersDown() const { return EventDispatcherTestApi(event_dispatcher_.get()).AreAnyPointersDown(); } @@ -321,8 +358,22 @@ return ModalWindowControllerTestApi(mwc).GetActiveSystemModalWindow(); } +void EventDispatcherTest::RunTasks() { + bool enable_async_event_targeting = GetParam(); + if (!enable_async_event_targeting) + return; + + base::RunLoop runloop; + runloop.RunUntilIdle(); +} + void EventDispatcherTest::SetUp() { - testing::Test::SetUp(); + bool enable_async_event_targeting = GetParam(); + if (enable_async_event_targeting) { + base::CommandLine::ForCurrentProcess()->AppendSwitch( + "enable-async-event-targeting"); + } + testing::TestWithParam<bool>::SetUp(); window_delegate_ = base::MakeUnique<TestServerWindowDelegate>(); root_window_ = @@ -337,7 +388,7 @@ test_event_dispatcher_delegate_->set_root(root_window_.get()); } -TEST_F(EventDispatcherTest, ProcessEvent) { +TEST_P(EventDispatcherTest, ProcessEvent) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -347,8 +398,8 @@ const ui::PointerEvent ui_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(20, 25), gfx::Point(20, 25), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(ui_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), ui_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -363,11 +414,11 @@ EXPECT_EQ(gfx::Point(10, 15), dispatched_event->location()); } -TEST_F(EventDispatcherTest, ProcessEventNoTarget) { +TEST_P(EventDispatcherTest, ProcessEventNoTarget) { // Send event without a target. ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - event_dispatcher()->ProcessEvent(key, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Event wasn't dispatched to a target. std::unique_ptr<DispatchedEventDetails> details = @@ -382,7 +433,7 @@ EXPECT_EQ(ui::VKEY_A, event_out->AsKeyEvent()->key_code()); } -TEST_F(EventDispatcherTest, AcceleratorBasic) { +TEST_P(EventDispatcherTest, AcceleratorBasic) { ClearSetup(); TestEventDispatcherDelegate event_dispatcher_delegate(nullptr); EventDispatcher dispatcher(&event_dispatcher_delegate); @@ -420,7 +471,7 @@ EXPECT_TRUE(dispatcher.AddAccelerator(accelerator_3, std::move(matcher))); } -TEST_F(EventDispatcherTest, EventMatching) { +TEST_P(EventDispatcherTest, EventMatching) { TestEventDispatcherDelegate* event_dispatcher_delegate = test_event_dispatcher_delegate(); EventDispatcher* dispatcher = event_dispatcher(); @@ -431,7 +482,8 @@ dispatcher->AddAccelerator(accelerator_1, std::move(matcher)); ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_W, ui::EF_CONTROL_DOWN); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(accelerator_1, event_dispatcher_delegate->GetAndClearLastAccelerator()); @@ -439,29 +491,33 @@ // ignoring. key = ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_NUM_LOCK_ON); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(accelerator_1, event_dispatcher_delegate->GetAndClearLastAccelerator()); key = ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_W, ui::EF_NONE); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(0u, event_dispatcher_delegate->GetAndClearLastAccelerator()); uint32_t accelerator_2 = 2; matcher = ui::CreateKeyMatcher(ui::mojom::KeyboardCode::W, ui::mojom::kEventFlagNone); dispatcher->AddAccelerator(accelerator_2, std::move(matcher)); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(accelerator_2, event_dispatcher_delegate->GetAndClearLastAccelerator()); dispatcher->RemoveAccelerator(accelerator_2); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(0u, event_dispatcher_delegate->GetAndClearLastAccelerator()); } // Tests that a post-target accelerator is not triggered by ProcessEvent. -TEST_F(EventDispatcherTest, PostTargetAccelerator) { +TEST_P(EventDispatcherTest, PostTargetAccelerator) { TestEventDispatcherDelegate* event_dispatcher_delegate = test_event_dispatcher_delegate(); EventDispatcher* dispatcher = event_dispatcher(); @@ -474,7 +530,8 @@ ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_W, ui::EF_CONTROL_DOWN); // The post-target accelerator should be fired if there is no focused window. - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(accelerator_1, event_dispatcher_delegate->GetAndClearLastAccelerator()); std::unique_ptr<DispatchedEventDetails> details = @@ -486,7 +543,8 @@ event_dispatcher_delegate->SetFocusedWindowFromEventDispatcher(child.get()); // With a focused window the event should be dispatched. - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(0u, event_dispatcher_delegate->GetAndClearLastAccelerator()); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(details); @@ -498,14 +556,15 @@ EXPECT_FALSE(accelerator_weak_ptr); // Post deletion there should be no accelerator - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(0u, event_dispatcher_delegate->GetAndClearLastAccelerator()); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(details); EXPECT_FALSE(details->accelerator); } -TEST_F(EventDispatcherTest, ProcessPost) { +TEST_P(EventDispatcherTest, ProcessPost) { TestEventDispatcherDelegate* event_dispatcher_delegate = test_event_dispatcher_delegate(); EventDispatcher* dispatcher = event_dispatcher(); @@ -533,15 +592,16 @@ // Dispatch for ANY, which should trigger PRE and not call // DispatchInputEventToWindow(). ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_W, ui::EF_CONTROL_DOWN); - dispatcher->ProcessEvent(key, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); EXPECT_EQ(EventDispatcherDelegate::AcceleratorPhase::PRE, event_dispatcher_delegate->last_accelerator_phase()); EXPECT_EQ(pre_id, event_dispatcher_delegate->GetAndClearLastAccelerator()); EXPECT_FALSE(event_dispatcher_delegate->has_queued_events()); // Dispatch for POST, which should trigger POST. - dispatcher->ProcessEvent(key, 0, - EventDispatcher::AcceleratorMatchPhase::POST_ONLY); + DispatchEvent(dispatcher, key, 0, + EventDispatcher::AcceleratorMatchPhase::POST_ONLY); std::unique_ptr<DispatchedEventDetails> details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); ASSERT_TRUE(details); @@ -549,7 +609,7 @@ EXPECT_EQ(post_id, details->accelerator->id()); } -TEST_F(EventDispatcherTest, Capture) { +TEST_P(EventDispatcherTest, Capture) { ServerWindow* root = root_window(); std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); @@ -592,7 +652,7 @@ tests, arraysize(tests)); } -TEST_F(EventDispatcherTest, CaptureMultipleMouseButtons) { +TEST_P(EventDispatcherTest, CaptureMultipleMouseButtons) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -635,7 +695,7 @@ tests, arraysize(tests)); } -TEST_F(EventDispatcherTest, ClientAreaGoesToOwner) { +TEST_P(EventDispatcherTest, ClientAreaGoesToOwner) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -651,8 +711,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(12, 12), gfx::Point(12, 12), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target child and be in the non-client area. std::unique_ptr<DispatchedEventDetails> details = @@ -666,8 +726,8 @@ const ui::PointerEvent move_event( ui::MouseEvent(ui::ET_MOUSE_MOVED, gfx::Point(17, 18), gfx::Point(17, 18), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, 0)); - dispatcher->ProcessEvent(move_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, move_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Still same target. details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); @@ -679,8 +739,8 @@ const ui::PointerEvent release_event(ui::MouseEvent( ui::ET_MOUSE_RELEASED, gfx::Point(17, 18), gfx::Point(17, 18), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(release_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, release_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // The event should not have been dispatched to the delegate. details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); @@ -693,8 +753,8 @@ const ui::PointerEvent press_event2(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(21, 22), gfx::Point(21, 22), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event2, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event2, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(event_dispatcher_delegate->has_queued_events()); ASSERT_EQ(child.get(), details->window); @@ -708,7 +768,7 @@ EXPECT_EQ(ui::ET_POINTER_DOWN, details->event->type()); } -TEST_F(EventDispatcherTest, AdditionalClientArea) { +TEST_P(EventDispatcherTest, AdditionalClientArea) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -724,8 +784,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(28, 11), gfx::Point(28, 11), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target child and be in the client area. std::unique_ptr<DispatchedEventDetails> details = @@ -735,7 +795,7 @@ EXPECT_TRUE(details->IsClientArea()); } -TEST_F(EventDispatcherTest, HitTestMask) { +TEST_P(EventDispatcherTest, HitTestMask) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -746,8 +806,8 @@ const ui::PointerEvent move1(ui::MouseEvent( ui::ET_MOUSE_MOVED, gfx::Point(11, 11), gfx::Point(11, 11), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, 0)); - event_dispatcher()->ProcessEvent(move1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), move1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Event went through the child window and hit the root. std::unique_ptr<DispatchedEventDetails> details1 = @@ -761,8 +821,8 @@ const ui::PointerEvent move2(ui::MouseEvent( ui::ET_MOUSE_MOVED, gfx::Point(11, 12), gfx::Point(11, 12), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, 0)); - event_dispatcher()->ProcessEvent(move2, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), move2, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Mouse exits the root. std::unique_ptr<DispatchedEventDetails> details2 = @@ -776,7 +836,7 @@ EXPECT_TRUE(details3->IsClientArea()); } -TEST_F(EventDispatcherTest, DontFocusOnSecondDown) { +TEST_P(EventDispatcherTest, DontFocusOnSecondDown) { std::unique_ptr<ServerWindow> child1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> child2 = CreateChildWindow(WindowId(1, 4)); @@ -792,8 +852,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(12, 12), gfx::Point(12, 12), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_FALSE(event_dispatcher_delegate->has_queued_events()); @@ -806,15 +866,15 @@ const ui::PointerEvent touch_event(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(53, 54), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 2))); - dispatcher->ProcessEvent(touch_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_FALSE(event_dispatcher_delegate->has_queued_events()); EXPECT_EQ(child2.get(), details->window); EXPECT_EQ(nullptr, event_dispatcher_delegate->GetAndClearLastFocusedWindow()); } -TEST_F(EventDispatcherTest, TwoPointersActive) { +TEST_P(EventDispatcherTest, TwoPointersActive) { std::unique_ptr<ServerWindow> child1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> child2 = CreateChildWindow(WindowId(1, 4)); @@ -830,8 +890,8 @@ const ui::PointerEvent touch_event1(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(12, 13), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(touch_event1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child1.get(), details->window); @@ -840,8 +900,8 @@ const ui::PointerEvent drag_event1(ui::TouchEvent( ui::ET_TOUCH_MOVED, gfx::Point(53, 54), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(drag_event1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, drag_event1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child1.get(), details->window); @@ -849,8 +909,8 @@ const ui::PointerEvent touch_event2(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(54, 55), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 2))); - dispatcher->ProcessEvent(touch_event2, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event2, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child2.get(), details->window); @@ -858,14 +918,14 @@ const ui::PointerEvent drag_event2(ui::TouchEvent( ui::ET_TOUCH_MOVED, gfx::Point(13, 14), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 2))); - dispatcher->ProcessEvent(drag_event2, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, drag_event2, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child2.get(), details->window); // Drag again with id 1, child1 should continue to get it. - dispatcher->ProcessEvent(drag_event1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, drag_event1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child1.get(), details->window); @@ -873,20 +933,20 @@ const ui::PointerEvent touch_release(ui::TouchEvent( ui::ET_TOUCH_RELEASED, gfx::Point(54, 55), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(touch_release, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_release, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child1.get(), details->window); const ui::PointerEvent touch_event3(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(54, 55), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 2))); - dispatcher->ProcessEvent(touch_event3, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event3, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(child2.get(), details->window); } -TEST_F(EventDispatcherTest, DestroyWindowWhileGettingEvents) { +TEST_P(EventDispatcherTest, DestroyWindowWhileGettingEvents) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -900,8 +960,8 @@ const ui::PointerEvent touch_event1(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(12, 13), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(touch_event1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_FALSE(event_dispatcher_delegate->has_queued_events()); @@ -913,13 +973,13 @@ const ui::PointerEvent drag_event1(ui::TouchEvent( ui::ET_TOUCH_MOVED, gfx::Point(53, 54), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(drag_event1, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, drag_event1, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(nullptr, details.get()); } -TEST_F(EventDispatcherTest, MouseInExtendedHitTestRegion) { +TEST_P(EventDispatcherTest, MouseInExtendedHitTestRegion) { ServerWindow* root = root_window(); std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); @@ -934,8 +994,8 @@ const ui::PointerEvent ui_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(8, 9), gfx::Point(8, 9), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(ui_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, ui_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); ASSERT_EQ(root, details->window); @@ -944,8 +1004,8 @@ const ui::PointerEvent release_event(ui::MouseEvent( ui::ET_MOUSE_RELEASED, gfx::Point(8, 9), gfx::Point(8, 9), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(release_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, release_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_FALSE(event_dispatcher_delegate->has_queued_events()); ASSERT_EQ(root, details->window); @@ -954,8 +1014,8 @@ // Change the extended hit test region and send event in extended hit test // region. Should result in exit for root, followed by press for child. child->set_extended_hit_test_region(gfx::Insets(5, 5, 5, 5)); - dispatcher->ProcessEvent(ui_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, ui_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_EQ(root, details->window); EXPECT_EQ(ui::ET_POINTER_EXITED, details->event->type()); @@ -971,7 +1031,7 @@ EXPECT_EQ(gfx::Point(-2, -1), details->event->AsPointerEvent()->location()); } -TEST_F(EventDispatcherTest, WheelWhileDown) { +TEST_P(EventDispatcherTest, WheelWhileDown) { std::unique_ptr<ServerWindow> child1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> child2 = CreateChildWindow(WindowId(1, 4)); @@ -1000,7 +1060,7 @@ // Tests that when explicit capture has been set that all events go to the // designated window, and that when capture is cleared, events find the // appropriate target window. -TEST_F(EventDispatcherTest, SetExplicitCapture) { +TEST_P(EventDispatcherTest, SetExplicitCapture) { ServerWindow* root = root_window(); std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); @@ -1020,8 +1080,8 @@ const ui::PointerEvent left_press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(left_press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, left_press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target child. std::unique_ptr<DispatchedEventDetails> details = @@ -1037,8 +1097,8 @@ ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(right_press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, right_press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(IsMouseButtonDown()); @@ -1047,8 +1107,8 @@ ui::ET_MOUSE_RELEASED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(left_release_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, left_release_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(IsMouseButtonDown()); @@ -1056,8 +1116,8 @@ const ui::PointerEvent touch_event(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(15, 15), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 2))); - dispatcher->ProcessEvent(touch_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(IsMouseButtonDown()); @@ -1066,8 +1126,8 @@ ui::MouseEvent(ui::ET_MOUSE_MOVED, gfx::Point(15, 5), gfx::Point(15, 5), base::TimeTicks(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(move_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, move_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_TRUE(IsMouseButtonDown()); @@ -1076,8 +1136,8 @@ ui::MouseEvent(ui::ET_MOUSE_RELEASED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(right_release_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, right_release_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); EXPECT_FALSE(IsMouseButtonDown()); } @@ -1088,8 +1148,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target the root. std::unique_ptr<DispatchedEventDetails> details = @@ -1102,7 +1162,7 @@ // This test verifies that explicit capture overrides and resets implicit // capture. -TEST_F(EventDispatcherTest, ExplicitCaptureOverridesImplicitCapture) { +TEST_P(EventDispatcherTest, ExplicitCaptureOverridesImplicitCapture) { ServerWindow* root = root_window(); std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); @@ -1148,8 +1208,8 @@ const ui::PointerEvent touch_event(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(12, 13), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(touch_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); } std::unique_ptr<DispatchedEventDetails> details = @@ -1181,8 +1241,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(15, 15), gfx::Point(15, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target the root. details = event_dispatcher_delegate->GetAndAdvanceDispatchedEventDetails(); @@ -1193,7 +1253,7 @@ // Tests that setting capture does delete active pointer targets for the capture // window. -TEST_F(EventDispatcherTest, CaptureUpdatesActivePointerTargets) { +TEST_P(EventDispatcherTest, CaptureUpdatesActivePointerTargets) { ServerWindow* root = root_window(); root->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1202,8 +1262,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), gfx::Point(5, 5), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - dispatcher->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1214,8 +1274,8 @@ const ui::PointerEvent touch_event(ui::TouchEvent( ui::ET_TOUCH_PRESSED, gfx::Point(12, 13), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 1))); - dispatcher->ProcessEvent(touch_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(dispatcher, touch_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); } ASSERT_TRUE(AreAnyPointersDown()); @@ -1231,7 +1291,7 @@ // Tests that when explicit capture is changed, that the previous window with // capture is no longer being observed. -TEST_F(EventDispatcherTest, UpdatingCaptureStopsObservingPreviousCapture) { +TEST_P(EventDispatcherTest, UpdatingCaptureStopsObservingPreviousCapture) { std::unique_ptr<ServerWindow> child1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> child2 = CreateChildWindow(WindowId(1, 4)); @@ -1254,7 +1314,7 @@ // Tests that destroying a window with explicit capture clears the capture // state. -TEST_F(EventDispatcherTest, DestroyingCaptureWindowRemovesExplicitCapture) { +TEST_P(EventDispatcherTest, DestroyingCaptureWindowRemovesExplicitCapture) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); child->SetBounds(gfx::Rect(10, 10, 20, 20)); @@ -1271,7 +1331,7 @@ // Tests that when |client_id| is set for a window performing capture, that this // preference is used regardless of whether an event targets the client region. -TEST_F(EventDispatcherTest, CaptureInNonClientAreaOverridesActualPoint) { +TEST_P(EventDispatcherTest, CaptureInNonClientAreaOverridesActualPoint) { ServerWindow* root = root_window(); root->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1285,8 +1345,8 @@ const ui::PointerEvent press_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(6, 6), gfx::Point(6, 6), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(press_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), press_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); // Events should target child and be in the client area. std::unique_ptr<DispatchedEventDetails> details = @@ -1296,7 +1356,7 @@ EXPECT_TRUE(details->IsNonclientArea()); } -TEST_F(EventDispatcherTest, ProcessPointerEvents) { +TEST_P(EventDispatcherTest, ProcessPointerEvents) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1306,8 +1366,8 @@ const ui::PointerEvent pointer_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(20, 25), gfx::Point(20, 25), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent( - pointer_event, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), pointer_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1328,8 +1388,8 @@ ui::ET_TOUCH_RELEASED, gfx::Point(25, 20), base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, touch_id))); - event_dispatcher()->ProcessEvent( - pointer_event, 0, EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), pointer_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1346,7 +1406,7 @@ } } -TEST_F(EventDispatcherTest, ResetClearsPointerDown) { +TEST_P(EventDispatcherTest, ResetClearsPointerDown) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1356,8 +1416,8 @@ const ui::PointerEvent ui_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(20, 25), gfx::Point(20, 25), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(ui_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), ui_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1371,7 +1431,7 @@ EXPECT_FALSE(AreAnyPointersDown()); } -TEST_F(EventDispatcherTest, ResetClearsCapture) { +TEST_P(EventDispatcherTest, ResetClearsCapture) { ServerWindow* root = root_window(); root->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1385,7 +1445,7 @@ } // Tests that events on a modal parent target the modal child. -TEST_F(EventDispatcherTest, ModalWindowEventOnModalParent) { +TEST_P(EventDispatcherTest, ModalWindowEventOnModalParent) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 5)); @@ -1400,8 +1460,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(15, 15), gfx::Point(15, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1418,7 +1478,7 @@ } // Tests that events on a modal child target the modal child itself. -TEST_F(EventDispatcherTest, ModalWindowEventOnModalChild) { +TEST_P(EventDispatcherTest, ModalWindowEventOnModalChild) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 5)); @@ -1433,8 +1493,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(55, 15), gfx::Point(55, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1452,7 +1512,7 @@ // Tests that events on an unrelated window are not affected by the modal // window. -TEST_F(EventDispatcherTest, ModalWindowEventOnUnrelatedWindow) { +TEST_P(EventDispatcherTest, ModalWindowEventOnUnrelatedWindow) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 5)); std::unique_ptr<ServerWindow> w3 = CreateChildWindow(WindowId(1, 6)); @@ -1469,8 +1529,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(75, 15), gfx::Point(75, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1488,7 +1548,7 @@ // Tests that events events on a descendant of a modal parent target the modal // child. -TEST_F(EventDispatcherTest, ModalWindowEventOnDescendantOfModalParent) { +TEST_P(EventDispatcherTest, ModalWindowEventOnDescendantOfModalParent) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w11 = CreateChildWindowWithParent(WindowId(1, 4), w1.get()); @@ -1506,8 +1566,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(25, 25), gfx::Point(25, 25), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1524,7 +1584,7 @@ } // Tests that events on a system modal window target the modal window itself. -TEST_F(EventDispatcherTest, ModalWindowEventOnSystemModal) { +TEST_P(EventDispatcherTest, ModalWindowEventOnSystemModal) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1535,8 +1595,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(15, 15), gfx::Point(15, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1553,7 +1613,7 @@ } // Tests that events outside of system modal window target the modal window. -TEST_F(EventDispatcherTest, ModalWindowEventOutsideSystemModal) { +TEST_P(EventDispatcherTest, ModalWindowEventOutsideSystemModal) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); @@ -1565,8 +1625,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(45, 15), gfx::Point(45, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1583,7 +1643,7 @@ } // Tests events on a sub-window of system modal window target the window itself. -TEST_F(EventDispatcherTest, ModalWindowEventSubWindowSystemModal) { +TEST_P(EventDispatcherTest, ModalWindowEventSubWindowSystemModal) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); w1->SetModalType(MODAL_TYPE_SYSTEM); event_dispatcher()->AddSystemModalWindow(w1.get()); @@ -1611,7 +1671,8 @@ for (size_t i = 0; i < arraysize(kTouchData); i++) { // Send touch press and check that the expected target receives it. - event_dispatcher()->ProcessEvent( + DispatchEvent( + event_dispatcher(), ui::PointerEvent(ui::TouchEvent( ui::ET_TOUCH_PRESSED, kTouchData[i].location, base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 0))), @@ -1622,7 +1683,8 @@ EXPECT_EQ(kTouchData[i].expected_target, details->window) << i; // Release touch. - event_dispatcher()->ProcessEvent( + DispatchEvent( + event_dispatcher(), ui::PointerEvent(ui::TouchEvent( ui::ET_TOUCH_RELEASED, kTouchData[i].location, base::TimeTicks(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 0))), @@ -1632,7 +1694,7 @@ } // Tests that setting capture to a descendant of a modal parent fails. -TEST_F(EventDispatcherTest, ModalWindowSetCaptureDescendantOfModalParent) { +TEST_P(EventDispatcherTest, ModalWindowSetCaptureDescendantOfModalParent) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w11 = CreateChildWindowWithParent(WindowId(1, 4), w1.get()); @@ -1651,7 +1713,7 @@ } // Tests that setting capture to a window unrelated to a modal parent works. -TEST_F(EventDispatcherTest, ModalWindowSetCaptureUnrelatedWindow) { +TEST_P(EventDispatcherTest, ModalWindowSetCaptureUnrelatedWindow) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 4)); std::unique_ptr<ServerWindow> w3 = CreateChildWindow(WindowId(1, 5)); @@ -1669,7 +1731,7 @@ } // Tests that setting capture fails when there is a system modal window. -TEST_F(EventDispatcherTest, ModalWindowSystemSetCapture) { +TEST_P(EventDispatcherTest, ModalWindowSystemSetCapture) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 4)); @@ -1684,7 +1746,7 @@ } // Tests having multiple system modal windows. -TEST_F(EventDispatcherTest, ModalWindowMultipleSystemModals) { +TEST_P(EventDispatcherTest, ModalWindowMultipleSystemModals) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); std::unique_ptr<ServerWindow> w2 = CreateChildWindow(WindowId(1, 4)); std::unique_ptr<ServerWindow> w3 = CreateChildWindow(WindowId(1, 5)); @@ -1726,7 +1788,7 @@ EXPECT_EQ(nullptr, GetActiveSystemModalWindow()); } -TEST_F(EventDispatcherTest, CaptureNotResetOnParentChange) { +TEST_P(EventDispatcherTest, CaptureNotResetOnParentChange) { std::unique_ptr<ServerWindow> w1 = CreateChildWindow(WindowId(1, 3)); w1->set_event_targeting_policy(mojom::EventTargetingPolicy::DESCENDANTS_ONLY); std::unique_ptr<ServerWindow> w11 = @@ -1743,8 +1805,8 @@ const ui::PointerEvent mouse_pressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(15, 15), gfx::Point(15, 15), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(mouse_pressed, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), mouse_pressed, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); event_dispatcher()->SetCaptureWindow(w11.get(), kClientAreaId); std::unique_ptr<DispatchedEventDetails> details = @@ -1761,7 +1823,7 @@ EventDispatcherTestApi(event_dispatcher()).capture_window()); } -TEST_F(EventDispatcherTest, ChangeCaptureFromClientToNonclient) { +TEST_P(EventDispatcherTest, ChangeCaptureFromClientToNonclient) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); event_dispatcher()->SetCaptureWindow(child.get(), kNonclientAreaId); EXPECT_EQ(kNonclientAreaId, @@ -1776,7 +1838,7 @@ EXPECT_EQ(kClientAreaId, event_dispatcher()->capture_window_client_id()); } -TEST_F(EventDispatcherTest, MoveMouseFromNoTargetToValidTarget) { +TEST_P(EventDispatcherTest, MoveMouseFromNoTargetToValidTarget) { ServerWindow* root = root_window(); root->set_event_targeting_policy( mojom::EventTargetingPolicy::DESCENDANTS_ONLY); @@ -1802,7 +1864,7 @@ tests, arraysize(tests)); } -TEST_F(EventDispatcherTest, NoTargetToTargetWithMouseDown) { +TEST_P(EventDispatcherTest, NoTargetToTargetWithMouseDown) { ServerWindow* root = root_window(); root->set_event_targeting_policy( mojom::EventTargetingPolicy::DESCENDANTS_ONLY); @@ -1835,7 +1897,7 @@ tests, arraysize(tests)); } -TEST_F(EventDispatcherTest, DontSendExitToSameClientWhenCaptureChanges) { +TEST_P(EventDispatcherTest, DontSendExitToSameClientWhenCaptureChanges) { ServerWindow* root = root_window(); root->set_event_targeting_policy( mojom::EventTargetingPolicy::DESCENDANTS_ONLY); @@ -1868,7 +1930,7 @@ EXPECT_FALSE(test_event_dispatcher_delegate()->has_queued_events()); } -TEST_F(EventDispatcherTest, MousePointerClearedOnDestroy) { +TEST_P(EventDispatcherTest, MousePointerClearedOnDestroy) { root_window()->set_event_targeting_policy( mojom::EventTargetingPolicy::DESCENDANTS_ONLY); std::unique_ptr<ServerWindow> c1 = CreateChildWindow(WindowId(1, 3)); @@ -1876,13 +1938,13 @@ root_window()->SetBounds(gfx::Rect(0, 0, 100, 100)); c1->SetBounds(gfx::Rect(10, 10, 20, 20)); - event_dispatcher()->SetMousePointerDisplayLocation(gfx::Point(15, 15), 0); + SetMousePointerDisplayLocation(event_dispatcher(), gfx::Point(15, 15), 0); EXPECT_EQ(c1.get(), event_dispatcher()->mouse_cursor_source_window()); c1.reset(); EXPECT_EQ(nullptr, event_dispatcher()->mouse_cursor_source_window()); } -TEST_F(EventDispatcherTest, LocationHonorsTransform) { +TEST_P(EventDispatcherTest, LocationHonorsTransform) { std::unique_ptr<ServerWindow> child = CreateChildWindow(WindowId(1, 3)); gfx::Transform transform; @@ -1896,8 +1958,8 @@ const ui::PointerEvent ui_event(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(20, 25), gfx::Point(20, 25), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); - event_dispatcher()->ProcessEvent(ui_event, 0, - EventDispatcher::AcceleratorMatchPhase::ANY); + DispatchEvent(event_dispatcher(), ui_event, 0, + EventDispatcher::AcceleratorMatchPhase::ANY); std::unique_ptr<DispatchedEventDetails> details = test_event_dispatcher_delegate()->GetAndAdvanceDispatchedEventDetails(); @@ -1912,6 +1974,8 @@ EXPECT_EQ(gfx::Point(5, 7), dispatched_event->location()); } +INSTANTIATE_TEST_CASE_P(/* no prefix */, EventDispatcherTest, testing::Bool()); + } // namespace test } // namespace ws } // namespace ui
diff --git a/services/ui/ws/event_targeter.cc b/services/ui/ws/event_targeter.cc index 1fb3f79e..531ea8e 100644 --- a/services/ui/ws/event_targeter.cc +++ b/services/ui/ws/event_targeter.cc
@@ -4,18 +4,72 @@ #include "services/ui/ws/event_targeter.h" +#include "base/command_line.h" +#include "base/memory/ptr_util.h" +#include "base/task_scheduler/post_task.h" +#include "base/threading/thread_task_runner_handle.h" #include "services/ui/ws/event_targeter_delegate.h" namespace ui { namespace ws { +EventTargeter::HitTestRequest::HitTestRequest(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback) + : location(location), + display_id(display_id), + callback(std::move(callback)) {} + +EventTargeter::HitTestRequest::~HitTestRequest() {} + EventTargeter::EventTargeter(EventTargeterDelegate* event_targeter_delegate) - : event_targeter_delegate_(event_targeter_delegate) {} + : event_targeter_delegate_(event_targeter_delegate), + hit_test_in_flight_(false), + weak_ptr_factory_(this) {} EventTargeter::~EventTargeter() {} -LocationTarget EventTargeter::FindTargetForLocation(const gfx::Point& location, - int64_t display_id) { +void EventTargeter::FindTargetForLocation(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback) { + if (IsHitTestInFlight()) { + std::unique_ptr<HitTestRequest> hittest_request = + base::MakeUnique<HitTestRequest>(location, display_id, + std::move(callback)); + hit_test_request_queue_.push(std::move(hittest_request)); + return; + } + + ProcessFindTarget(location, display_id, std::move(callback)); +} + +bool EventTargeter::IsHitTestInFlight() const { + return hit_test_in_flight_ || !hit_test_request_queue_.empty(); +} + +void EventTargeter::ProcessFindTarget(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback) { + // TODO(riajiang): After HitTestComponent is implemented, do synchronous + // hit-test for most cases using shared memory and only ask Blink + // asynchronously for hard cases. For now, assume all synchronous hit-tests + // failed if the "enable-async-event-targeting" flag is turned on. + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + "enable-async-event-targeting")) { + DCHECK(!hit_test_in_flight_); + hit_test_in_flight_ = true; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&EventTargeter::FindTargetForLocationNow, + weak_ptr_factory_.GetWeakPtr(), location, + display_id, base::Passed(&callback))); + } else { + FindTargetForLocationNow(location, display_id, std::move(callback)); + } +} + +void EventTargeter::FindTargetForLocationNow(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback) { LocationTarget location_target; location_target.location_in_root = location; location_target.display_id = display_id; @@ -26,7 +80,22 @@ ui::ws::FindDeepestVisibleWindowForLocation( root, location_target.location_in_root); } - return location_target; + std::move(callback).Run(location_target); + ProcessNextHitTestRequestFromQueue(); +} + +void EventTargeter::ProcessNextHitTestRequestFromQueue() { + hit_test_in_flight_ = false; + if (hit_test_request_queue_.empty()) { + event_targeter_delegate_->ProcessNextAvailableEvent(); + return; + } + + std::unique_ptr<HitTestRequest> hittest_request = + std::move(hit_test_request_queue_.front()); + hit_test_request_queue_.pop(); + ProcessFindTarget(hittest_request->location, hittest_request->display_id, + std::move(hittest_request->callback)); } } // namespace ws
diff --git a/services/ui/ws/event_targeter.h b/services/ui/ws/event_targeter.h index c71650a..a1f75013 100644 --- a/services/ui/ws/event_targeter.h +++ b/services/ui/ws/event_targeter.h
@@ -6,8 +6,11 @@ #define SERVICES_UI_WS_EVENT_TARGETER_H_ #include <stdint.h> +#include <queue> +#include "base/callback.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "services/ui/ws/window_finder.h" #include "ui/display/types/display_constants.h" #include "ui/gfx/geometry/point.h" @@ -24,20 +27,55 @@ int64_t display_id = display::kInvalidDisplayId; }; +using HitTestCallback = base::OnceCallback<void(const LocationTarget&)>; + // Finds the target window for a location. class EventTargeter { public: explicit EventTargeter(EventTargeterDelegate* event_targeter_delegate); ~EventTargeter(); - // Returns a LocationTarget for the supplied |location|. If there is no valid - // root window, |window| in the returned value is null. - LocationTarget FindTargetForLocation(const gfx::Point& location, - int64_t display_id); + // Calls WindowFinder to find the target for |location|. + // |callback| is called with the LocationTarget found. + void FindTargetForLocation(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback); + + bool IsHitTestInFlight() const; private: + struct HitTestRequest { + HitTestRequest(const gfx::Point& location, + int64_t display_id, + HitTestCallback hittest_callback); + ~HitTestRequest(); + + gfx::Point location; + int64_t display_id; + HitTestCallback callback; + }; + + void ProcessFindTarget(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback); + + void FindTargetForLocationNow(const gfx::Point& location, + int64_t display_id, + HitTestCallback callback); + + void ProcessNextHitTestRequestFromQueue(); + EventTargeterDelegate* event_targeter_delegate_; + // True if we are waiting for the result of a hit-test. False otherwise. + bool hit_test_in_flight_; + + // Requests for a new location while waiting on an existing request are added + // here. + std::queue<std::unique_ptr<HitTestRequest>> hit_test_request_queue_; + + base::WeakPtrFactory<EventTargeter> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(EventTargeter); };
diff --git a/services/ui/ws/event_targeter_delegate.h b/services/ui/ws/event_targeter_delegate.h index 2e46860..f9f00d4 100644 --- a/services/ui/ws/event_targeter_delegate.h +++ b/services/ui/ws/event_targeter_delegate.h
@@ -23,6 +23,10 @@ virtual ServerWindow* GetRootWindowContaining(gfx::Point* location_in_display, int64_t* display_id) = 0; + // Calls EventDispatcherDelegate::ProcessNextAvailableEvent, see + // event_dispatcher_delegate.h for details. + virtual void ProcessNextAvailableEvent() = 0; + protected: virtual ~EventTargeterDelegate() {} };
diff --git a/services/ui/ws/test_utils.h b/services/ui/ws/test_utils.h index dc2803dd8fa..1734541 100644 --- a/services/ui/ws/test_utils.h +++ b/services/ui/ws/test_utils.h
@@ -207,7 +207,7 @@ void DispatchInputEventToWindow(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator) { wms_->DispatchInputEventToWindow(target, client_id, display_id, event, @@ -233,19 +233,22 @@ } WindowTree* tree_awaiting_input_ack() { - return wms_->in_flight_event_details_ ? wms_->in_flight_event_details_->tree - : nullptr; + return wms_->in_flight_event_dispatch_details_ + ? wms_->in_flight_event_dispatch_details_->tree + : nullptr; } + bool is_event_queue_empty() const { return wms_->event_queue_.empty(); } + const std::vector<std::unique_ptr<WindowManagerDisplayRoot>>& window_manager_display_roots() const { return wms_->window_manager_display_roots_; } bool AckInFlightEvent(mojom::EventResult result) { - if (!wms_->in_flight_event_details_) + if (!wms_->in_flight_event_dispatch_details_) return false; - wms_->OnEventAck(wms_->in_flight_event_details_->tree, result); + wms_->OnEventAck(wms_->in_flight_event_dispatch_details_->tree, result); return true; }
diff --git a/services/ui/ws/window_manager_state.cc b/services/ui/ws/window_manager_state.cc index eec94676..df51174 100644 --- a/services/ui/ws/window_manager_state.cc +++ b/services/ui/ws/window_manager_state.cc
@@ -15,6 +15,7 @@ #include "services/ui/ws/display.h" #include "services/ui/ws/display_creation_config.h" #include "services/ui/ws/display_manager.h" +#include "services/ui/ws/event_targeter.h" #include "services/ui/ws/platform_display.h" #include "services/ui/ws/server_window.h" #include "services/ui/ws/user_display_manager.h" @@ -74,7 +75,7 @@ } // namespace -WindowManagerState::InFlightEventDetails::InFlightEventDetails( +WindowManagerState::InFlightEventDispatchDetails::InFlightEventDispatchDetails( WindowManagerState* window_manager_state, WindowTree* tree, int64_t display_id, @@ -86,7 +87,8 @@ phase(phase), weak_factory(window_manager_state) {} -WindowManagerState::InFlightEventDetails::~InFlightEventDetails() {} +WindowManagerState::InFlightEventDispatchDetails:: + ~InFlightEventDispatchDetails() {} class WindowManagerState::ProcessedEventTarget { public: @@ -213,10 +215,11 @@ const std::unordered_map<std::string, std::vector<uint8_t>>& drag_data, uint32_t drag_operation) { int32_t drag_pointer = MouseEvent::kMousePointerId; - if (in_flight_event_details_ && - in_flight_event_details_->event->IsPointerEvent()) { - drag_pointer = - in_flight_event_details_->event->AsPointerEvent()->pointer_details().id; + if (in_flight_event_dispatch_details_ && + in_flight_event_dispatch_details_->event->IsPointerEvent()) { + drag_pointer = in_flight_event_dispatch_details_->event->AsPointerEvent() + ->pointer_details() + .id; } else { NOTIMPLEMENTED() << "Set drag drop set up during something other than a " << "pointer event; rejecting drag."; @@ -271,13 +274,14 @@ void WindowManagerState::OnWillDestroyTree(WindowTree* tree) { event_dispatcher_.OnWillDestroyDragTargetConnection(tree); - if (!in_flight_event_details_ || in_flight_event_details_->tree != tree) + if (!in_flight_event_dispatch_details_ || + in_flight_event_dispatch_details_->tree != tree) return; // The WindowTree is dying. So it's not going to ack the event. // If the dying tree matches the root |tree_| mark as handled so we don't // notify it of accelerators. - OnEventAck(in_flight_event_details_->tree, + OnEventAck(in_flight_event_dispatch_details_->tree, tree == window_tree_ ? mojom::EventResult::HANDLED : mojom::EventResult::UNHANDLED); } @@ -295,7 +299,7 @@ } void WindowManagerState::Activate(const gfx::Point& mouse_location_on_display, - const int64_t display_id) { + int64_t display_id) { SetAllRootWindowsVisible(true); event_dispatcher_.Reset(); event_dispatcher_.SetMousePointerDisplayLocation(mouse_location_on_display, @@ -315,7 +319,8 @@ int64_t display_id) { // If this is still waiting for an ack from a previously sent event, then // queue up the event to be dispatched once the ack is received. - if (in_flight_event_details_) { + if (event_dispatcher_.IsProcessingEvent() || + in_flight_event_dispatch_details_) { if (!event_queue_.empty() && !event_queue_.back()->processed_target && EventsCanBeCoalesced(*event_queue_.back()->event, event)) { event_queue_.back()->event = CoalesceEvents( @@ -333,12 +338,12 @@ void WindowManagerState::OnAcceleratorAck( mojom::EventResult result, const std::unordered_map<std::string, std::vector<uint8_t>>& properties) { - DCHECK(in_flight_event_details_); + DCHECK(in_flight_event_dispatch_details_); DCHECK_EQ(EventDispatchPhase::PRE_TARGET_ACCELERATOR, - in_flight_event_details_->phase); + in_flight_event_dispatch_details_->phase); - std::unique_ptr<InFlightEventDetails> details = - std::move(in_flight_event_details_); + std::unique_ptr<InFlightEventDispatchDetails> details = + std::move(in_flight_event_dispatch_details_); if (result == mojom::EventResult::UNHANDLED) { DCHECK(details->event->IsKeyEvent()); @@ -352,7 +357,7 @@ // We don't do this first to ensure we don't send an event twice to clients. window_server()->SendToPointerWatchers(*details->event, user_id(), nullptr, nullptr, details->display_id); - ProcessNextEventFromQueue(); + ProcessNextAvailableEvent(); } } @@ -412,9 +417,9 @@ void WindowManagerState::OnEventAck(mojom::WindowTree* tree, mojom::EventResult result) { - DCHECK(in_flight_event_details_); - std::unique_ptr<InFlightEventDetails> details = - std::move(in_flight_event_details_); + DCHECK(in_flight_event_dispatch_details_); + std::unique_ptr<InFlightEventDispatchDetails> details = + std::move(in_flight_event_dispatch_details_); if (result == mojom::EventResult::UNHANDLED && details->post_target_accelerator) { @@ -422,23 +427,26 @@ *details->event, AcceleratorPhase::POST); } - ProcessNextEventFromQueue(); + ProcessNextAvailableEvent(); } void WindowManagerState::OnEventAckTimeout(ClientSpecificId client_id) { WindowTree* hung_tree = window_server()->GetTreeWithId(client_id); if (hung_tree && !hung_tree->janky()) window_tree_->ClientJankinessChanged(hung_tree); - if (in_flight_event_details_->phase == + if (in_flight_event_dispatch_details_->phase == EventDispatchPhase::PRE_TARGET_ACCELERATOR) { OnAcceleratorAck(mojom::EventResult::UNHANDLED, KeyEvent::Properties()); } else { - OnEventAck(in_flight_event_details_->tree, mojom::EventResult::UNHANDLED); + OnEventAck(in_flight_event_dispatch_details_->tree, + mojom::EventResult::UNHANDLED); } } void WindowManagerState::ProcessEventImpl(const ui::Event& event, int64_t display_id) { + DCHECK(!in_flight_event_dispatch_details_ && + !event_dispatcher_.IsProcessingEvent()); // Debug accelerators are always checked and don't interfere with processing. ProcessDebugAccelerator(event, display_id); event_dispatcher_.ProcessEvent(event, display_id, @@ -456,32 +464,15 @@ event_queue_.push(std::move(queued_event)); } -void WindowManagerState::ProcessNextEventFromQueue() { - // Loop through |event_queue_| stopping after dispatching the first valid - // event. - while (!event_queue_.empty()) { - std::unique_ptr<QueuedEvent> queued_event = std::move(event_queue_.front()); - event_queue_.pop(); - if (!queued_event->processed_target) { - ProcessEventImpl(*queued_event->event, queued_event->display_id); - return; - } - if (queued_event->processed_target->IsValid()) { - DispatchInputEventToWindowImpl( - queued_event->processed_target->window(), - queued_event->processed_target->client_id(), queued_event->display_id, - *queued_event->event, queued_event->processed_target->accelerator()); - return; - } - } -} - +// TODO(riajiang): We might want to do event targeting for the next event while +// waiting for the current event to be dispatched. crbug.com/724521 void WindowManagerState::DispatchInputEventToWindowImpl( ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, base::WeakPtr<Accelerator> accelerator) { + DCHECK(!in_flight_event_dispatch_details_); DCHECK(target); if (target->parent() == nullptr) target = GetWindowManagerRootForDisplayRoot(target); @@ -495,17 +486,18 @@ DCHECK(tree); ScheduleInputEventTimeout(tree, target, display_id, event, EventDispatchPhase::TARGET); - in_flight_event_details_->post_target_accelerator = accelerator; + in_flight_event_dispatch_details_->post_target_accelerator = accelerator; // Ignore |tree| because it will receive the event via normal dispatch. - window_server()->SendToPointerWatchers(event, user_id(), target, tree, - in_flight_event_details_->display_id); + window_server()->SendToPointerWatchers( + event, user_id(), target, tree, + in_flight_event_dispatch_details_->display_id); tree->DispatchInputEvent( target, event, - base::BindOnce(&WindowManagerState::OnEventAck, - in_flight_event_details_->weak_factory.GetWeakPtr(), - tree)); + base::BindOnce( + &WindowManagerState::OnEventAck, + in_flight_event_dispatch_details_->weak_factory.GetWeakPtr(), tree)); } void WindowManagerState::AddDebugAccelerators() { @@ -516,7 +508,7 @@ } void WindowManagerState::ProcessDebugAccelerator(const ui::Event& event, - const int64_t display_id) { + int64_t display_id) { if (event.type() != ui::ET_KEY_PRESSED) return; @@ -530,7 +522,7 @@ } void WindowManagerState::HandleDebugAccelerator(DebugAcceleratorType type, - const int64_t display_id) { + int64_t display_id) { #if DCHECK_IS_ON() // Error so it will be collected in system logs. for (Display* display : display_manager()->displays()) { @@ -549,12 +541,12 @@ void WindowManagerState::ScheduleInputEventTimeout(WindowTree* tree, ServerWindow* target, - const int64_t display_id, + int64_t display_id, const Event& event, EventDispatchPhase phase) { - std::unique_ptr<InFlightEventDetails> details = - base::MakeUnique<InFlightEventDetails>(this, tree, display_id, event, - phase); + std::unique_ptr<InFlightEventDispatchDetails> details = + base::MakeUnique<InFlightEventDispatchDetails>(this, tree, display_id, + event, phase); // TOOD(sad): Adjust this delay, possibly make this dynamic. const base::TimeDelta max_delay = base::debug::BeingDebugged() @@ -564,10 +556,10 @@ FROM_HERE, max_delay, base::Bind(&WindowManagerState::OnEventAckTimeout, details->weak_factory.GetWeakPtr(), tree->id())); - in_flight_event_details_ = std::move(details); + in_flight_event_dispatch_details_ = std::move(details); } -bool WindowManagerState::ConvertPointToScreen(const int64_t display_id, +bool WindowManagerState::ConvertPointToScreen(int64_t display_id, gfx::Point* point) { Display* display = display_manager()->GetDisplayById(display_id); if (display) { @@ -584,19 +576,19 @@ // EventDispatcherDelegate: void WindowManagerState::OnAccelerator(uint32_t accelerator_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, AcceleratorPhase phase) { DCHECK(IsActive()); const bool needs_ack = phase == AcceleratorPhase::PRE; WindowTree::AcceleratorCallback ack_callback; if (needs_ack) { - DCHECK(!in_flight_event_details_); + DCHECK(!in_flight_event_dispatch_details_); ScheduleInputEventTimeout(window_tree_, nullptr, display_id, event, EventDispatchPhase::PRE_TARGET_ACCELERATOR); - ack_callback = - base::BindOnce(&WindowManagerState::OnAcceleratorAck, - in_flight_event_details_->weak_factory.GetWeakPtr()); + ack_callback = base::BindOnce( + &WindowManagerState::OnAcceleratorAck, + in_flight_event_dispatch_details_->weak_factory.GetWeakPtr()); } window_tree_->OnAccelerator(accelerator_id, event, std::move(ack_callback)); } @@ -608,7 +600,7 @@ } ServerWindow* WindowManagerState::GetFocusedWindowForEventDispatcher( - const int64_t display_id) { + int64_t display_id) { ServerWindow* focused_window = window_server()->GetFocusedWindow(); if (focused_window) return focused_window; @@ -655,7 +647,7 @@ void WindowManagerState::OnMouseCursorLocationChanged( const gfx::Point& point_in_display, - const int64_t display_id) { + int64_t display_id) { gfx::Point point_in_screen(point_in_display); if (ConvertPointToScreen(display_id, &point_in_screen)) { window_server() @@ -669,13 +661,13 @@ void WindowManagerState::DispatchInputEventToWindow(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator) { DCHECK(IsActive()); // TODO(sky): this needs to see if another wms has capture and if so forward // to it. - if (in_flight_event_details_) { + if (in_flight_event_dispatch_details_) { std::unique_ptr<ProcessedEventTarget> processed_event_target( new ProcessedEventTarget(target, client_id, accelerator)); QueueEvent(event, std::move(processed_event_target), display_id); @@ -689,6 +681,33 @@ weak_accelerator); } +void WindowManagerState::ProcessNextAvailableEvent() { + // Loop through |event_queue_| stopping after dispatching the first valid + // event. + while (!event_queue_.empty()) { + if (in_flight_event_dispatch_details_) + return; + + if (!event_queue_.front()->processed_target && + event_dispatcher_.IsProcessingEvent()) + return; + + std::unique_ptr<QueuedEvent> queued_event = std::move(event_queue_.front()); + event_queue_.pop(); + if (!queued_event->processed_target) { + ProcessEventImpl(*queued_event->event, queued_event->display_id); + return; + } + if (queued_event->processed_target->IsValid()) { + DispatchInputEventToWindowImpl( + queued_event->processed_target->window(), + queued_event->processed_target->client_id(), queued_event->display_id, + *queued_event->event, queued_event->processed_target->accelerator()); + return; + } + } +} + ClientSpecificId WindowManagerState::GetEventTargetClientId( const ServerWindow* window, bool in_nonclient_area) { @@ -760,7 +779,7 @@ } void WindowManagerState::OnEventTargetNotFound(const ui::Event& event, - const int64_t display_id) { + int64_t display_id) { window_server()->SendToPointerWatchers(event, user_id(), nullptr, /* window */ nullptr /* ignore_tree */, display_id); if (event.IsMousePointerEvent())
diff --git a/services/ui/ws/window_manager_state.h b/services/ui/ws/window_manager_state.h index 818c179..c936136b 100644 --- a/services/ui/ws/window_manager_state.h +++ b/services/ui/ws/window_manager_state.h
@@ -100,7 +100,7 @@ bool IsActive() const; void Activate(const gfx::Point& mouse_location_on_display, - const int64_t display_id); + int64_t display_id); void Deactivate(); // Processes an event from PlatformDisplay. @@ -157,13 +157,13 @@ }; // Tracks state associated with an event being dispatched to a client. - struct InFlightEventDetails { - InFlightEventDetails(WindowManagerState* window_manager_state, - WindowTree* tree, - int64_t display_id, - const Event& event, - EventDispatchPhase phase); - ~InFlightEventDetails(); + struct InFlightEventDispatchDetails { + InFlightEventDispatchDetails(WindowManagerState* window_manager_state, + WindowTree* tree, + int64_t display_id, + const Event& event, + EventDispatchPhase phase); + ~InFlightEventDispatchDetails(); base::OneShotTimer timer; WindowTree* tree; @@ -217,15 +217,10 @@ std::unique_ptr<ProcessedEventTarget> processed_event_target, int64_t display_id); - // Processes the next valid event in |event_queue_|. If the event has already - // been processed it is dispatched, otherwise the event is passed to the - // EventDispatcher for processing. - void ProcessNextEventFromQueue(); - // Dispatches the event to the appropriate client and starts the ack timer. void DispatchInputEventToWindowImpl(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const Event& event, base::WeakPtr<Accelerator> accelerator); @@ -234,16 +229,15 @@ // Finds the debug accelerator for |event| and if one is found calls // HandleDebugAccelerator(). - void ProcessDebugAccelerator(const Event& event, const int64_t display_id); + void ProcessDebugAccelerator(const Event& event, int64_t display_id); // Runs the specified debug accelerator. - void HandleDebugAccelerator(DebugAcceleratorType type, - const int64_t display_id); + void HandleDebugAccelerator(DebugAcceleratorType type, int64_t display_id); // Called when waiting for an event or accelerator to be processed by |tree|. void ScheduleInputEventTimeout(WindowTree* tree, ServerWindow* target, - const int64_t display_id, + int64_t display_id, const Event& event, EventDispatchPhase phase); @@ -251,34 +245,36 @@ // the input should be in display-physical-pixel space, and the output is in // screen-dip space. Returns true if the |point| is successfully converted, // false otherwise. - bool ConvertPointToScreen(const int64_t display_id, gfx::Point* point); + bool ConvertPointToScreen(int64_t display_id, gfx::Point* point); // EventDispatcherDelegate: void OnAccelerator(uint32_t accelerator_id, - const int64_t display_id, + int64_t display_id, const Event& event, AcceleratorPhase phase) override; void SetFocusedWindowFromEventDispatcher(ServerWindow* window) override; - ServerWindow* GetFocusedWindowForEventDispatcher( - const int64_t display_id) override; + ServerWindow* GetFocusedWindowForEventDispatcher(int64_t display_id) override; void SetNativeCapture(ServerWindow* window) override; void ReleaseNativeCapture() override; void UpdateNativeCursorFromDispatcher() override; void OnCaptureChanged(ServerWindow* new_capture, ServerWindow* old_capture) override; void OnMouseCursorLocationChanged(const gfx::Point& point, - const int64_t display_id) override; + int64_t display_id) override; void DispatchInputEventToWindow(ServerWindow* target, ClientSpecificId client_id, - const int64_t display_id, + int64_t display_id, const Event& event, Accelerator* accelerator) override; + // Processes the next valid event in |event_queue_|. If the event has already + // been processed it is dispatched, otherwise the event is passed to the + // EventDispatcher for processing. + void ProcessNextAvailableEvent() override; ClientSpecificId GetEventTargetClientId(const ServerWindow* window, bool in_nonclient_area) override; ServerWindow* GetRootWindowContaining(gfx::Point* location_in_display, int64_t* display_id) override; - void OnEventTargetNotFound(const Event& event, - const int64_t display_id) override; + void OnEventTargetNotFound(const Event& event, int64_t display_id) override; // ServerWindowObserver: void OnWindowEmbeddedAppDisconnected(ServerWindow* window) override; @@ -291,13 +287,16 @@ bool got_frame_decoration_values_ = false; mojom::FrameDecorationValuesPtr frame_decoration_values_; + // Events can go into this queue if there's a hit-test in flight in + // EventDispatcher or if we are actively dispatching an event. std::queue<std::unique_ptr<QueuedEvent>> event_queue_; std::vector<DebugAccelerator> debug_accelerators_; // If non-null we're actively waiting for a response from a client for an // event. - std::unique_ptr<InFlightEventDetails> in_flight_event_details_; + std::unique_ptr<InFlightEventDispatchDetails> + in_flight_event_dispatch_details_; EventDispatcher event_dispatcher_;
diff --git a/services/ui/ws/window_manager_state_unittest.cc b/services/ui/ws/window_manager_state_unittest.cc index d1dc651..de07ca32 100644 --- a/services/ui/ws/window_manager_state_unittest.cc +++ b/services/ui/ws/window_manager_state_unittest.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "base/command_line.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" @@ -47,7 +48,7 @@ ServerWindow** server_window); void DispatchInputEventToWindow(ServerWindow* target, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator); void OnEventAckTimeout(ClientSpecificId client_id); @@ -100,13 +101,15 @@ // testing::Test: void SetUp() override; + protected: + // Handles WindowStateManager ack timeouts. + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + private: WindowEventTargetingHelper window_event_targeting_helper_; WindowManagerState* window_manager_state_; - // Handles WindowStateManager ack timeouts. - scoped_refptr<base::TestSimpleTaskRunner> task_runner_; TestWindowManager window_manager_; ServerWindow* window_ = nullptr; WindowTree* window_tree_ = nullptr; @@ -139,7 +142,7 @@ void WindowManagerStateTest::DispatchInputEventToWindow( ServerWindow* target, - const int64_t display_id, + int64_t display_id, const ui::Event& event, Accelerator* accelerator) { WindowManagerStateTestApi test_api(window_manager_state_); @@ -178,6 +181,22 @@ } } +class WindowManagerStateTestAsync : public WindowManagerStateTest { + public: + WindowManagerStateTestAsync() {} + ~WindowManagerStateTestAsync() override {} + + // WindowManagerStateTest: + void SetUp() override { + base::CommandLine::ForCurrentProcess()->AppendSwitch( + "enable-async-event-targeting"); + WindowManagerStateTest::SetUp(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(WindowManagerStateTestAsync); +}; + // Tests that when an event is dispatched with no accelerator, that post target // accelerator is not triggered. TEST_F(WindowManagerStateTest, NullAccelerator) { @@ -699,6 +718,41 @@ EXPECT_EQ(ui::CursorType::kPointer, cursor_type()); } +TEST_F(WindowManagerStateTestAsync, CursorResetOverNoTargetAsync) { + ASSERT_EQ(1u, window_server()->display_manager()->displays().size()); + const ClientWindowId child_window_id(11); + window_tree()->NewWindow(child_window_id, ServerWindow::Properties()); + ServerWindow* child_window = + window_tree()->GetWindowByClientId(child_window_id); + window_tree()->AddWindow(FirstRootId(window_tree()), child_window_id); + // Setup steps already do hit-test for mouse cursor update so this should go + // to the queue in EventDispatcher. + EXPECT_TRUE(window_manager_state()->event_dispatcher()->IsProcessingEvent()); + child_window->SetVisible(true); + child_window->SetBounds(gfx::Rect(0, 0, 20, 20)); + child_window->parent()->SetCursor(ui::CursorData(ui::CursorType::kCopy)); + // Move the mouse outside the bounds of the child, so that the mouse is not + // over any valid windows. Cursor should change to POINTER. + ui::PointerEvent move( + ui::ET_POINTER_MOVED, gfx::Point(25, 25), gfx::Point(25, 25), 0, 0, + ui::PointerDetails(EventPointerType::POINTER_TYPE_MOUSE, 0), + base::TimeTicks()); + WindowManagerStateTestApi test_api(window_manager_state()); + EXPECT_TRUE(test_api.is_event_queue_empty()); + window_manager_state()->ProcessEvent(move, 0); + // There's no event dispatching in flight but there's hit-test in flight in + // EventDispatcher so we still put event processing request into the queue + // in WindowManagerState. + EXPECT_FALSE(test_api.tree_awaiting_input_ack()); + EXPECT_TRUE(window_manager_state()->event_dispatcher()->IsProcessingEvent()); + EXPECT_FALSE(test_api.is_event_queue_empty()); + task_runner_->RunUntilIdle(); + EXPECT_TRUE(test_api.is_event_queue_empty()); + // The event isn't over a valid target, which should trigger resetting the + // cursor to POINTER. + EXPECT_EQ(ui::CursorType::kPointer, cursor_type()); +} + } // namespace test } // namespace ws } // namespace ui
diff --git a/services/ui/ws/window_server.cc b/services/ui/ws/window_server.cc index 1031515..2aaa85e 100644 --- a/services/ui/ws/window_server.cc +++ b/services/ui/ws/window_server.cc
@@ -621,8 +621,6 @@ EventDispatcher* event_dispatcher = display_root->window_manager_state()->event_dispatcher(); event_dispatcher->UpdateCursorProviderByLastKnownLocation(); - display_root->window_manager_state()->cursor_state().SetCurrentWindowCursor( - event_dispatcher->GetCurrentMouseCursor()); } } @@ -638,8 +636,6 @@ return; event_dispatcher->UpdateNonClientAreaForCurrentWindow(); - display_root->window_manager_state()->cursor_state().SetCurrentWindowCursor( - event_dispatcher->GetCurrentMouseCursor()); } bool WindowServer::IsUserInHighContrastMode(const UserId& user) const {
diff --git a/testing/buildbot/filters/ash_unittests_mus.filter b/testing/buildbot/filters/ash_unittests_mus.filter index f46660d..5a02a51 100644 --- a/testing/buildbot/filters/ash_unittests_mus.filter +++ b/testing/buildbot/filters/ash_unittests_mus.filter
@@ -8,8 +8,6 @@ -CursorWindowControllerTest.MoveToDifferentDisplay -CursorWindowControllerTest.VisibilityTest -DisplayManagerTest.SoftwareMirroringWithCompositingCursor --DisplayManagerTest.TestDeviceScaleOnlyChange --DisplayManagerTest.UnifiedDesktopWith2xDSF -DisplayManagerTest.UpdateMouseCursorAfterRotateZoom -DragDropControllerTest.CaptureLostCancelsDragDrop -DragDropControllerTest.DragCancelAcrossDisplays
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index 6b6c99c..50dfb029 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -2109,3 +2109,7 @@ Bug(none) paint/pagination/composited-paginated-outlined-box.html [ Failure ] Bug(none) paint/pagination/composited-paginated-inline.html [ Failure ] + +Bug(none) paint/invalidation/absolute-display-block-to-none.html [ Failure ] +Bug(none) paint/invalidation/overhanging-float-detach-repaint.html [ Failure ] +Bug(none) paint/invalidation/trailing-floats-root-line-box-overflow.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 8bac1eb..850d5c4 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -119,9 +119,6 @@ crbug.com/717389 [ Linux Debug ] virtual/gpu/fast/canvas/canvas-clip-rule.html [ Crash ] crbug.com/717389 [ Win7 Debug ] virtual/gpu/fast/canvas/canvas-clip-rule.html [ Timeout ] -# This test fails only when spv2 is enabled. -crbug.com/719533 compositing/overflow/absolute-element-in-isolated-composited-ancestor.html [ Failure ] - # ====== Paint team owned tests to here ====== #### external/wpt/css/css-position-3
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-forms-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-forms-expected.txt index f1503f3b5..c0b8795 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-forms-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-forms-expected.txt
@@ -218,19 +218,11 @@ FAIL input.type: setAttribute() to "datetime" assert_equals: IDL get expected "datetime" but got "text" PASS input.type: 3 tests FAIL input.type: setAttribute() to "DATETIME" assert_equals: IDL get expected "datetime" but got "text" -PASS input.type: 15 tests -FAIL input.type: setAttribute() to "weeK" assert_equals: IDL get expected "text" but got "week" -PASS input.type: 30 tests -FAIL input.type: setAttribute() to "checKbox" assert_equals: IDL get expected "text" but got "checkbox" -PASS input.type: 80 tests +PASS input.type: 127 tests FAIL input.type: IDL set to "datetime" assert_equals: IDL get expected "datetime" but got "text" PASS input.type: 3 tests FAIL input.type: IDL set to "DATETIME" assert_equals: IDL get expected "datetime" but got "text" -PASS input.type: 15 tests -FAIL input.type: IDL set to "weeK" assert_equals: IDL get expected "text" but got "week" -PASS input.type: 30 tests -FAIL input.type: IDL set to "checKbox" assert_equals: IDL get expected "text" but got "checkbox" -PASS input.type: 30 tests +PASS input.type: 77 tests PASS input.defaultValue (<input value>): 32 tests PASS input.align: 32 tests PASS input.useMap: 32 tests
diff --git a/third_party/WebKit/LayoutTests/fast/forms/input-type-change3-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/input-type-change3-expected.txt index 3ff4246..60d15b7 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/input-type-change3-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/input-type-change3-expected.txt
@@ -17,6 +17,8 @@ PASS input.getAttribute("type") for " button " is correctly " button ". PASS input.type for "checkbox" is correctly "checkbox". PASS input.getAttribute("type") for "checkbox" is correctly "checkbox". +PASS input.type for "checKbox" is correctly "text". +PASS input.getAttribute("type") for "checKbox" is correctly "checKbox". PASS input.type for "email" is correctly "email". PASS input.getAttribute("type") for "email" is correctly "email". PASS input.type for "file" is correctly "file".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/input-type-change3.html b/third_party/WebKit/LayoutTests/fast/forms/input-type-change3.html index 672999f4..9067b49 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/input-type-change3.html +++ b/third_party/WebKit/LayoutTests/fast/forms/input-type-change3.html
@@ -32,6 +32,7 @@ check("button", "button"); check(" button ", "text", " button "); check("checkbox", "checkbox"); +check("chec\u212Abox", "text", "chec\u212Abox"); check("email", "email"); check("file", "file"); check("hidden", "hidden");
diff --git a/third_party/WebKit/LayoutTests/fast/harness/resources/results-test.js b/third_party/WebKit/LayoutTests/fast/harness/resources/results-test.js index 14593b94..bfab1d70 100644 --- a/third_party/WebKit/LayoutTests/fast/harness/resources/results-test.js +++ b/third_party/WebKit/LayoutTests/fast/harness/resources/results-test.js
@@ -1,7 +1,8 @@ // To run these tests, load results.html in a browser. // You should see a series of PASS lines. -if (window.testRunner) +if (window.testRunner) { testRunner.dumpAsText(); +} var testStyles = document.createElement('style'); testStyles.innerText = ".test-pass { color: green; } .test-fail { color: red; }"; @@ -11,13 +12,11 @@ var g_log = ["You should see a series of PASS lines."]; // Make async actually be sync for the sake of simpler testing. -function async(func, args) -{ +function async(func, args) { func.apply(null, args); } -function mockResults() -{ +function mockResults() { return { tests: {}, "skipped": 0, @@ -32,8 +31,7 @@ }; } -function isFailureExpected(expected, actual) -{ +function isFailureExpected(expected, actual) { var isExpected = true; if (actual != 'SKIP') { var expectedArray = expected.split(' '); @@ -49,8 +47,7 @@ return isExpected; } -function mockExpectation(expected, actual) -{ +function mockExpectation(expected, actual) { return { expected: expected, time_ms: 1, @@ -62,31 +59,29 @@ function currentTestName() { var testName = 'TEST ' + g_testIndex; - if (g_testName) + if (g_testName) { testName += ' (' + g_testName + ')'; + } return testName; } -function logPass(msg) -{ - g_log.push('<span class="test-pass">' + msg + '</span>: ' + currentTestName()) +function logPass(msg) { + g_log.push('<span class="test-pass">' + msg + '</span>: ' + currentTestName()); } -function logFail(msg) -{ - g_log.push('<span class="test-fail">' + msg + '</span>: ' + currentTestName()) +function logFail(msg) { + g_log.push('<span class="test-fail">' + msg + '</span>: ' + currentTestName()); } -function assertTrue(bool) -{ - if (bool) +function assertTrue(bool) { + if (bool) { logPass('PASS'); - else + } else { logFail('FAIL'); + } } -function runTest(results, assertions, opt_testName, opt_localStorageValue) -{ +function runTest(results, assertions, opt_testName, opt_localStorageValue) { document.body.innerHTML = ''; g_testIndex++; g_state = undefined; @@ -107,24 +102,23 @@ } } -function runDefaultSingleRowTest(test, expected, actual, isExpected, textResults, imageResults, opt_testName) -{ - results = mockResults(); +function runDefaultSingleRowTest(test, expected, actual, isExpected, textResults, imageResults, opt_testName) { + var results = mockResults(); results.tests[test] = mockExpectation(expected, actual); runSingleRowTest(results, isExpected, textResults, imageResults, opt_testName); } -function runSingleRowTest(results, isExpected, textResults, imageResults, opt_testName) -{ +function runSingleRowTest(results, isExpected, textResults, imageResults, opt_testName) { for (var key in results.tests) var test = key; var expected = results.tests[test].expected; var actual = results.tests[test].actual; runTest(results, function() { - if (isExpected) + if (isExpected) { assertTrue(document.querySelector('tbody').className == 'expected'); - else + } else { assertTrue(document.querySelector('tbody').className.indexOf('expected') == -1); + } assertTrue(document.querySelector('tbody td:nth-child(1)').textContent == '+' + test + ' \u2691'); assertTrue(document.querySelector('tbody td:nth-child(2)').textContent == textResults); @@ -135,10 +129,9 @@ } -function runTests() -{ +function runTests() { var results = mockResults(); - var subtree = results.tests['foo'] = {} + var subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('PASS', 'TEXT'); runTest(results, function() { assertTrue(document.getElementById('image-results-header').textContent == ''); @@ -146,7 +139,7 @@ }, 'text results header'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'MISSING'); subtree['bar.html'].is_missing_text = true; subtree['bar.html'].is_missing_audio = true; @@ -160,7 +153,7 @@ }, 'actual result links'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('PASS', 'TEXT'); subtree['bar.html'].has_stderr = true; runTest(results, function() { @@ -169,7 +162,7 @@ }, 'stderr link'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'PASS'); subtree['bar1.html'] = mockExpectation('CRASH', 'PASS'); subtree['bar2.html'] = mockExpectation('IMAGE', 'PASS'); @@ -208,7 +201,7 @@ } results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'PASS'); subtree['bar-missing.html'] = mockExpectation('TEXT', 'MISSING'); subtree['bar-missing.html'].is_missing_text = true; @@ -220,15 +213,17 @@ expandAllExpectations(); assertTrue(document.querySelectorAll('tbody tr').length == 8); var expandLinks = document.querySelectorAll('.expand-button-text'); - for (var i = 0; i < expandLinks.length; i++) + for (var i = 0; i < expandLinks.length; i++) { assertTrue(isExpanded(expandLinks[i])); + } collapseAllExpectations(); // Collapsed expectations stay in the dom, but are display:none. assertTrue(document.querySelectorAll('tbody tr').length == 8); - var expandLinks = document.querySelectorAll('.expand-button-text'); - for (var i = 0; i < expandLinks.length; i++) + expandLinks = document.querySelectorAll('.expand-button-text'); + for (var i = 0; i < expandLinks.length; i++) { assertTrue(isCollapsed(expandLinks[i])); + } expandExpectations(expandLinks[1]); assertTrue(isCollapsed(expandLinks[0])); @@ -239,7 +234,7 @@ }, 'collapsing expectation rows'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('PASS', 'TEXT'); subtree['bar-expected-fail.html'] = mockExpectation('TEXT', 'TEXT'); runTest(results, function() { @@ -311,7 +306,7 @@ }, 'mismatch reftest'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar-flaky-pass.html'] = mockExpectation('PASS TEXT', 'PASS'); runTest(results, function() { assertTrue(!document.getElementById('results-table')); @@ -320,7 +315,7 @@ }, 'expected flaky and passed'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar-flaky-fail.html'] = mockExpectation('PASS TEXT', 'IMAGE PASS'); runTest(results, function() { assertTrue(!document.getElementById('results-table')); @@ -329,7 +324,7 @@ }, 'expected flaky and image mismatch'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar-flaky-expected.html'] = mockExpectation('PASS FAIL', 'PASS TEXT'); runTest(results, function() { assertTrue(!document.getElementById('results-table')); @@ -339,7 +334,7 @@ }, 'expected flaky and text mismatch'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar-really-long-path-that-should-probably-wrap-because-otherwise-the-table-will-be-too-wide.html'] = mockExpectation('PASS', 'TEXT'); runTest(results, function() { document.body.style.width = '800px'; @@ -350,14 +345,14 @@ }, 'long test name'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'TEXT'); runTest(results, function() { assertTrue(document.querySelector('tbody td:nth-child(2)').textContent.indexOf('pretty diff') != -1); }, 'pretty diff link'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'PASS'); subtree['bar-1.html'] = mockExpectation('TEXT', 'CRASH'); subtree['bar-5.html'] = mockExpectation('TEXT', 'IMAGE+TEXT'); @@ -382,7 +377,7 @@ }, 'TableSorter.sortColumn does not raise a JS error'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar-5.html'] = mockExpectation('TEXT', 'IMAGE+TEXT'); runTest(results, function() { expandAllExpectations(); @@ -393,7 +388,7 @@ target: png, clientX: x, clientY: y - } + }; PixelZoomer.showOnDelay = false; PixelZoomer.handleMouseMove(mockEvent); assertTrue(!!document.querySelector('.pixel-zoom-container')); @@ -401,7 +396,7 @@ }, 'zoom image on hover'); results = mockResults(); - var subtree = results.tests['fullscreen'] = {} + subtree = results.tests['fullscreen'] = {}; subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT'); runTest(results, function() { // Use a regexp to match windows and unix-style paths. @@ -413,7 +408,7 @@ shouldUseTracLinks = function() { return true; }; results = mockResults(); - var subtree = results.tests['fullscreen'] = {} + subtree = results.tests['fullscreen'] = {}; subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT'); runTest(results, function() { var expectedHref = 'https://crrev.com/' + results.chromium_revision + '/third_party/WebKit/LayoutTests/fullscreen/full-screen-api.html'; @@ -421,7 +416,7 @@ }, 'chromium revision link'); results = mockResults(); - var subtree = results.tests['fullscreen'] = {} + subtree = results.tests['fullscreen'] = {}; subtree['full-screen-api.html'] = mockExpectation('TEXT', 'IMAGE+TEXT'); results.chromium_revision = ''; runTest(results, function() { @@ -455,15 +450,17 @@ }, 'reading options from localstorage', '{"toggle-images":false,"show-expected-failures":true}'); function enclosingNodeWithTagNameHasClassName(node, tagName, className) { - while (node && (!node.tagName || node.localName != tagName)) + while (node && (!node.tagName || node.localName != tagName)) { node = node.parentNode; - if (!node) + } + if (!node) { return false; + } return node.className == className; } results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['expected-to-pass-but-crashed.html'] = mockExpectation('PASS', 'CRASH'); subtree['expected-to-pass-or-crash-and-crashed.html'] = mockExpectation('PASS CRASH', 'CRASH'); subtree['expected-to-pass-but-timeouted.html'] = mockExpectation('PASS', 'CRASH'); @@ -494,7 +491,7 @@ }, 'class names 1'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['expected-to-pass-or-crash-and-crashed.html'] = mockExpectation('PASS CRASH', 'CRASH'); subtree['expected-to-pass-or-timeout-and-timeouted.html'] = mockExpectation('PASS TIMEOUT', 'TIMEOUT'); subtree['expected-pass-or-fail-and-passed.html'] = mockExpectation('PASS FAIL', 'PASS'); @@ -516,7 +513,7 @@ }, 'class names 2'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'PASS'); subtree['crash.html'] = mockExpectation('IMAGE', 'CRASH'); subtree['flaky-fail.html'] = mockExpectation('PASS TEXT', 'IMAGE PASS'); @@ -530,7 +527,7 @@ }, 'crash and flaky fail test order'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['expected-missing.html'] = mockExpectation('MISSING', 'MISSING'); subtree['expected-missing.html'].is_missing_text = true; subtree['expected-missing.html'].is_missing_image = true; @@ -552,7 +549,7 @@ }, 'missing results table'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {} subtree['bar.html'] = mockExpectation('TEXT', 'FAIL'); subtree['bar1.html'] = mockExpectation('TEXT', 'FAIL'); subtree['bar2.html'] = mockExpectation('TEXT', 'FAIL'); @@ -578,7 +575,7 @@ }, 'keyboard shortcuts: next'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'FAIL'); subtree['bar1.html'] = mockExpectation('TEXT', 'FAIL'); subtree['bar2.html'] = mockExpectation('TEXT', 'FAIL'); @@ -690,7 +687,7 @@ }, 'keyboard shortcuts'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'PASS'); subtree['bar-1.html'] = mockExpectation('TEXT', 'CRASH'); subtree['bar-2.html'] = mockExpectation('PASS', 'IMAGE'); @@ -724,7 +721,7 @@ }, 'table titles 1'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('', 'PASS TEXT'); subtree['bar-1.html'] = mockExpectation('', 'TEXT IMAGE'); subtree['bar-2.html'] = mockExpectation('IMAGE TEXT', 'TEXT IMAGE'); @@ -739,7 +736,7 @@ }, 'table titles 2'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE'); subtree['bar1.html'] = mockExpectation('TEXT', 'TEXT'); subtree['bar2.html'] = mockExpectation('TEXT', 'TEXT'); @@ -759,7 +756,7 @@ }, 'flagging tests'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE'); subtree['bar1.html'] = mockExpectation('TEXT', 'IMAGE'); runTest(results, function() { @@ -769,7 +766,7 @@ }, 'flagged tests with newlines', '{"use-newlines":true}'); results = mockResults(); - var subtree = results.tests['foo'] = {} + subtree = results.tests['foo'] = {}; subtree['bar.html'] = mockExpectation('TEXT', 'IMAGE'); subtree['bar1.html'] = mockExpectation('TEXT', 'IMAGE'); runTest(results, function() { @@ -798,7 +795,7 @@ results.tests['foo'].has_repaint_overlay = true; runTest(results, function() { assertTrue(document.querySelector('tbody td:nth-child(2)').textContent.indexOf('overlay') != -1); - }, 'repaint overlay') + }, 'repaint overlay'); document.body.innerHTML = '<pre>' + g_log.join('\n') + '</pre>'; }
diff --git a/third_party/WebKit/LayoutTests/fast/harness/results.html b/third_party/WebKit/LayoutTests/fast/harness/results.html index 5a669d84..9fbfacf 100644 --- a/third_party/WebKit/LayoutTests/fast/harness/results.html +++ b/third_party/WebKit/LayoutTests/fast/harness/results.html
@@ -1,8 +1,11 @@ <!DOCTYPE html> +<html> +<head> <style> html { height: 100%; } + body { margin: 0; font-family: Helvetica, sans-serif; @@ -200,9 +203,11 @@ <style id="unexpected-style"></style> <script> +'use strict'; + var g_state; -function globalState() -{ + +function globalState() { if (!g_state) { g_state = { crashTests: [], @@ -218,13 +223,15 @@ testsWithStderr: [], timeoutTests: [], unexpectedPassTests: [] - } + }; } return g_state; } -function ADD_RESULTS(input) -{ +// This function is used in the JSONP wrapper for failing_results.json; +// when failing_results.json is loaded, the global state will be populated +// with test results. +function ADD_RESULTS(input) { globalState().results = input; } </script> @@ -232,42 +239,42 @@ <script src="failing_results.json"></script> <script> -function stripExtension(test) -{ +'use strict'; + +function stripExtension(test) { var index = test.lastIndexOf('.'); return test.substring(0, index); } -function matchesSelector(node, selector) -{ - if (node.webkitMatchesSelector) +function matchesSelector(node, selector) { + if (node.webkitMatchesSelector) { return node.webkitMatchesSelector(selector); + } - if (node.mozMatchesSelector) + if (node.mozMatchesSelector) { return node.mozMatchesSelector(selector); + } } -function parentOfType(node, selector) -{ +function parentOfType(node, selector) { while (node = node.parentNode) { - if (matchesSelector(node, selector)) + if (matchesSelector(node, selector)) { return node; + } } return null; } -function remove(node) -{ +function remove(node) { node.parentNode.removeChild(node); } -function forEach(nodeList, handler) -{ +function forEach(nodeList, handler) { Array.prototype.forEach.call(nodeList, handler); } -function resultIframe(src) -{ +// Returns HTML for an img or iframe element showing expected or actual results. +function resultIframe(src) { // FIXME: use audio tags for AUDIO tests? var layoutTestsIndex = src.indexOf('LayoutTests'); var name; @@ -277,60 +284,61 @@ name = prefix + src.substring(layoutTestsIndex + 'LayoutTests/'.length); } else { var lastDashIndex = src.lastIndexOf('-pretty'); - if (lastDashIndex == -1) + if (lastDashIndex == -1) { lastDashIndex = src.lastIndexOf('-'); + } name = src.substring(lastDashIndex + 1); } var tagName = (src.lastIndexOf('.png') == -1) ? 'iframe' : 'img'; - if (tagName != 'img') + if (tagName != 'img') { src += '?format=txt'; - return '<div class=result-container><div class=label>' + name + '</div><' + tagName + ' src="' + src + '"></' + tagName + '></div>'; + } + return '<div class=result-container><div class=label>' + + name + '</div><' + tagName + ' src="' + src + '"></' + tagName + '></div>'; } -function togglingImage(prefix) -{ - return '<div class=result-container><div class="label imageText"></div><img class=animatedImage data-prefix="' + - prefix + '"></img></div>'; +function togglingImage(prefix) { + return '<div class=result-container><div class="label imageText"></div>' + + '<img class=animatedImage data-prefix="' + prefix + '"></img></div>'; } -function toggleExpectations(element) -{ +function toggleExpectations(element) { var expandLink = element; - if (expandLink.className != 'expand-button-text') + if (expandLink.className != 'expand-button-text') { expandLink = expandLink.querySelector('.expand-button-text'); + } - if (expandLink.textContent == '+') + if (expandLink.textContent == '+') { expandExpectations(expandLink, true); - else + } else { collapseExpectations(expandLink); + } } -function collapseExpectations(expandLink) -{ +function collapseExpectations(expandLink) { expandLink.textContent = '+'; var existingResultsRow = parentOfType(expandLink, 'tbody').querySelector('.results-row'); - if (existingResultsRow) + if (existingResultsRow) { updateExpandedState(existingResultsRow, false); + } } -function updateExpandedState(row, isExpanded) -{ +function updateExpandedState(row, isExpanded) { row.setAttribute('data-expanded', isExpanded); updateImageTogglingTimer(); } -function appendHTML(node, html) -{ - if (node.insertAdjacentHTML) +function appendHTML(node, html) { + if (node.insertAdjacentHTML) { node.insertAdjacentHTML('beforeEnd', html); - else + } else { node.innerHTML += html; + } } -function expandExpectations(expandLink, selectRow) -{ +function expandExpectations(expandLink, selectRow) { var row = parentOfType(expandLink, 'tr'); var parentTbody = row.parentNode; var existingResultsRow = parentTbody.querySelector('.results-row'); @@ -339,8 +347,9 @@ expandLink.textContent = enDash; if (existingResultsRow) { updateExpandedState(existingResultsRow, true); - if (selectRow) + if (selectRow) { TestNavigator._setCurrentTest(parentTbody); + } return; } @@ -350,15 +359,14 @@ newCell.colSpan = row.querySelectorAll('td').length; var resultLinks = row.querySelectorAll('.result-link'); - var hasTogglingImages = false; for (var i = 0; i < resultLinks.length; i++) { var link = resultLinks[i]; var result; if (link.textContent == 'images') { - hasTogglingImages = true; result = togglingImage(link.getAttribute('data-prefix')); - } else + } else { result = resultIframe(link.href); + } appendHTML(newCell, result); } @@ -367,14 +375,15 @@ parentTbody.appendChild(newRow); updateExpandedState(newRow, true); - if (selectRow) + if (selectRow) { TestNavigator._setCurrentTest(parentTbody); + } updateImageTogglingTimer(); } -function updateImageTogglingTimer() -{ - var hasVisibleAnimatedImage = document.querySelector('.results-row[data-expanded="true"] .animatedImage'); +function updateImageTogglingTimer() { + var hasVisibleAnimatedImage = document.querySelector( + '.results-row[data-expanded="true"] .animatedImage'); if (!hasVisibleAnimatedImage) { clearInterval(globalState().togglingImageInterval); globalState().togglingImageInterval = null; @@ -387,92 +396,92 @@ } } -function async(func, args) -{ +function async(func, args) { setTimeout(function() { func.apply(null, args); }, 100); } -function visibleTests(opt_container) -{ +function visibleTests(opt_container) { var container = opt_container || document; - if (onlyShowUnexpectedFailures()) + if (onlyShowUnexpectedFailures()) { return container.querySelectorAll('tbody:not(.expected)'); - else + } else { return container.querySelectorAll('tbody'); + } } -function visibleExpandLinks() -{ - if (onlyShowUnexpectedFailures()) +function visibleExpandLinks() { + if (onlyShowUnexpectedFailures()) { return document.querySelectorAll('tbody:not(.expected) .expand-button-text'); - else + } else { return document.querySelectorAll('.expand-button-text'); + } } -function expandAllExpectations() -{ +function expandAllExpectations() { var expandLinks = visibleExpandLinks(); - for (var i = 0, len = expandLinks.length; i < len; i++) + for (var i = 0, len = expandLinks.length; i < len; i++) { async(expandExpectations, [expandLinks[i]]); + } } -function collapseAllExpectations() -{ +function collapseAllExpectations() { var expandLinks = visibleExpandLinks(); - for (var i = 0, len = expandLinks.length; i < len; i++) + for (var i = 0, len = expandLinks.length; i < len; i++) { async(collapseExpectations, [expandLinks[i]]); + } } -function shouldUseTracLinks() -{ +function shouldUseTracLinks() { return !globalState().results.layout_tests_dir || !location.toString().indexOf('file://') == 0; } -function testLinkTarget(test) -{ +function testLinkTarget(test) { var virtualMatch = /virtual\/[^\/]+\/(.*)/.exec(test); var devirtualTest = virtualMatch ? virtualMatch[1] : test; var target; if (shouldUseTracLinks()) { var revision = globalState().results.chromium_revision; - if (revision) + if (revision) { target = 'https://crrev.com/' + revision; - else + } else { target = 'https://chromium.googlesource.com/chromium/src/+/master'; + } target += '/third_party/WebKit/LayoutTests/' + devirtualTest; - } else + } else { target = globalState().results.layout_tests_dir + '/' + devirtualTest; + } return target; } -function testLink(test) -{ +function testLink(test) { var target = testLinkTarget(test); - return '<a class=test-link href="' + target + '">' + test + '</a><span class=flag onclick="unflag(this)"> \u2691</span>'; + var flagChar = '\u2691'; + return '<a class=test-link href="' + target + '">' + test + + '</a><span class=flag onclick="unflag(this)"> ' + flagChar + '</span>'; } -function unflag(flag) -{ +function unflag(flag) { var shouldFlag = false; TestNavigator.flagTest(parentOfType(flag, 'tbody'), shouldFlag); TestNavigator.updateFlaggedTestTextBox(); } -function testLinkWithExpandButton(test) -{ - return '<span class=expand-button onclick="toggleExpectations(this)"><span class=expand-button-text>+</span></span>' + testLink(test); +function testLinkWithExpandButton(test) { + return '<span class=expand-button onclick="toggleExpectations(this)">' + + '<span class=expand-button-text>+</span></span>' + + testLink(test); } -function resultLink(testPrefix, suffix, contents) -{ - return '<a class=result-link href="' + testPrefix + suffix + '" data-prefix="' + testPrefix + '">' + contents + '</a> '; +function resultLink(testPrefix, suffix, contents) { + return '<a class=result-link href="' + testPrefix + suffix + + '" data-prefix="' + testPrefix + '">' + contents + '</a> '; } -function processGlobalStateFor(testObject) -{ +function processGlobalStateFor(testObject) { var test = testObject.name; - if (testObject.has_stderr) + if (testObject.has_stderr) { globalState().testsWithStderr.push(testObject); + } globalState().hasHttpTests = globalState().hasHttpTests || test.indexOf('http/') == 0; @@ -488,7 +497,8 @@ var actualTokens = actual.split(' '); var passedWithImageOnlyFailureInRetry = actualTokens[0] == 'TEXT' && actualTokens[1] == 'IMAGE'; - if (actualTokens[1] && actual.indexOf('PASS') != -1 || (!globalState().results.pixel_tests_enabled && passedWithImageOnlyFailureInRetry)) { + if (actualTokens[1] && actual.indexOf('PASS') != -1 || + (!globalState().results.pixel_tests_enabled && passedWithImageOnlyFailureInRetry)) { globalState().flakyPassTests.push(testObject); return; } @@ -516,10 +526,11 @@ } globalState().failingTests.push(testObject); + + // FIXME: Handle tests with actual == PASS and expected == PASS. } -function toggleImages() -{ +function toggleImages() { var images = document.querySelectorAll('.animatedImage'); var imageTexts = document.querySelectorAll('.imageText'); for (var i = 0, len = images.length; i < len; i++) { @@ -535,8 +546,7 @@ } } -function textResultLinks(test, prefix) -{ +function textResultLinks(test, prefix) { var html = resultLink(prefix, '-expected.txt', 'expected') + resultLink(prefix, '-actual.txt', 'actual') + resultLink(prefix, '-diff.txt', 'diff') + @@ -569,18 +579,19 @@ } } - if (actual.indexOf('MISSING') != -1 && testObject.is_missing_image) + if (actual.indexOf('MISSING') != -1 && testObject.is_missing_image) { row += resultLink(testPrefix, '-actual.png', 'png result'); + } return row; } -function tableRow(testObject) -{ +function tableRow(testObject) { var row = '<tbody class="' + (testObject.is_unexpected ? '' : 'expected') + '"'; row += ' data-testname="' + testObject.name + '"'; - if (testObject.reftest_type && testObject.reftest_type.indexOf('!=') != -1) + if (testObject.reftest_type && testObject.reftest_type.indexOf('!=') != -1) { row += ' mismatchreftest=true'; + } row += '><tr>'; row += '<td>' + testLinkWithExpandButton(testObject.name) + '</td>'; @@ -604,26 +615,31 @@ } if (actual.indexOf('MISSING') != -1) { - if (testObject.is_missing_audio) + if (testObject.is_missing_audio) { row += resultLink(testPrefix, '-actual.wav', 'audio result'); - if (testObject.is_missing_text) + } + if (testObject.is_missing_text) { row += resultLink(testPrefix, '-actual.txt', 'result'); + } } if (actual.indexOf('CRASH') != -1) { row += resultLink(testPrefix, '-crash-log.txt', 'crash log'); row += resultLink(testPrefix, '-sample.txt', 'sample'); - if (testObject.has_stderr) + if (testObject.has_stderr) { row += resultLink(testPrefix, '-stderr.txt', 'stderr'); + } } - if (testObject.has_repaint_overlay) + if (testObject.has_repaint_overlay) { row += resultLink(testPrefix, '-overlay.html?' + encodeURIComponent(testLinkTarget(testObject.name)), 'overlay'); + } var actualTokens = actual.split(/\s+/); var cell = imageResultsCell(testObject, testPrefix, actualTokens[0]); - if (!cell && actualTokens.length > 1) + if (!cell && actualTokens.length > 1) { cell = imageResultsCell(testObject, 'retries/' + testPrefix, actualTokens[1]); + } row += '</td><td>' + cell + '</td>' + '<td>' + actual + '</td>' + @@ -632,8 +648,7 @@ return row; } -function forEachTest(handler, opt_tree, opt_prefix) -{ +function forEachTest(handler, opt_tree, opt_prefix) { var tree = opt_tree || globalState().results.tests; var prefix = opt_prefix || ''; @@ -643,32 +658,31 @@ var testObject = tree[key]; testObject.name = newPrefix; handler(testObject); - } else + } else { forEachTest(handler, tree[key], newPrefix); + } } } -function hasUnexpected(tests) -{ +function hasUnexpected(tests) { return tests.some(function (test) { return test.is_unexpected; }); } -function updateTestlistCounts() -{ +function updateTestListCounts() { forEach(document.querySelectorAll('.test-list-count'), function(count) { var container = parentOfType(count, 'div'); var testContainers; - if (onlyShowUnexpectedFailures()) + if (onlyShowUnexpectedFailures()) { testContainers = container.querySelectorAll('tbody:not(.expected)'); - else + } else { testContainers = container.querySelectorAll('tbody'); + } count.textContent = testContainers.length; - }) + }); } -function flagAll(headerLink) -{ +function flagAll(headerLink) { var tests = visibleTests(parentOfType(headerLink, 'div')); forEach(tests, function(test) { TestNavigator.flagTest(test, true); @@ -676,8 +690,7 @@ TestNavigator.updateFlaggedTestTextBox(); } -function unflagAll(headerLink) -{ +function unflagAll(headerLink) { var tests = visibleTests(parentOfType(headerLink, 'div')); forEach(tests, function(test) { TestNavigator.flagTest(test, false); @@ -685,47 +698,57 @@ TestNavigator.updateFlaggedTestTextBox(); } -function testListHeaderHtml(header) -{ - return '<h1>' + header + ' (<span class=test-list-count></span>): [<a href="#" class=flag-all onclick="flagAll(this)">flag all</a>] [<a href="#" class=flag-all onclick="unflagAll(this)">unflag all</a>]</h1>'; +function testListHeaderHtml(header) { + return '<h1>' + header + + ' (<span class=test-list-count></span>): [<a href="#" class=flag-all ' + + 'onclick="flagAll(this)">flag all</a>] [<a href="#" class=flag-all ' + + 'onclick="unflagAll(this)">unflag all</a>]</h1>'; } -function testList(tests, header, tableId) -{ +function testList(tests, header, tableId) { tests.sort(); - var html = '<div' + ((!hasUnexpected(tests) && tableId != 'stderr-table') ? ' class=expected' : '') + ' id=' + tableId + '>' + - testListHeaderHtml(header) + '<table>'; + var html = '<div' + + ((!hasUnexpected(tests) && tableId != 'stderr-table') ? ' class=expected' : '') + + ' id=' + tableId + '>' + testListHeaderHtml(header) + '<table>'; // FIXME: Include this for all testLists. - if (tableId == 'passes-table') + if (tableId == 'passes-table') { html += '<thead><th>test</th><th>expected</th></thead>'; + } for (var i = 0; i < tests.length; i++) { var testObject = tests[i]; var test = testObject.name; - html += '<tbody class="' + ((testObject.is_unexpected || tableId == 'stderr-table') ? '' : 'expected') + '" data-testname="' + test + '"><tr><td>' + + html += '<tbody class="' + + ((testObject.is_unexpected || tableId == 'stderr-table') ? '' : 'expected') + + '" data-testname="' + test + '"><tr><td>' + ((tableId == 'passes-table') ? testLink(test) : testLinkWithExpandButton(test)) + - '</td><td>'; + '</td><td>'; - if (tableId == 'stderr-table') + if (tableId == 'stderr-table') { html += resultLink(stripExtension(test), '-stderr.txt', 'stderr'); - else if (tableId == 'passes-table') + } + else if (tableId == 'passes-table') { html += testObject.expected; + } else if (tableId == 'crash-tests-table') { html += resultLink(stripExtension(test), '-crash-log.txt', 'crash log'); html += resultLink(stripExtension(test), '-sample.txt', 'sample'); - if (testObject.has_stderr) + if (testObject.has_stderr) { html += resultLink(stripExtension(test), '-stderr.txt', 'stderr'); - } else if (tableId == 'leak-tests-table') + } + } else if (tableId == 'leak-tests-table') { html += resultLink(stripExtension(test), '-leak-log.txt', 'leak log'); + } else if (tableId == 'timeout-tests-table') { // FIXME: only include timeout actual/diff results here if we actually spit out results for timeout tests. html += textResultLinks(test, stripExtension(test)); } - if (testObject.has_repaint_overlay) + if (testObject.has_repaint_overlay) { html += resultLink(stripExtension(test), '-overlay.html?' + encodeURIComponent(testLinkTarget(test)), 'overlay'); + } html += '</td></tr></tbody>'; } @@ -733,13 +756,11 @@ return html; } -function toArray(nodeList) -{ +function toArray(nodeList) { return Array.prototype.slice.call(nodeList); } -function trim(string) -{ +function trim(string) { return string.replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); } @@ -750,21 +771,20 @@ TableSorter._backwardArrow = '<svg style="width:10px;height:10px"><polygon points="0,10 10,10 5,0" style="fill:#ccc"></svg>'; -TableSorter._sortedContents = function(header, arrow) -{ +TableSorter._sortedContents = function(header, arrow) { return arrow + ' ' + trim(header.textContent) + ' ' + arrow; -} +}; -TableSorter._updateHeaderClassNames = function(newHeader) -{ +TableSorter._updateHeaderClassNames = function(newHeader) { var sortHeader = document.querySelector('.sortHeader'); if (sortHeader) { if (sortHeader == newHeader) { var isAlreadyReversed = sortHeader.classList.contains('reversed'); - if (isAlreadyReversed) + if (isAlreadyReversed) { sortHeader.classList.remove('reversed'); - else + } else { sortHeader.classList.add('reversed'); + } } else { sortHeader.textContent = sortHeader.textContent; sortHeader.classList.remove('sortHeader'); @@ -773,15 +793,13 @@ } newHeader.classList.add('sortHeader'); -} +}; -TableSorter._textContent = function(tbodyRow, column) -{ +TableSorter._textContent = function(tbodyRow, column) { return tbodyRow.querySelectorAll('td')[column].textContent; -} +}; -TableSorter._sortRows = function(newHeader, reversed) -{ +TableSorter._sortRows = function(newHeader, reversed) { var testsTable = document.getElementById('results-table'); var headers = toArray(testsTable.querySelectorAll('th')); var sortColumn = headers.indexOf(newHeader); @@ -797,37 +815,38 @@ if (sortColumn && aText == bText) { var aTestName = TableSorter._textContent(a, 0); var bTestName = TableSorter._textContent(b, 0); - if (aTestName == bTestName) + if (aTestName == bTestName) { return 0; + } return aTestName < bTestName ? -1 : 1; } - if (reversed) + if (reversed) { return aText < bText ? 1 : -1; - else + } else { return aText < bText ? -1 : 1; + } }); - for (var i = 0; i < rows.length; i++) + for (var i = 0; i < rows.length; i++) { testsTable.appendChild(rows[i]); -} + } +}; -TableSorter.sortColumn = function(columnNumber) -{ +TableSorter.sortColumn = function(columnNumber) { var newHeader = document.getElementById('results-table').querySelectorAll('th')[columnNumber]; TableSorter._sort(newHeader); -} +}; -TableSorter.handleClick = function(e) -{ +TableSorter.handleClick = function(e) { var newHeader = e.target; - if (newHeader.localName != 'th') + if (newHeader.localName != 'th') { return; + } TableSorter._sort(newHeader); -} +}; -TableSorter._sort = function(newHeader) -{ +TableSorter._sort = function(newHeader) { TableSorter._updateHeaderClassNames(newHeader); var reversed = newHeader.classList.contains('reversed'); @@ -835,7 +854,7 @@ newHeader.innerHTML = TableSorter._sortedContents(newHeader, sortArrow); TableSorter._sortRows(newHeader, reversed); -} +}; var PixelZoomer = {}; @@ -848,8 +867,7 @@ var kZoomedResultWidth = kResultWidth * PixelZoomer._zoomFactor; var kZoomedResultHeight = kResultHeight * PixelZoomer._zoomFactor; -PixelZoomer._zoomImageContainer = function(url) -{ +PixelZoomer._zoomImageContainer = function(url) { var container = document.createElement('div'); container.className = 'zoom-image-container'; @@ -874,10 +892,9 @@ container.appendChild(imageContainer); return container; -} +}; -PixelZoomer._createContainer = function(e) -{ +PixelZoomer._createContainer = function(e) { var tbody = parentOfType(e.target, 'tbody'); var row = tbody.querySelector('tr'); var imageDiffLinks = row.querySelectorAll('a[href$=".png"]'); @@ -885,8 +902,6 @@ var container = document.createElement('div'); container.className = 'pixel-zoom-container'; - var html = ''; - var togglingImageLink = row.querySelector('a[href$="-diffs.html"]'); if (togglingImageLink) { var prefix = togglingImageLink.getAttribute('data-prefix'); @@ -894,15 +909,15 @@ container.appendChild(PixelZoomer._zoomImageContainer(prefix + '-actual.png')); } - for (var i = 0; i < imageDiffLinks.length; i++) + for (var i = 0; i < imageDiffLinks.length; i++) { container.appendChild(PixelZoomer._zoomImageContainer(imageDiffLinks[i].href)); + } document.body.appendChild(container); PixelZoomer._drawAll(); -} +}; -PixelZoomer._draw = function(imageContainer) -{ +PixelZoomer._draw = function(imageContainer) { var image = imageContainer.querySelector('img'); var canvas = imageContainer.querySelector('canvas'); @@ -924,38 +939,41 @@ ctx.strokeRect(-1.5, -1.5, kZoomedResultWidth + 2, kZoomedResultHeight + 2); ctx.scale(PixelZoomer._zoomFactor, PixelZoomer._zoomFactor); ctx.drawImage(image, 0, 0); -} +}; -PixelZoomer._drawAll = function() -{ +PixelZoomer._drawAll = function() { forEach(document.querySelectorAll('.pixel-zoom-container .scaled-image-container'), PixelZoomer._draw); -} +}; -PixelZoomer.handleMouseOut = function(e) -{ - if (e.relatedTarget && e.relatedTarget.tagName != 'IFRAME') +PixelZoomer.handleMouseOut = function(e) { + if (e.relatedTarget && e.relatedTarget.tagName != 'IFRAME') { return; + } // If e.relatedTarget is null, we've moused out of the document. var container = document.querySelector('.pixel-zoom-container'); - if (container) + if (container) { remove(container); -} + } +}; PixelZoomer.handleMouseMove = function(e) { - if (PixelZoomer._mouseMoveTimeout) + if (PixelZoomer._mouseMoveTimeout) { clearTimeout(PixelZoomer._mouseMoveTimeout); + } - if (parentOfType(e.target, '.pixel-zoom-container')) + if (parentOfType(e.target, '.pixel-zoom-container')) { return; + } var container = document.querySelector('.pixel-zoom-container'); var resultContainer = (e.target.className == 'result-container') ? e.target : parentOfType(e.target, '.result-container'); if (!resultContainer || !resultContainer.querySelector('img')) { - if (container) + if (container) { remove(container); + } return; } @@ -976,7 +994,7 @@ } PixelZoomer._drawAll(); -} +}; document.addEventListener('mousemove', PixelZoomer.handleMouseMove, false); document.addEventListener('mouseout', PixelZoomer.handleMouseOut, false); @@ -987,125 +1005,126 @@ TestNavigator.currentTest = null; TestNavigator.flaggedTests = {}; TestNavigator._createFlaggedTestContainer(); -} +}; -TestNavigator.handleKeyEvent = function(event) -{ - if (event.metaKey || event.shiftKey || event.ctrlKey) +TestNavigator.handleKeyEvent = function(event) { + if (event.metaKey || event.shiftKey || event.ctrlKey) { return; + } switch (String.fromCharCode(event.charCode)) { - case 'i': - TestNavigator._scrollToFirstTest(); - break; - case 'j': - TestNavigator._scrollToNextTest(); - break; - case 'k': - TestNavigator._scrollToPreviousTest(); - break; - case 'l': - TestNavigator._scrollToLastTest(); - break; - case 'e': - TestNavigator._expandCurrentTest(); - break; - case 'c': - TestNavigator._collapseCurrentTest(); - break; - case 't': - TestNavigator._toggleCurrentTest(); - break; - case 'f': - TestNavigator._toggleCurrentTestFlagged(); - break; + case 'i': + TestNavigator._scrollToFirstTest(); + break; + case 'j': + TestNavigator._scrollToNextTest(); + break; + case 'k': + TestNavigator._scrollToPreviousTest(); + break; + case 'l': + TestNavigator._scrollToLastTest(); + break; + case 'e': + TestNavigator._expandCurrentTest(); + break; + case 'c': + TestNavigator._collapseCurrentTest(); + break; + case 't': + TestNavigator._toggleCurrentTest(); + break; + case 'f': + TestNavigator._toggleCurrentTestFlagged(); + break; } -} +}; -TestNavigator._scrollToFirstTest = function() -{ +TestNavigator._scrollToFirstTest = function() { var links = visibleTests(); - if (links.length == 0) + if (links.length == 0) { return; - if (TestNavigator._setCurrentTest(links[0])) + } + if (TestNavigator._setCurrentTest(links[0])) { TestNavigator._scrollToCurrentTest(); -} + } +}; -TestNavigator._scrollToLastTest = function() -{ +TestNavigator._scrollToLastTest = function() { var links = visibleTests(); - if (links.length == 0) + if (links.length == 0) { return; - if (TestNavigator._setCurrentTest(links[links.length - 1])) + } + if (TestNavigator._setCurrentTest(links[links.length - 1])) { TestNavigator._scrollToCurrentTest(); -} + } +}; -TestNavigator._scrollToNextTest = function() -{ +TestNavigator._scrollToNextTest = function() { if (!TestNavigator.currentTest) { TestNavigator._scrollToFirstTest(); return; } var onlyUnexpected = onlyShowUnexpectedFailures(); for (var tbody = TestNavigator.currentTest.nextElementSibling; tbody; tbody = tbody.nextElementSibling) { - if (tbody.tagName.toLowerCase() != 'tbody') + if (tbody.tagName.toLowerCase() != 'tbody') { continue; - if (onlyUnexpected && tbody.classList.contains('expected')) + } + if (onlyUnexpected && tbody.classList.contains('expected')) { continue; - if (TestNavigator._setCurrentTest(tbody)) + } + if (TestNavigator._setCurrentTest(tbody)) { TestNavigator._scrollToCurrentTest(); + } break; } -} +}; -TestNavigator._scrollToPreviousTest = function() -{ +TestNavigator._scrollToPreviousTest = function() { if (!TestNavigator.currentTest) { TestNavigator._scrollToLastTest(); return; } var onlyUnexpected = onlyShowUnexpectedFailures(); for (var tbody = TestNavigator.currentTest.previousElementSibling; tbody; tbody = tbody.previousElementSibling) { - if (tbody.tagName.toLowerCase() != 'tbody') + if (tbody.tagName.toLowerCase() != 'tbody') { continue; - if (onlyUnexpected && tbody.classList.contains('expected')) + } + if (onlyUnexpected && tbody.classList.contains('expected')) { continue; - if (TestNavigator._setCurrentTest(tbody)) + } + if (TestNavigator._setCurrentTest(tbody)) { TestNavigator._scrollToCurrentTest(); + } break; } -} +}; -TestNavigator._currentTestExpandLink = function() -{ +TestNavigator._currentTestExpandLink = function() { return TestNavigator.currentTest.querySelector('.expand-button-text'); -} +}; -TestNavigator._expandCurrentTest = function() -{ +TestNavigator._expandCurrentTest = function() { expandExpectations(TestNavigator._currentTestExpandLink()); -} +}; -TestNavigator._collapseCurrentTest = function() -{ +TestNavigator._collapseCurrentTest = function() { collapseExpectations(TestNavigator._currentTestExpandLink()); -} +}; -TestNavigator._toggleCurrentTest = function() -{ +TestNavigator._toggleCurrentTest = function() { toggleExpectations(TestNavigator._currentTestExpandLink()); -} +}; -TestNavigator._toggleCurrentTestFlagged = function() -{ +TestNavigator._toggleCurrentTestFlagged = function() { var testLink = TestNavigator.currentTest; TestNavigator.flagTest(testLink, !testLink.classList.contains('flagged')); TestNavigator.updateFlaggedTestTextBox(); -} +}; -// FIXME: Test navigator shouldn't know anything about flagging. It should probably call out to TestFlagger or something. -TestNavigator.flagTest = function(testTbody, shouldFlag) -{ +// FIXME: Test navigator shouldn't know anything about flagging. +// Flagging-related functionality could be extracted to a separate object. +TestNavigator.flagTest = function(testTbody, shouldFlag) { var testName = testTbody.getAttribute('data-testname'); if (shouldFlag) { @@ -1115,10 +1134,9 @@ testTbody.classList.remove('flagged'); delete TestNavigator.flaggedTests[testName]; } -} +}; -TestNavigator._createFlaggedTestContainer = function() -{ +TestNavigator._createFlaggedTestContainer = function() { var flaggedTestContainer = document.createElement('div'); flaggedTestContainer.id = 'flagged-test-container'; flaggedTestContainer.innerHTML = '<h2>Flagged Tests</h2>' + @@ -1127,93 +1145,91 @@ '</label>' + '<pre id="flagged-tests" contentEditable></pre>'; document.body.appendChild(flaggedTestContainer); -} +}; -TestNavigator.updateFlaggedTestTextBox = function() -{ +TestNavigator.updateFlaggedTestTextBox = function() { var flaggedTestTextbox = document.getElementById('flagged-tests'); var flaggedTests = Object.keys(this.flaggedTests); flaggedTests.sort(); var separator = document.getElementById('use-newlines').checked ? '\n' : ' '; flaggedTestTextbox.innerHTML = flaggedTests.join(separator); document.getElementById('flagged-test-container').style.display = flaggedTests.length ? '' : 'none'; -} +}; -TestNavigator._setCurrentTest = function(tbody) -{ - if (TestNavigator.currentTest) +TestNavigator._setCurrentTest = function(tbody) { + if (TestNavigator.currentTest) { TestNavigator.currentTest.classList.remove('current'); + } TestNavigator.currentTest = tbody; tbody.classList.add('current'); return true; -} +}; -TestNavigator._scrollToCurrentTest = function() -{ +TestNavigator._scrollToCurrentTest = function() { var targetLink = TestNavigator.currentTest; - if (!targetLink) + if (!targetLink) { return; + } var rowRect = targetLink.getBoundingClientRect(); var container = document.querySelector('.content-container'); - // rowRect is in client coords (i.e. relative to viewport), so we just want to add its top to the current scroll position. + // rowRect is in client coordinates (i.e. relative to viewport), so we just + // want to add its top to the current scroll position. container.scrollTop += rowRect.top - 20; -} +}; -TestNavigator.onlyShowUnexpectedFailuresChanged = function() -{ +TestNavigator.onlyShowUnexpectedFailuresChanged = function() { var currentTest = document.querySelector('.current'); - if (!currentTest) + if (!currentTest) { return; + } // If our currentTest became hidden, reset the currentTestIndex. - if (onlyShowUnexpectedFailures() && currentTest.classList.contains('expected')) + if (onlyShowUnexpectedFailures() && currentTest.classList.contains('expected')) { TestNavigator._scrollToFirstTest(); -} + } +}; document.addEventListener('keypress', TestNavigator.handleKeyEvent, false); -function onlyShowUnexpectedFailures() -{ +function onlyShowUnexpectedFailures() { return !document.getElementById('show-expected-failures').checked; } -function handleStderrChange() -{ +function handleStderrChange() { OptionWriter.save(); - document.getElementById('stderr-style').textContent = document.getElementById('show-stderr').checked ? + document.getElementById('stderr-style').textContent = + document.getElementById('show-stderr').checked ? '' : '#stderr-table { display: none; }'; } -function handleUnexpectedPassesChange() -{ +function handleUnexpectedPassesChange() { OptionWriter.save(); - document.getElementById('unexpected-pass-style').textContent = document.getElementById('show-unexpected-passes').checked ? + document.getElementById('unexpected-pass-style').textContent = + document.getElementById('show-unexpected-passes').checked ? '' : '#passes-table { display: none; }'; } -function handleFlakyFailuresChange() -{ +function handleFlakyFailuresChange() { OptionWriter.save(); - document.getElementById('flaky-failures-style').textContent = document.getElementById('show-flaky-failures').checked ? + document.getElementById('flaky-failures-style').textContent = + document.getElementById('show-flaky-failures').checked ? '' : '.flaky { display: none; }'; } -function handleUnexpectedResultsChange() -{ +function handleUnexpectedResultsChange() { OptionWriter.save(); updateExpectedFailures(); } -function updateExpectedFailures() -{ +function updateExpectedFailures() { document.getElementById('unexpected-style').textContent = onlyShowUnexpectedFailures() ? '.expected { display: none; }' : ''; - updateTestlistCounts(); + updateTestListCounts(); TestNavigator.onlyShowUnexpectedFailuresChanged(); } @@ -1221,8 +1237,7 @@ OptionWriter._key = 'run-webkit-tests-options'; -OptionWriter.save = function() -{ +OptionWriter.save = function() { var options = document.querySelectorAll('label input'); var data = {}; for (var i = 0, len = options.length; i < len; i++) { @@ -1230,10 +1245,9 @@ data[option.id] = option.checked; } localStorage.setItem(OptionWriter._key, JSON.stringify(data)); -} +}; -OptionWriter.apply = function() -{ +OptionWriter.apply = function() { var json = localStorage.getItem(OptionWriter._key); if (!json) { updateAllOptions(); @@ -1243,39 +1257,40 @@ var data = JSON.parse(json); for (var id in data) { var input = document.getElementById(id); - if (input) + if (input) { input.checked = data[id]; + } } updateAllOptions(); +}; + +function updateAllOptions() { + forEach(document.querySelectorAll('input'), function(input) { + input.onchange(); + }); } -function updateAllOptions() -{ - forEach(document.querySelectorAll('input'), function(input) { input.onchange(); }); -} - -function handleToggleUseNewlines() -{ +function handleToggleUseNewlines() { OptionWriter.save(); TestNavigator.updateFlaggedTestTextBox(); } -function handleToggleImagesChange() -{ +function handleToggleImagesChange() { OptionWriter.save(); updateTogglingImages(); } -function updateTogglingImages() -{ +function updateTogglingImages() { var shouldToggle = document.getElementById('toggle-images').checked; globalState().shouldToggleImages = shouldToggle; if (shouldToggle) { - forEach(document.querySelectorAll('table:not(#missing-table) tbody:not([mismatchreftest]) a[href$=".png"]'), convertToTogglingHandler(function(prefix) { - return resultLink(prefix, '-diffs.html', 'images'); - })); - forEach(document.querySelectorAll('table:not(#missing-table) tbody:not([mismatchreftest]) img[src$=".png"]'), convertToTogglingHandler(togglingImage)); + forEach(document.querySelectorAll('table:not(#missing-table) tbody:not([mismatchreftest]) a[href$=".png"]'), + convertToTogglingHandler(function(prefix) { + return resultLink(prefix, '-diffs.html', 'images'); + })); + forEach(document.querySelectorAll('table:not(#missing-table) tbody:not([mismatchreftest]) img[src$=".png"]'), + convertToTogglingHandler(togglingImage)); } else { forEach(document.querySelectorAll('a[href$="-diffs.html"]'), convertToNonTogglingHandler(resultLink)); forEach(document.querySelectorAll('.animatedImage'), convertToNonTogglingHandler(function (absolutePrefix, suffix) { @@ -1286,54 +1301,56 @@ updateImageTogglingTimer(); } -function getResultContainer(node) -{ +function getResultContainer(node) { return (node.tagName == 'IMG') ? parentOfType(node, '.result-container') : node; } -function convertToTogglingHandler(togglingImageFunction) -{ +function convertToTogglingHandler(togglingImageFunction) { return function(node) { var url = (node.tagName == 'IMG') ? node.src : node.href; - if (url.match('-expected.png$')) + if (url.match('-expected.png$')) { remove(getResultContainer(node)); - else if (url.match('-actual.png$')) { + } else if (url.match('-actual.png$')) { var name = parentOfType(node, 'tbody').querySelector('.test-link').textContent; getResultContainer(node).outerHTML = togglingImageFunction(stripExtension(name)); } - } + }; } -function convertToNonTogglingHandler(resultFunction) -{ +function convertToNonTogglingHandler(resultFunction) { return function(node) { var prefix = node.getAttribute('data-prefix'); getResultContainer(node).outerHTML = resultFunction(prefix, '-expected.png', 'expected') + resultFunction(prefix, '-actual.png', 'actual'); - } + }; } -function failingTestsTable(tests, title, id) -{ - if (!tests.length) +// Returns HTML for a table listing failing tests from the test run. +function failingTestsTable(tests, title, id) { + if (!tests.length) { return ''; + } - var numberofUnexpectedFailures = 0; + var numberOfUnexpectedFailures = 0; var tableRowHtml = ''; - for (var i = 0; i < tests.length; i++){ + for (var i = 0; i < tests.length; i++) { tableRowHtml += tableRow(tests[i]); - if (tests[i].is_unexpected) - numberofUnexpectedFailures++; + if (tests[i].is_unexpected) { + numberOfUnexpectedFailures++; + } } var className = ''; - if (id) + if (id) { className += id.split('-')[0]; - if (!hasUnexpected(tests)) + } + if (!hasUnexpected(tests)) { className += ' expected'; + } var header = '<div'; - if (className) + if (className) { header += ' class="' + className + '"'; + } header += '>' + testListHeaderHtml(title) + '<table id="' + id + '"><thead><tr>' + @@ -1343,17 +1360,20 @@ '<th>actual</th>' + '<th>expected</th>'; - if (id == 'flaky-tests-table') + if (id == 'flaky-tests-table') { header += '<th>failures</th>'; + } header += '</tr></thead>'; - return header + tableRowHtml + '</table></div>'; } -function generatePage() -{ +// Initializes the results page. +// This includes adding HTML for the toolbar and the tables with test results, +// and setting the state of TestNavigator and OptionWriter. +// This function requires that globalState().results is already populated. +function generatePage() { forEachTest(processGlobalStateFor); var html = '<div class=content-container><div id=toolbar>' + @@ -1370,14 +1390,17 @@ '<label><input id="show-stderr" type=checkbox onchange="handleStderrChange()">stderr</label>' + '</div></div>'; - if (globalState().results.interrupted) - html += "<p class='stopped-running-early-message'>Testing exited early.</p>" + if (globalState().results.interrupted) { + html += "<p class='stopped-running-early-message'>Testing exited early.</p>"; + } - if (globalState().crashTests.length) + if (globalState().crashTests.length) { html += testList(globalState().crashTests, 'Tests that crashed', 'crash-tests-table'); + } - if (globalState().leakTests.length) + if (globalState().leakTests.length) { html += testList(globalState().leakTests, 'Tests that leaked', 'leak-tests-table'); + } html += failingTestsTable(globalState().failingTests, 'Tests that failed text/pixel/audio diff', 'results-table'); @@ -1385,17 +1408,20 @@ html += failingTestsTable(globalState().missingResults, 'Tests that had no expected results (probably new)', 'missing-table'); - if (globalState().timeoutTests.length) + if (globalState().timeoutTests.length) { html += testList(globalState().timeoutTests, 'Tests that timed out', 'timeout-tests-table'); + } - if (globalState().testsWithStderr.length) + if (globalState().testsWithStderr.length) { html += testList(globalState().testsWithStderr, 'Tests that had stderr output', 'stderr-table'); + } html += failingTestsTable(globalState().flakyPassTests, 'Flaky tests (failed the first run and passed on retry)', 'flaky-tests-table'); - if (globalState().unexpectedPassTests.length) + if (globalState().unexpectedPassTests.length) { html += testList(globalState().unexpectedPassTests, 'Tests expected to fail but passed', 'passes-table'); + } if (globalState().hasHttpTests) { html += '<p>httpd access log: <a href="access_log.txt">access_log.txt</a></p>' + @@ -1409,15 +1435,16 @@ if (document.getElementById('results-table')) { document.getElementById('results-table').addEventListener('click', TableSorter.handleClick, false); TableSorter.sortColumn(0); - if (!globalState().hasTextFailures) + if (!globalState().hasTextFailures) { document.getElementById('text-results-header').textContent = ''; + } if (!globalState().hasImageFailures) { document.getElementById('image-results-header').textContent = ''; parentOfType(document.getElementById('toggle-images'), 'label').style.display = 'none'; } } - updateTestlistCounts(); + updateTestListCounts(); TestNavigator.reset(); OptionWriter.apply(); @@ -1426,4 +1453,6 @@ <!-- HACK: when json_results_test.js is included, loading this page runs the tests. It is not copied to the layout-test-results output directory. --> <script src="resources/results-test.js"></script> +</head> <body onload="generatePage()"></body> +</html>
diff --git a/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text-expected.txt b/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text-expected.txt new file mode 100644 index 0000000..00fbf64 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text-expected.txt
@@ -0,0 +1,225 @@ +CONSOLE MESSAGE: line 3: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +CONSOLE MESSAGE: line 5: www.bar.com +CONSOLE MESSAGE: line 6: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +CONSOLE MESSAGE: line 7: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +CONSOLE MESSAGE: line 8: www.01234567890123456789zfoobarz01234567890123456789 +CONSOLE MESSAGE: line 9: www.01234567890123456789zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz01234567890123456789 +CONSOLE MESSAGE: line 10: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com +Tests that console copies truncated text in messages properly. + +Message count: 8 +Long url has max length: 150, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z…z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Running: testSelectWithinTruncatedUrl + +Making selection: 1, 0, 1, 75 +Selection length: 75, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 1, 0, 1, 76 +Selection length: 84, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 1, 0, 1, 150 +Selection length: 158, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 1, 75, 1, 76 +Selection length: 9, text: 123456789 + +Making selection: 1, 75, 1, 150 +Selection length: 83, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 1, 76, 1, 150 +Selection length: 74, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Running: testSelectAcrossMultipleMessages + +Making selection: 1, 0, 2, 11 +Selection length: 175, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com + +Making selection: 1, 75, 2, 11 +Selection length: 100, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com + +Making selection: 1, 76, 2, 11 +Selection length: 91, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com + +Running: testSelectAcrossMultipleMessagesWithTruncatedUrls + +Making selection: 1, 0, 3, 75 +Selection length: 256, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com +VM:6 www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 1, 0, 3, 76 +Selection length: 265, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com +VM:6 www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 1, 0, 3, 150 +Selection length: 339, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com +VM:5 www.bar.com +VM:6 www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Running: testSelectWithinMessageWithMultipleTruncatedUrls + +Making selection: 4, 0, 4, 75 +Selection length: 75, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 4, 0, 4, 76 +Selection length: 84, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 4, 0, 4, 163 +Selection length: 171, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com + +Making selection: 4, 0, 4, 238 +Selection length: 246, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 4, 0, 4, 239 +Selection length: 255, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 4, 0, 4, 313 +Selection length: 329, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 4, 75, 4, 76 +Selection length: 9, text: 123456789 + +Making selection: 4, 75, 4, 163 +Selection length: 96, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com + +Making selection: 4, 75, 4, 238 +Selection length: 171, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 4, 75, 4, 239 +Selection length: 180, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 4, 75, 4, 313 +Selection length: 254, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 4, 76, 4, 163 +Selection length: 87, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com + +Making selection: 4, 76, 4, 238 +Selection length: 162, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 4, 76, 4, 239 +Selection length: 171, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 4, 76, 4, 313 +Selection length: 245, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com www.bar.com www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 4, 163, 4, 238 +Selection length: 75, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z + +Making selection: 4, 163, 4, 239 +Selection length: 84, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789 + +Making selection: 4, 163, 4, 313 +Selection length: 158, text: www.z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 4, 238, 4, 239 +Selection length: 9, text: 123456789 + +Making selection: 4, 238, 4, 313 +Selection length: 83, text: 123456789z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Making selection: 4, 239, 4, 313 +Selection length: 74, text: z123456789z123456789z123456789z123456789z123456789z123456789z123456789.com + +Running: testSelectWithinShortUrlWithHashes + +Making selection: 5, 0, 5, 14 +Selection length: 26, text: www.01234567890123456789zf + +Making selection: 5, 0, 5, 28 +Selection length: 52, text: www.01234567890123456789zfoobarz01234567890123456789 + +Making selection: 5, 14, 5, 28 +Selection length: 26, text: oobarz01234567890123456789 + +Running: testSelectWithinUrlWithHashes + +Making selection: 6, 0, 6, 63 +Selection length: 75, text: www.01234567890123456789zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 6, 0, 6, 64 +Selection length: 120, text: www.01234567890123456789zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 6, 0, 6, 126 +Selection length: 194, text: www.01234567890123456789zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz01234567890123456789 + +Making selection: 6, 63, 6, 64 +Selection length: 45, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 6, 63, 6, 126 +Selection length: 119, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz01234567890123456789 + +Making selection: 6, 64, 6, 126 +Selection length: 74, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz01234567890123456789 + +Running: testSelectWithinHighlightedUrlBeginning +Searching for text: www. +Highlighted 18 matches + +Making selection: 7, 0, 7, 75 +Selection length: 75, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 76 +Selection length: 134, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 150 +Selection length: 208, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 75, 7, 76 +Selection length: 59, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 75, 7, 150 +Selection length: 133, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 76, 7, 150 +Selection length: 74, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Running: testSelectWithinHighlightedUrlMiddle +Searching for text: zzzzz +Highlighted 118 matches + +Making selection: 7, 0, 7, 75 +Selection length: 75, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 76 +Selection length: 134, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 150 +Selection length: 208, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 75, 7, 76 +Selection length: 59, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 75, 7, 150 +Selection length: 133, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 76, 7, 150 +Selection length: 74, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Running: testSelectWithinHighlightedUrlEnd +Searching for text: .com +Highlighted 14 matches + +Making selection: 7, 0, 7, 75 +Selection length: 75, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 76 +Selection length: 134, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 0, 7, 150 +Selection length: 208, text: www.zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 75, 7, 76 +Selection length: 59, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + +Making selection: 7, 75, 7, 150 +Selection length: 133, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com + +Making selection: 7, 76, 7, 150 +Selection length: 74, text: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.com +
diff --git a/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text.html b/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text.html new file mode 100644 index 0000000..0ab591c --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/console/console-copy-truncated-text.html
@@ -0,0 +1,196 @@ +<html> +<head> +<script src="../../http/tests/inspector/inspector-test.js"></script> +<script src="../../http/tests/inspector/console-test.js"></script> +<script> + +function test() +{ + var longUrl = "www." + "z123456789".repeat(15) + ".com"; + var shortUrl = "www.bar.com"; + var mixedUrl = longUrl + " " + shortUrl + " " + longUrl; + var shortUrlWithHashes = "www." + "0123456789".repeat(2) + "zfoobarz" + "0123456789".repeat(2); + var urlWithHashes = "www." + "0123456789".repeat(2) + "z".repeat(150) + "0123456789".repeat(2); + var highlightedUrl = "www." + "z".repeat(200) + ".com"; + var prepareCode = ` + // Keep this as the first url logged to record the max truncated length. + console.log("${longUrl}"); + + console.log("${shortUrl}"); + console.log("${longUrl}"); + console.log("${mixedUrl}"); + console.log("${shortUrlWithHashes}"); + console.log("${urlWithHashes}"); + console.log("${highlightedUrl}"); + `; + + var expectedMessageCount = 8; + var consoleView = Console.ConsoleView.instance(); + var viewport = Console.ConsoleView.instance()._viewport; + var maxLength; + var halfMaxLength; + var secondLongUrlIndexInMixedUrl; + + var tests = [ + function testSelectWithinTruncatedUrl(next) + { + makeSelectionAndDump(1, 0, 1, halfMaxLength); + makeSelectionAndDump(1, 0, 1, halfMaxLength + 1); + makeSelectionAndDump(1, 0, 1, maxLength); + makeSelectionAndDump(1, halfMaxLength, 1, halfMaxLength + 1); + makeSelectionAndDump(1, halfMaxLength, 1, maxLength); + makeSelectionAndDump(1, halfMaxLength + 1, 1, maxLength); + next(); + }, + + function testSelectAcrossMultipleMessages(next) { + makeSelectionAndDump(1, 0, 2, shortUrl.length); + makeSelectionAndDump(1, halfMaxLength, 2, shortUrl.length); + makeSelectionAndDump(1, halfMaxLength + 1, 2, shortUrl.length); + next(); + }, + + function testSelectAcrossMultipleMessagesWithTruncatedUrls(next) { + makeSelectionAndDump(1, 0, 3, halfMaxLength); + makeSelectionAndDump(1, 0, 3, halfMaxLength + 1); + makeSelectionAndDump(1, 0, 3, maxLength); + next(); + }, + + function testSelectWithinMessageWithMultipleTruncatedUrls(next) { + makeSelectionAndDump(4, 0, 4, halfMaxLength); + makeSelectionAndDump(4, 0, 4, halfMaxLength + 1); + makeSelectionAndDump(4, 0, 4, secondLongUrlIndexInMixedUrl); + makeSelectionAndDump(4, 0, 4, secondLongUrlIndexInMixedUrl + halfMaxLength); + makeSelectionAndDump(4, 0, 4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1); + makeSelectionAndDump(4, 0, 4, secondLongUrlIndexInMixedUrl + maxLength); + + makeSelectionAndDump(4, halfMaxLength, 4, halfMaxLength + 1); + makeSelectionAndDump(4, halfMaxLength, 4, secondLongUrlIndexInMixedUrl); + makeSelectionAndDump(4, halfMaxLength, 4, secondLongUrlIndexInMixedUrl + halfMaxLength); + makeSelectionAndDump(4, halfMaxLength, 4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1); + makeSelectionAndDump(4, halfMaxLength, 4, secondLongUrlIndexInMixedUrl + maxLength); + + makeSelectionAndDump(4, halfMaxLength + 1, 4, secondLongUrlIndexInMixedUrl); + makeSelectionAndDump(4, halfMaxLength + 1, 4, secondLongUrlIndexInMixedUrl + halfMaxLength); + makeSelectionAndDump(4, halfMaxLength + 1, 4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1); + makeSelectionAndDump(4, halfMaxLength + 1, 4, secondLongUrlIndexInMixedUrl + maxLength); + + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl, 4, secondLongUrlIndexInMixedUrl + halfMaxLength); + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl, 4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1); + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl, 4, secondLongUrlIndexInMixedUrl + maxLength); + + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl + halfMaxLength, 4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1); + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl + halfMaxLength, 4, secondLongUrlIndexInMixedUrl + maxLength); + + makeSelectionAndDump(4, secondLongUrlIndexInMixedUrl + halfMaxLength + 1, 4, secondLongUrlIndexInMixedUrl + maxLength); + next(); + }, + + function testSelectWithinShortUrlWithHashes(next) + { + var hashedUrlMaxLength = consoleMessageText(5).length; + var hashedUrlHalfMaxLength = Math.ceil(hashedUrlMaxLength / 2); + makeSelectionAndDump(5, 0, 5, hashedUrlHalfMaxLength); + makeSelectionAndDump(5, 0, 5, hashedUrlMaxLength); + makeSelectionAndDump(5, hashedUrlHalfMaxLength, 5, hashedUrlMaxLength); + next(); + }, + + function testSelectWithinUrlWithHashes(next) + { + var hashedUrlMaxLength = consoleMessageText(6).length; + var hashedUrlHalfMaxLength = Math.ceil(hashedUrlMaxLength / 2); + makeSelectionAndDump(6, 0, 6, hashedUrlHalfMaxLength); + makeSelectionAndDump(6, 0, 6, hashedUrlHalfMaxLength + 1); + makeSelectionAndDump(6, 0, 6, hashedUrlMaxLength); + makeSelectionAndDump(6, hashedUrlHalfMaxLength, 6, hashedUrlHalfMaxLength + 1); + makeSelectionAndDump(6, hashedUrlHalfMaxLength, 6, hashedUrlMaxLength); + makeSelectionAndDump(6, hashedUrlHalfMaxLength + 1, 6, hashedUrlMaxLength); + next(); + }, + + function testSelectWithinHighlightedUrlBeginning(next) { + testHighlightedUrlWithSearchQuery("www.", next); + }, + + function testSelectWithinHighlightedUrlMiddle(next) { + testHighlightedUrlWithSearchQuery("zzzzz", next); + }, + + function testSelectWithinHighlightedUrlEnd(next) { + testHighlightedUrlWithSearchQuery(".com", next); + } + ]; + + InspectorTest.waitForConsoleMessages(expectedMessageCount, () => { + viewport.invalidate(); + + // Get the max truncated length from the first longUrl logged. + try { + var longUrlMessageText = consoleMessageText(1); + maxLength = longUrlMessageText.length; + halfMaxLength = Math.ceil(maxLength / 2); + secondLongUrlIndexInMixedUrl = maxLength + 1 + shortUrl.length + 1; + InspectorTest.addResult("Long url has max length: " + maxLength + ", text: " + longUrlMessageText); + } catch (e) { + InspectorTest.addResult("FAIL: Could not get max truncation length from first longUrl message."); + InspectorTest.completeTest(); + return; + } + InspectorTest.runTestSuite(tests); + }); + InspectorTest.evaluateInConsole(prepareCode); + + function consoleMessageText(index) { + var messageElement = consoleView._visibleViewMessages[index].element(); + return messageElement.querySelector('.console-message-text').deepTextContent(); + } + + function makeSelectionAndDump(fromMessage, fromTextOffset, toMessage, toTextOffset) { + InspectorTest.addResult("\nMaking selection: " + fromMessage + ", " + fromTextOffset + ", " + toMessage + ", " + toTextOffset); + + // Ignore the anchor text on the start/end message, just use their contents. + var fromAnchor = consoleView.itemElement(fromMessage).element().querySelector('.console-message-anchor'); + var toAnchor = consoleView.itemElement(toMessage).element().querySelector('.console-message-anchor'); + fromTextOffset += fromAnchor ? fromAnchor.deepTextContent().length : 0; + toTextOffset += toAnchor ? toAnchor.deepTextContent().length : 0; + InspectorTest.selectConsoleMessages(fromMessage, fromTextOffset, toMessage, toTextOffset); + var selectedText = viewport._selectedText(); + if (selectedText) { + selectedText = selectedText.replace(/\bVM\d+/g, "VM"); + InspectorTest.addResult("Selection length: " + selectedText.length + ", text: " + selectedText); + } else { + InspectorTest.addResult("No selection"); + } + } + + function testHighlightedUrlWithSearchQuery(query, next) { + // Clear any existing ranges to avoid using them as the query. + window.getSelection().removeAllRanges(); + InspectorTest.addSniffer(consoleView, "_searchFinishedForTests", onSearch); + consoleView._searchableView._searchInputElement.value = query; + consoleView._searchableView.showSearchField(); + InspectorTest.addResult("Searching for text: " + query); + + function onSearch() { + var matches = consoleView.element.childTextNodes().filter(node => node.parentElement.classList.contains("highlighted-search-result")).map(node => node.parentElement); + InspectorTest.addResult("Highlighted " + matches.length + " matches"); + + // Use TextNodes for containers to get inside the highlighted match element. + makeSelectionAndDump(7, 0, 7, halfMaxLength); + makeSelectionAndDump(7, 0, 7, halfMaxLength + 1); + makeSelectionAndDump(7, 0, 7, maxLength); + makeSelectionAndDump(7, halfMaxLength, 7, halfMaxLength + 1); + makeSelectionAndDump(7, halfMaxLength, 7, maxLength); + makeSelectionAndDump(7, halfMaxLength + 1, 7, maxLength); + next(); + } + } +} +</script> +</head> +<body onload="runTest()"> +<p>Tests that console copies truncated text in messages properly.</p> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt new file mode 100644 index 0000000..2e0cb0b --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt
@@ -0,0 +1,247 @@ +CONSOLE WARNING: line 327: The provided value 'fancy' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 333: The provided value 'undefined' is not a valid enum value of type ChannelInterpretation. +CONSOLE WARNING: line 481: The provided value '9x' is not a valid enum value of type OverSampleType. +CONSOLE WARNING: line 696: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 725: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +This is a testharness.js-based test. +PASS # AUDIT TASK RUNNER STARTED. +PASS > [initialize] Initialize contexts for testing +PASS context = new AudioContext() did not throw an exception. +PASS otherContext = new AudioContext() did not throw an exception. +PASS < [initialize] All assertions passed. (total 2 assertions) +PASS > [createBuffer] +PASS context.createBuffer(99, 1, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of channels provided (99) is outside the range [1, 32].". +PASS context.createBuffer(0, 1, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of channels provided (0) is outside the range [1, 32].". +PASS context.createBuffer(1, 1, 1) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (1) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 2999) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (2999) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 384001) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (384001) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 1e6) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (1.00000e+6) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 3000) did not throw an exception. +PASS context.createBuffer(1, 1, 192000) did not throw an exception. +PASS context.createBuffer(1, 1, 384000) did not throw an exception. +PASS context.createBuffer(1, 0, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of frames provided (0) is less than or equal to the minimum bound (0).". +PASS context.createBuffer(new ArrayBuffer(100), true) threw TypeError: "Failed to execute 'createBuffer' on 'BaseAudioContext': 3 arguments required, but only 2 present.". +PASS < [createBuffer] All assertions passed. (total 11 assertions) +PASS > [createMediaElementSource] +PASS context.createMediaElementSource(null) threw TypeError: "Failed to execute 'createMediaElementSource' on 'BaseAudioContext': parameter 1 is not of type 'HTMLMediaElement'.". +PASS < [createMediaElementSource] All assertions passed. (total 1 assertions) +PASS > [createMediaStreamSource] +PASS context.createMediaStreamSource(null) threw TypeError: "Failed to execute 'createMediaStreamSource' on 'BaseAudioContext': parameter 1 is not of type 'MediaStream'.". +PASS < [createMediaStreamSource] All assertions passed. (total 1 assertions) +PASS > [createScriptProcessor] +PASS context.createScriptProcessor(1, 1, 1) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': buffer size (1) must be 0 or a power of two between 256 and 16384.". +PASS context.createScriptProcessor(4096, 100, 1) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': number of input channels (100) exceeds maximum (32).". +PASS context.createScriptProcessor(4096, 1, 100) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': number of output channels (100) exceeds maximum (32).". +PASS context.createScriptProcessor() did not throw an exception. +PASS context.createScriptProcessor(0) did not throw an exception. +PASS < [createScriptProcessor] All assertions passed. (total 5 assertions) +PASS > [createChannelSplitter] +PASS context.createChannelSplitter(0) threw IndexSizeError: "Failed to execute 'createChannelSplitter' on 'BaseAudioContext': The number of outputs provided (0) is outside the range [1, 32].". +PASS context.createChannelSplitter(99) threw IndexSizeError: "Failed to execute 'createChannelSplitter' on 'BaseAudioContext': The number of outputs provided (99) is outside the range [1, 32].". +PASS context.createChannelMerger(0) threw IndexSizeError: "Failed to execute 'createChannelMerger' on 'BaseAudioContext': The number of inputs provided (0) is outside the range [1, 32].". +PASS < [createChannelSplitter] All assertions passed. (total 3 assertions) +PASS > [createChannelMerger] +PASS context.createChannelMerger(99) threw IndexSizeError: "Failed to execute 'createChannelMerger' on 'BaseAudioContext': The number of inputs provided (99) is outside the range [1, 32].". +PASS < [createChannelMerger] All assertions passed. (total 1 assertions) +PASS > [createPeriodicWave] +PASS context.createPeriodicWave(null, null) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': The provided value cannot be converted to a sequence.". +PASS context.createPeriodicWave(new Float32Array(10), null) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': The provided value cannot be converted to a sequence.". +PASS context.createPeriodicWave(new Float32Array(4100), new Float32Array(4100)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(8192), new Float32Array(8192)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(10000), new Float32Array(10000)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(10), new Float32Array(7)) threw IndexSizeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': length of real array (10) and length of imaginary array (7) must match.". +PASS < [createPeriodicWave] All assertions passed. (total 6 assertions) +PASS > [createAnalyser] +PASS AnalyserNode.fftSize = 42 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The value provided (42) is not a power of two.". +PASS AnalyserNode.fftSize is not equal to 42. +PASS AnalyserNode.fftSize = 16 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The FFT size provided (16) is outside the range [32, 32768].". +PASS AnalyserNode.fftSize is not equal to 16. +PASS AnalyserNode.fftSize = 32768 did not throw an exception. +PASS AnalyserNode.fftSize = 65536 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The FFT size provided (65536) is outside the range [32, 32768].". +PASS AnalyserNode.fftSize is not equal to 65536. +PASS AnalyserNode.minDecibels = -10 threw IndexSizeError: "Failed to set the 'minDecibels' property on 'AnalyserNode': The minDecibels provided (-10) is greater than the maximum bound (-30).". +PASS AnalyserNode.minDecibels is not equal to -10. +PASS AnalyserNode.maxDecibels = -150 threw IndexSizeError: "Failed to set the 'maxDecibels' property on 'AnalyserNode': The maxDecibels provided (-150) is less than the minimum bound (-100).". +PASS AnalyserNode.maxDecibels is not equal to -150. +PASS AnalyserNode.minDecibels = -30 threw IndexSizeError: "Failed to set the 'minDecibels' property on 'AnalyserNode': The minDecibels provided (-30) is greater than or equal to the maximum bound (-30).". +PASS AnalyserNode.minDecibels is not equal to -30. +PASS AnalyserNode.maxDecibels = -100 threw IndexSizeError: "Failed to set the 'maxDecibels' property on 'AnalyserNode': The maxDecibels provided (-100) is less than or equal to the minimum bound (-100).". +PASS AnalyserNode.maxDecibels is not equal to -100. +PASS AnalyserNode.smoothingTimeConstant = -0.1 threw IndexSizeError: "Failed to set the 'smoothingTimeConstant' property on 'AnalyserNode': The smoothing value provided (-0.1) is outside the range [0, 1].". +PASS AnalyserNode.smoothingTimeConstant is not equal to -0.1. +PASS AnalyserNode.smoothingTimeConstant = 1.5 threw IndexSizeError: "Failed to set the 'smoothingTimeConstant' property on 'AnalyserNode': The smoothing value provided (1.5) is outside the range [0, 1].". +PASS AnalyserNode.smoothingTimeConstant is not equal to 1.5. +PASS AnalyserNode.getFloatFrequencyData(null) threw TypeError: "Failed to execute 'getFloatFrequencyData' on 'AnalyserNode': parameter 1 is not of type 'Float32Array'.". +PASS AnalyserNode.getByteFrequencyData(null) threw TypeError: "Failed to execute 'getByteFrequencyData' on 'AnalyserNode': parameter 1 is not of type 'Uint8Array'.". +PASS AnalyserNode.getFloatTimeDomainData(null) threw TypeError: "Failed to execute 'getFloatTimeDomainData' on 'AnalyserNode': parameter 1 is not of type 'Float32Array'.". +PASS AnalyserNode.getByteTimeDomainData(null) threw TypeError: "Failed to execute 'getByteTimeDomainData' on 'AnalyserNode': parameter 1 is not of type 'Uint8Array'.". +PASS AnalyserNode.getFloatFrequencyData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getFloatFrequencyData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getByteFrequencyData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getByteFrequencyData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getFloatTimeDomainData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getFloatTimeDomainData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getByteTimeDomainData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getByteTimeDomainData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AudioBuffer.getChannelData(2) threw IndexSizeError: "Failed to execute 'getChannelData' on 'AudioBuffer': channel index (2) exceeds number of channels (1)". +PASS < [createAnalyser] All assertions passed. (total 28 assertions) +PASS > [Init test nodes] Create test nodes for the following tests +PASS node = context.createGain() did not throw an exception. +PASS node2 = context.createGain() did not throw an exception. +PASS < [Init test nodes] All assertions passed. (total 2 assertions) +PASS > [connections] AudioNode connections +PASS node.connect(null, 0, 0) threw TypeError: "Failed to execute 'connect' on 'AudioNode': parameter 1 is not of type 'AudioNode'.". +PASS node.connect(context.destination, 100, 0) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': output index (100) exceeds number of outputs (1).". +PASS node.connect(context.destination, 0, 100) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': input index (100) exceeds number of inputs (1).". +PASS node.connect(node2.gain, 100) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': output index (100) exceeds number of outputs (1).". +PASS node.disconnect(99) threw IndexSizeError: "Failed to execute 'disconnect' on 'AudioNode': The output index provided (99) is outside the range [0, 0].". +PASS node.connect(otherContext.destination) threw InvalidAccessError: "Failed to execute 'connect' on 'AudioNode': cannot connect to a destination belonging to a different audio context.". +PASS < [connections] All assertions passed. (total 6 assertions) +PASS > [channel-stuff] channelCount, channelCountMode, channelInterpretation +PASS GainNode.channelCount = 99 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channel count provided (99) is outside the range [1, 32].". +PASS GainNode.channelCount is not equal to 99. +PASS node.channelCountMode = "fancy" did not throw an exception. +PASS node.channelCountMode is equal to max. +PASS node.channelInterpretation = mode did not throw an exception. +PASS node.channelInterpretation is equal to speakers. +PASS context.destination.channelCount = 99 threw IndexSizeError: [error message omitted]. +PASS < [channel-stuff] All assertions passed. (total 7 assertions) +PASS > [audioparam] +PASS param.setValueCurveAtTime(null, 0, 0) threw TypeError: "Failed to execute 'setValueCurveAtTime' on 'AudioParam': The provided value cannot be converted to a sequence.". +PASS node.gain.exponentialRampToValueAtTime(-1, 0.1) did not throw an exception. +PASS node.gain.exponentialRampToValueAtTime(0, 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(1e-100, 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -149), 0.1) did not throw an exception. +PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -150), 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS < [audioparam] All assertions passed. (total 6 assertions) +PASS > [biquad] +PASS node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), new Float32Array(1)) did not throw an exception. +PASS node.getFrequencyResponse(null, new Float32Array(1), new Float32Array(1)) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 1 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(new Float32Array(1), null, new Float32Array(1)) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 2 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), null) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 3 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(shared_view, nonshared_view, nonshared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS node.getFrequencyResponse(nonshared_view, shared_view, nonshared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS node.getFrequencyResponse(nonshared_view, nonshared_view, shared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS < [biquad] All assertions passed. (total 7 assertions) +PASS > [offline-audio-context] +PASS new OfflineAudioContext(32, 100, context.sampleRate) did not throw an exception. +PASS new OfflineAudioContext(0, 100, context.sampleRate) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of channels provided (0) is outside the range [1, 32].". +PASS new OfflineAudioContext(99, 100, context.sampleRate) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of channels provided (99) is outside the range [1, 32].". +PASS new OfflineAudioContext(1, 100, 1) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The sampleRate provided (1) is outside the range [3000, 384000].". +PASS new OfflineAudioContext(1, 100, 1e6) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The sampleRate provided (1.00000e+6) is outside the range [3000, 384000].". +PASS new OfflineAudioContext(1, -88200000000000, 44100) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': OfflineAudioContext(1, 1448390656, 44100)". +PASS new OfflineAudioContext(1, 0, 44100) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of frames provided (0) is less than the minimum bound (1).". +PASS < [offline-audio-context] All assertions passed. (total 7 assertions) +PASS > [waveshaper] +PASS node.oversample = "9x" did not throw an exception. +PASS node.oversample is equal to none. +PASS node.curve = {} threw TypeError: "Failed to set the 'curve' property on 'WaveShaperNode': The provided value is not of type 'Float32Array'.". +PASS node.curve = new Float32Array(1) threw InvalidAccessError: "Failed to set the 'curve' property on 'WaveShaperNode': The curve length provided (1) is less than the minimum bound (2).". +PASS node.curve is equal to ${expected}. +PASS node.curve = new Float32Array(2) did not throw an exception. +PASS node.curve = null did not throw an exception. +PASS < [waveshaper] All assertions passed. (total 7 assertions) +PASS > [audio-buffer-source] AudioBufferSource start/stop +PASS source = context.createBufferSource() did not throw an exception. +PASS source.buffer = buffer did not throw an exception. +PASS source.buffer = context.createBuffer(1, 10, context.sampleRate) threw InvalidStateError: "Failed to set the 'buffer' property on 'AudioBufferSourceNode': Cannot set buffer after it has been already been set". +PASS source.start(-1) threw InvalidAccessError: "Failed to execute 'start' on 'AudioBufferSourceNode': The start time provided (-1) is less than the minimum bound (0).". +PASS source.start(Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(-Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, -Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, -1) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The offset provided (-1) is less than the minimum bound (0).". +PASS source.start(1, -Number.MIN_VALUE) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The offset provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.start(1, 1, Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, -Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, -1) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The duration provided (-1) is less than the minimum bound (0).". +PASS source.start(1, 1, -Number.MIN_VALUE) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The duration provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.start() did not throw an exception. +PASS source.stop(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.stop(Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop(-Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop(NaN) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop() did not throw an exception. +PASS source2 = context.createBufferSource() did not throw an exception. +PASS source2.buffer = buffer did not throw an exception. +PASS source2.start(0, 0) did not throw an exception. +PASS source3 = context.createBufferSource() did not throw an exception. +PASS source3.buffer = buffer did not throw an exception. +PASS source3.start(0, -1/Infinity) did not throw an exception. +PASS source4 = context.createBufferSource() did not throw an exception. +PASS source4.start() did not throw an exception. +PASS source5 = context.createBufferSource() did not throw an exception. +PASS source5.buffer = buffer did not throw an exception. +PASS source5.stop() threw InvalidStateError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.". +PASS source6 = context.createBufferSource() did not throw an exception. +PASS source6.buffer = buffer did not throw an exception. +PASS source6.start() did not throw an exception. +PASS source6.start() threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': cannot call start more than once.". +PASS source7 = context.createBufferSource() did not throw an exception. +PASS source7.buffer = buffer did not throw an exception. +PASS source7.start() did not throw an exception. +PASS source7.stop() did not throw an exception. +PASS < [audio-buffer-source] All assertions passed. (total 42 assertions) +PASS > [oscillator] start/stop +PASS source8 = context.createOscillator() did not throw an exception. +PASS source8.start(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The start time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source8.start(Infinity) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start(-Infinity) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start(NaN) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start() did not throw an exception. +PASS source8.stop(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source8.stop(Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop(-Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop(NaN) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop() did not throw an exception. +PASS osc = context.createOscillator() did not throw an exception. +PASS osc.stop() threw InvalidStateError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.". +PASS osc1 = context.createOscillator() did not throw an exception. +PASS osc1.start() did not throw an exception. +PASS osc1.stop() did not throw an exception. +PASS osc.setPeriodicWave(null) threw TypeError: "Failed to execute 'setPeriodicWave' on 'OscillatorNode': parameter 1 is not of type 'PeriodicWave'.". +PASS < [oscillator] All assertions passed. (total 17 assertions) +PASS > [convolver] +PASS oc = new OfflineAudioContext(1, 44100, 44100) did not throw an exception. +PASS conv = oc.createConvolver() did not throw an exception. +PASS conv.buffer = {} threw TypeError: "Failed to set the 'buffer' property on 'ConvolverNode': The provided value is not of type 'AudioBuffer'.". +PASS conv.buffer = oc.createBuffer(1, 100, 22050) threw NotSupportedError: "Failed to set the 'buffer' property on 'ConvolverNode': The buffer sample rate of 22050 does not match the context rate of 44100 Hz.". +PASS conv.buffer is equal to ${expected}. +PASS < [convolver] All assertions passed. (total 5 assertions) +PASS > [panner] +PASS panner.channelCount = 1 did not throw an exception. +PASS panner.channelCount = 2 did not throw an exception. +PASS PannerNode.channelCount = 0 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channelCount provided (0) is outside the range [1, 2].". +PASS PannerNode.channelCount is not equal to 0. +PASS PannerNode.channelCount = 3 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channelCount provided (3) is outside the range [1, 2].". +PASS PannerNode.channelCount is not equal to 3. +PASS PannerNode.channelCountMode = max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': Panner: 'max' is not allowed". +PASS PannerNode.channelCountMode is not equal to max. +PASS panner.channelCountMode = "explicit" did not throw an exception. +PASS panner.channelCountMode = "clamped-max" did not throw an exception. +PASS panner.channelCountMode = "junk" did not throw an exception. +PASS < [panner] All assertions passed. (total 11 assertions) +PASS > [script-processor] +PASS script = context.createScriptProcessor(256, 3) did not throw an exception. +PASS script.channelCount is equal to 3. +PASS script.channelCountMode is equal to explicit. +PASS script.channelCount = 3 did not throw an exception. +PASS ScriptProcessorNode.channelCount = 1 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': channelCount cannot be changed from 3 to 1". +PASS ScriptProcessorNode.channelCount is not equal to 1. +PASS ScriptProcessorNode.channelCount = 7 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': channelCount cannot be changed from 3 to 7". +PASS ScriptProcessorNode.channelCount is not equal to 7. +PASS script.channelCountMode = "explicit" did not throw an exception. +PASS ScriptProcessorNode.channelCountMode = max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': channelCountMode cannot be changed from 'explicit' to 'max'". +PASS ScriptProcessorNode.channelCountMode is not equal to max. +PASS ScriptProcessorNode.channelCountMode = clamped-max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': channelCountMode cannot be changed from 'explicit' to 'clamped-max'". +PASS ScriptProcessorNode.channelCountMode is not equal to clamped-max. +PASS script.channelCountMode = "junk" did not throw an exception. +PASS < [script-processor] All assertions passed. (total 14 assertions) +PASS > [misc] Miscellaneous tests +PASS osc.noteOn is equal to undefined. +PASS osc.noteOff is equal to undefined. +PASS source.noteOn is equal to undefined. +PASS source.noteOff is equal to undefined. +PASS < [misc] All assertions passed. (total 4 assertions) +PASS # AUDIT TASK RUNNER FINISHED: 22 tasks ran successfully. +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-exceptional-values.html b/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-exceptional-values.html index d66f6a2..01faf80b 100644 --- a/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-exceptional-values.html +++ b/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-exceptional-values.html
@@ -13,112 +13,223 @@ <script id="layout-test-code"> let audit = Audit.createTaskRunner(); - // For these values, AudioParam methods should throw an error because they - // are invalid; only - // finite values are allowed. - let targetValues = [Infinity, -Infinity, NaN]; + // Context to use for all of the tests. The context isn't used for any + // processing; just need one for creating a gain node, which is used for + // all the tests. + let context; - // For these time values, AudioParam methods should throw an error because - // they are - // invalid. Only finite non-negative values are allowed for any time or - // time-like parameter. - let timeValues = [-1, Infinity, -Infinity, NaN]; + // For these values, AudioParam methods should throw a Typeerror because + // they are not finite values. + let nonFiniteValues = [Infinity, -Infinity, NaN]; - // For these duration values, AudioParam methods should throw an error - // because they are - // invalid. Only finite values are allowed for any duration parameter. - let durationValues = [-1, Infinity, -Infinity, NaN, 0]; + audit.define('initialize', (task, should) => { + should(() => { + // Context for testing. Rendering isn't done, so any valid values can + // be used here so might as well make them small. + context = new OfflineAudioContext(1, 1, 8000); + }, 'Creating context for testing').notThrow(); - // For these timeConstant values for setTargetAtTime an error must be - // thrown because they are - // invalid. - let timeConstantValues = [-1, Infinity, -Infinity, NaN]; - - // Just an array for use by setValueCurveAtTime. The length and contents - // of the array are not - // important. - let curve = new Float32Array(10); + task.done(); + }); audit.define( { - label: 'test', - description: - 'Test exceptional arguments for AudioParam timeline events' + label: 'test value', + description: 'Test non-finite arguments for AudioParam value' }, - function(task, should) { - let context = new AudioContext(); + (task, should) => { let gain = context.createGain(); - // Test the value parameter - for (value of targetValues) { - let testMethods = [ - {name: 'setValueAtTime', arg: [value, 1]}, - {name: 'linearRampToValueAtTime', arg: [value, 1]}, - {name: 'exponentialRampToValueAtTime', arg: [value, 1]}, - {name: 'setTargetAtTime', arg: [value, 1, 1]} - ]; + // Default method for generating the arguments for an automation + // method for testing the value of the automation. + let defaultFuncArg = (value) => [value, 1]; - for (method of testMethods) { - let message = - 'gain.gain.' + method.name + '(' + method.arg + ')'; - should( - () => gain.gain[method.name].apply(gain.gain, method.arg), - message) - .throw(); + // Test the value parameter + doTests(should, gain, 'TypeError', nonFiniteValues, [ + {automationName: 'setValueAtTime', funcArg: defaultFuncArg}, { + automationName: 'linearRampToValueAtTime', + funcArg: defaultFuncArg + }, + { + automationName: 'exponentialRampToValueAtTime', + funcArg: defaultFuncArg + }, + { + automationName: 'setTargetAtTime', + funcArg: (value) => [value, 1, 1] } - } + ]); + task.done(); + }); + + audit.define( + { + label: 'test time', + description: 'Test non-finite arguments for AudioParam time' + }, + (task, should) => { + let gain = context.createGain(); + + // Default method for generating the arguments for an automation + // method for testing the time parameter of the automation. + let defaultFuncArg = (startTime) => [1, startTime]; // Test the time parameter - for (startTime of timeValues) { - let testMethods = [ - {name: 'setValueAtTime', arg: [1, startTime]}, - {name: 'linearRampToValueAtTime', arg: [1, startTime]}, - {name: 'exponentialRampToValueAtTime', arg: [1, startTime]}, - {name: 'setTargetAtTime', arg: [1, startTime, 1]} - ]; + doTests(should, gain, 'TypeError', nonFiniteValues, [ + {automationName: 'setValueAtTime', funcArg: defaultFuncArg}, + { + automationName: 'linearRampToValueAtTime', + funcArg: defaultFuncArg + }, + { + automationName: 'exponentialRampToValueAtTime', + funcArg: defaultFuncArg + }, + // Test start time for setTarget + { + automationName: 'setTargetAtTime', + funcArg: (startTime) => [1, startTime, 1] + }, + // Test time constant for setTarget + { + automationName: 'setTargetAtTime', + funcArg: (timeConstant) => [1, 1, timeConstant] + }, + ]); - for (method of testMethods) { - let message = - 'gain.gain.' + method.name + '(' + method.arg + ')'; - should( - () => gain.gain[method.name].apply(gain.gain, method.arg), - message) - .throw(); - } - } + task.done(); + }); - // Test time constant - for (value of timeConstantValues) { - should( - () => gain.gain.setTargetAtTime(1, 1, value), - 'gain.gain.setTargetAtTime(1, 1, ' + value + ')') - .throw(); - } + audit.define( + { + label: 'test setValueCurve', + description: 'Test non-finite arguments for setValueCurveAtTime' + }, + (task, should) => { + let gain = context.createGain(); - // Test startTime and duration for setValueCurveAtTime - for (startTime of timeValues) { - should( - () => gain.gain.setValueCurveAtTime(curve, startTime, 1), - 'gain.gain.setValueCurveAtTime(curve, ' + startTime + ', 1)') - .throw(); - } - for (duration of durationValues) { - should( - () => gain.gain.setValueCurveAtTime(curve, 1, duration), - 'gain.gain.setValueCurveAtTime(curve, 1, ' + duration + ')') - .throw(); - } - // Non-finite curve values should signal an error. - for (curve of [[1, 2, Infinity, 3], [1, NaN, 2, 3]]) { - should( - () => gain.gain.setValueCurveAtTime(curve, 1, 1), - 'gain.gain.setValueCurveAtTime([' + curve + '], 1, 1)') - .throw(); - } + // Just an array for use by setValueCurveAtTime. The length and + // contents of the array are not important. + let curve = new Float32Array(3); + + doTests(should, gain, 'TypeError', nonFiniteValues, [ + { + automationName: 'setValueCurveAtTime', + funcArg: (startTime) => [curve, startTime, 1] + }, + ]); + + // Non-finite values for the curve should signal an error + doTests( + should, gain, 'TypeError', + [[1, 2, Infinity, 3], [1, NaN, 2, 3]], [{ + automationName: 'setValueCurveAtTime', + funcArg: (c) => [c, 1, 1] + }]); + + task.done(); + }); + + audit.define( + { + label: 'special cases 1', + description: 'Test exceptions for finite values' + }, + (task, should) => { + let gain = context.createGain(); + + // Default method for generating the arguments for an automation + // method for testing the time parameter of the automation. + let defaultFuncArg = (startTime) => [1, startTime]; + + // Test the time parameter + let curve = new Float32Array(3); + doTests(should, gain, 'RangeError', [-1], [ + {automationName: 'setValueAtTime', funcArg: defaultFuncArg}, + { + automationName: 'linearRampToValueAtTime', + funcArg: defaultFuncArg + }, + { + automationName: 'exponentialRampToValueAtTime', + funcArg: defaultFuncArg + }, + { + automationName: 'setTargetAtTime', + funcArg: (startTime) => [1, startTime, 1] + }, + // Test time constant + { + automationName: 'setTargetAtTime', + funcArg: (timeConstant) => [1, 1, timeConstant] + }, + // startTime and duration for setValueCurve + { + automationName: 'setValueCurveAtTime', + funcArg: (startTime) => [curve, startTime, 1] + }, + { + automationName: 'setValueCurveAtTime', + funcArg: (duration) => [curve, 1, duration] + }, + ]); + + // One final test for setValueCurve: duration can't be 0. + should( + () => gain.gain.setValueCurveAtTime(curve, 1, 0), + 'gain.gain.setValueCurveAtTime(curve, 1, 0)') + .throw('RangeError'); + + task.done(); + }); + + audit.define( + { + label: 'special cases 2', + description: 'Test special cases for expeonentialRamp' + }, + (task, should) => { + let gain = context.createGain(); + + doTests(should, gain, 'RangeError', [0, -1e-100, 1e-100], [{ + automationName: 'exponentialRampToValueAtTime', + funcArg: (value) => [value, 1] + }]); + task.done(); }); audit.run(); + + // Run test over the set of values in |testValues| for all of the + // automation methods in |testMethods|. The expected error type is + // |errorName|. |testMethods| is an array of dictionaries with attributes + // |automationName| giving the name of the automation method to be tested + // and |funcArg| being a function of one parameter that produces an array + // that will be used as the argument to the automation method. + function doTests(should, node, errorName, testValues, testMethods) { + testValues.forEach(value => { + testMethods.forEach(method => { + let args = method.funcArg(value); + let message = 'gain.gain.' + method.automationName + '(' + + argString(args) + ')'; + should(() => node.gain[method.automationName](...args), message) + .throw(errorName); + }); + }); + } + + // Specialized printer for automation arguments so that messages make + // sense. We assume the first element is either a number or an array. If + // it's an array, there are always three elements, and we want to print + // out the brackets for the array argument. + function argString(arg) { + if (typeof(arg[0]) === 'number') { + return arg.toString(); + } + + return '[' + arg[0] + '],' + arg[1] + ',' + arg[2]; + } </script> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-method-chaining.html b/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-method-chaining.html index 3eef32f..00f0dce 100644 --- a/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-method-chaining.html +++ b/third_party/WebKit/LayoutTests/webaudio/AudioParam/audioparam-method-chaining.html
@@ -68,7 +68,7 @@ .linearRampToValueAtTime(2.0, 1.0); }, 'Calling setValueAtTime() with a negative end time') - .throw('InvalidAccessError'); + .throw('RangeError'); // The first operation succeeds but the second fails due to zero target // value for the exponential ramp. Thus only the first should have @@ -79,7 +79,7 @@ 0.0, 1.0); }, 'Calling exponentialRampToValueAtTime() with a zero target value') - .throw('InvalidAccessError'); + .throw('RangeError'); osc.start(); osc.stop(1.0);
diff --git a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt index de0c2a7..1641d40 100644 --- a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt
@@ -105,10 +105,10 @@ PASS > [audioparam] PASS param.setValueCurveAtTime(null, 0, 0) threw TypeError: "Failed to execute 'setValueCurveAtTime' on 'AudioParam': The provided value cannot be converted to a sequence.". PASS node.gain.exponentialRampToValueAtTime(-1, 0.1) did not throw an exception. -PASS node.gain.exponentialRampToValueAtTime(0, 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". -PASS node.gain.exponentialRampToValueAtTime(1e-100, 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(0, 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(1e-100, 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -149), 0.1) did not throw an exception. -PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -150), 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -150), 0.1) threw RangeError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". PASS < [audioparam] All assertions passed. (total 6 assertions) PASS > [biquad] PASS node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), new Float32Array(1)) did not throw an exception.
diff --git a/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp b/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp index 1a1239d5..0fb850a8 100644 --- a/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp
@@ -138,10 +138,10 @@ if (!can_access) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccess); + WebFeature::kCrossOriginPropertyAccess); if (target->opener() == accessing_window) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccessFromOpener); + WebFeature::kCrossOriginPropertyAccessFromOpener); } } @@ -166,10 +166,10 @@ if (!can_access) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccess); + WebFeature::kCrossOriginPropertyAccess); if (target->opener() == accessing_window) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccessFromOpener); + WebFeature::kCrossOriginPropertyAccessFromOpener); } } @@ -195,10 +195,10 @@ if (!can_access) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccess); + WebFeature::kCrossOriginPropertyAccess); if (target->DomWindow()->opener() == accessing_window) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccessFromOpener); + WebFeature::kCrossOriginPropertyAccessFromOpener); } } @@ -224,10 +224,10 @@ if (!can_access) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccess); + WebFeature::kCrossOriginPropertyAccess); if (target->DomWindow()->opener() == accessing_window) { UseCounter::Count(accessing_window->GetFrame(), - UseCounter::kCrossOriginPropertyAccessFromOpener); + WebFeature::kCrossOriginPropertyAccessFromOpener); } }
diff --git a/third_party/WebKit/Source/bindings/core/v8/BindingSecurityTest.cpp b/third_party/WebKit/Source/bindings/core/v8/BindingSecurityTest.cpp index 904579b9..7f840bcf 100644 --- a/third_party/WebKit/Source/bindings/core/v8/BindingSecurityTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/BindingSecurityTest.cpp
@@ -107,33 +107,33 @@ TEST_P(BindingSecurityCounterTest, CrossOriginWindow) { LoadWindowAndAccessProperty(OriginDisposition::CrossOrigin, GetParam()); EXPECT_TRUE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccess)); + WebFeature::kCrossOriginPropertyAccess)); EXPECT_TRUE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccessFromOpener)); + WebFeature::kCrossOriginPropertyAccessFromOpener)); } TEST_P(BindingSecurityCounterTest, SameOriginWindow) { LoadWindowAndAccessProperty(OriginDisposition::SameOrigin, GetParam()); EXPECT_FALSE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccess)); + WebFeature::kCrossOriginPropertyAccess)); EXPECT_FALSE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccessFromOpener)); + WebFeature::kCrossOriginPropertyAccessFromOpener)); } TEST_P(BindingSecurityCounterTest, CrossOriginFrame) { LoadFrameAndAccessProperty(OriginDisposition::CrossOrigin, GetParam()); EXPECT_TRUE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccess)); + WebFeature::kCrossOriginPropertyAccess)); EXPECT_FALSE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccessFromOpener)); + WebFeature::kCrossOriginPropertyAccessFromOpener)); } TEST_P(BindingSecurityCounterTest, SameOriginFrame) { LoadFrameAndAccessProperty(OriginDisposition::SameOrigin, GetParam()); EXPECT_FALSE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccess)); + WebFeature::kCrossOriginPropertyAccess)); EXPECT_FALSE(GetDocument().GetPage()->GetUseCounter().HasRecordedMeasurement( - UseCounter::kCrossOriginPropertyAccessFromOpener)); + WebFeature::kCrossOriginPropertyAccessFromOpener)); } } // namespace
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp index 853c25f..ea5a972 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp
@@ -58,7 +58,7 @@ EnteredDOMWindow(script_state->GetIsolate()), ToDocument(target)->GetFrame(), BindingSecurity::ErrorReportOption::kDoNotReport)) { - UseCounter::Count(target, UseCounter::kScheduledActionIgnored); + UseCounter::Count(target, WebFeature::kScheduledActionIgnored); return new ScheduledAction(script_state); } } @@ -73,7 +73,7 @@ EnteredDOMWindow(script_state->GetIsolate()), ToDocument(target)->GetFrame(), BindingSecurity::ErrorReportOption::kDoNotReport)) { - UseCounter::Count(target, UseCounter::kScheduledActionIgnored); + UseCounter::Count(target, WebFeature::kScheduledActionIgnored); return new ScheduledAction(script_state); } }
diff --git a/third_party/WebKit/Source/bindings/core/v8/UseCounterCallback.cpp b/third_party/WebKit/Source/bindings/core/v8/UseCounterCallback.cpp index 16c32963..f094f00 100644 --- a/third_party/WebKit/Source/bindings/core/v8/UseCounterCallback.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/UseCounterCallback.cpp
@@ -16,110 +16,110 @@ if (V8PerIsolateData::From(isolate)->IsUseCounterDisabled()) return; - UseCounter::Feature blink_feature; + WebFeature blink_feature; bool deprecated = false; switch (feature) { case v8::Isolate::kUseAsm: - blink_feature = UseCounter::kUseAsm; + blink_feature = WebFeature::kUseAsm; break; case v8::Isolate::kBreakIterator: - blink_feature = UseCounter::kBreakIterator; + blink_feature = WebFeature::kBreakIterator; break; case v8::Isolate::kLegacyConst: - blink_feature = UseCounter::kLegacyConst; + blink_feature = WebFeature::kLegacyConst; break; case v8::Isolate::kSloppyMode: - blink_feature = UseCounter::kV8SloppyMode; + blink_feature = WebFeature::kV8SloppyMode; break; case v8::Isolate::kStrictMode: - blink_feature = UseCounter::kV8StrictMode; + blink_feature = WebFeature::kV8StrictMode; break; case v8::Isolate::kStrongMode: - blink_feature = UseCounter::kV8StrongMode; + blink_feature = WebFeature::kV8StrongMode; break; case v8::Isolate::kRegExpPrototypeStickyGetter: - blink_feature = UseCounter::kV8RegExpPrototypeStickyGetter; + blink_feature = WebFeature::kV8RegExpPrototypeStickyGetter; break; case v8::Isolate::kRegExpPrototypeToString: - blink_feature = UseCounter::kV8RegExpPrototypeToString; + blink_feature = WebFeature::kV8RegExpPrototypeToString; break; case v8::Isolate::kRegExpPrototypeUnicodeGetter: - blink_feature = UseCounter::kV8RegExpPrototypeUnicodeGetter; + blink_feature = WebFeature::kV8RegExpPrototypeUnicodeGetter; break; case v8::Isolate::kIntlV8Parse: - blink_feature = UseCounter::kV8IntlV8Parse; + blink_feature = WebFeature::kV8IntlV8Parse; break; case v8::Isolate::kIntlPattern: - blink_feature = UseCounter::kV8IntlPattern; + blink_feature = WebFeature::kV8IntlPattern; break; case v8::Isolate::kIntlResolved: - blink_feature = UseCounter::kV8IntlResolved; + blink_feature = WebFeature::kV8IntlResolved; break; case v8::Isolate::kPromiseChain: - blink_feature = UseCounter::kV8PromiseChain; + blink_feature = WebFeature::kV8PromiseChain; break; case v8::Isolate::kPromiseAccept: - blink_feature = UseCounter::kV8PromiseAccept; + blink_feature = WebFeature::kV8PromiseAccept; break; case v8::Isolate::kPromiseDefer: - blink_feature = UseCounter::kV8PromiseDefer; + blink_feature = WebFeature::kV8PromiseDefer; break; case v8::Isolate::kHtmlCommentInExternalScript: - blink_feature = UseCounter::kV8HTMLCommentInExternalScript; + blink_feature = WebFeature::kV8HTMLCommentInExternalScript; break; case v8::Isolate::kHtmlComment: - blink_feature = UseCounter::kV8HTMLComment; + blink_feature = WebFeature::kV8HTMLComment; break; case v8::Isolate::kSloppyModeBlockScopedFunctionRedefinition: - blink_feature = UseCounter::kV8SloppyModeBlockScopedFunctionRedefinition; + blink_feature = WebFeature::kV8SloppyModeBlockScopedFunctionRedefinition; break; case v8::Isolate::kForInInitializer: - blink_feature = UseCounter::kV8ForInInitializer; + blink_feature = WebFeature::kV8ForInInitializer; break; case v8::Isolate::kArrayProtectorDirtied: - blink_feature = UseCounter::kV8ArrayProtectorDirtied; + blink_feature = WebFeature::kV8ArrayProtectorDirtied; break; case v8::Isolate::kArraySpeciesModified: - blink_feature = UseCounter::kV8ArraySpeciesModified; + blink_feature = WebFeature::kV8ArraySpeciesModified; break; case v8::Isolate::kArrayPrototypeConstructorModified: - blink_feature = UseCounter::kV8ArrayPrototypeConstructorModified; + blink_feature = WebFeature::kV8ArrayPrototypeConstructorModified; break; case v8::Isolate::kArrayInstanceProtoModified: - blink_feature = UseCounter::kV8ArrayInstanceProtoModified; + blink_feature = WebFeature::kV8ArrayInstanceProtoModified; break; case v8::Isolate::kArrayInstanceConstructorModified: - blink_feature = UseCounter::kV8ArrayInstanceConstructorModified; + blink_feature = WebFeature::kV8ArrayInstanceConstructorModified; break; case v8::Isolate::kLegacyFunctionDeclaration: - blink_feature = UseCounter::kV8LegacyFunctionDeclaration; + blink_feature = WebFeature::kV8LegacyFunctionDeclaration; break; case v8::Isolate::kRegExpPrototypeSourceGetter: - blink_feature = UseCounter::kV8RegExpPrototypeSourceGetter; + blink_feature = WebFeature::kV8RegExpPrototypeSourceGetter; break; case v8::Isolate::kRegExpPrototypeOldFlagGetter: - blink_feature = UseCounter::kV8RegExpPrototypeOldFlagGetter; + blink_feature = WebFeature::kV8RegExpPrototypeOldFlagGetter; break; case v8::Isolate::kDecimalWithLeadingZeroInStrictMode: - blink_feature = UseCounter::kV8DecimalWithLeadingZeroInStrictMode; + blink_feature = WebFeature::kV8DecimalWithLeadingZeroInStrictMode; break; case v8::Isolate::kLegacyDateParser: - blink_feature = UseCounter::kV8LegacyDateParser; + blink_feature = WebFeature::kV8LegacyDateParser; break; case v8::Isolate::kDefineGetterOrSetterWouldThrow: - blink_feature = UseCounter::kV8DefineGetterOrSetterWouldThrow; + blink_feature = WebFeature::kV8DefineGetterOrSetterWouldThrow; break; case v8::Isolate::kFunctionConstructorReturnedUndefined: - blink_feature = UseCounter::kV8FunctionConstructorReturnedUndefined; + blink_feature = WebFeature::kV8FunctionConstructorReturnedUndefined; break; case v8::Isolate::kAssigmentExpressionLHSIsCallInSloppy: - blink_feature = UseCounter::kV8AssigmentExpressionLHSIsCallInSloppy; + blink_feature = WebFeature::kV8AssigmentExpressionLHSIsCallInSloppy; break; case v8::Isolate::kAssigmentExpressionLHSIsCallInStrict: - blink_feature = UseCounter::kV8AssigmentExpressionLHSIsCallInStrict; + blink_feature = WebFeature::kV8AssigmentExpressionLHSIsCallInStrict; break; case v8::Isolate::kPromiseConstructorReturnedUndefined: - blink_feature = UseCounter::kV8PromiseConstructorReturnedUndefined; + blink_feature = WebFeature::kV8PromiseConstructorReturnedUndefined; break; default: // This can happen if V8 has added counters that this version of Blink
diff --git a/third_party/WebKit/Source/bindings/core/v8/V0CustomElementConstructorBuilder.cpp b/third_party/WebKit/Source/bindings/core/v8/V0CustomElementConstructorBuilder.cpp index 906e5c5..8330faa3 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V0CustomElementConstructorBuilder.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V0CustomElementConstructorBuilder.cpp
@@ -347,7 +347,7 @@ StringOrDictionary::fromString(maybe_type->IsNull() ? g_null_atom : type), exception_state); if (element) { - UseCounter::Count(document, UseCounter::kV0CustomElementsConstruct); + UseCounter::Count(document, WebFeature::kV0CustomElementsConstruct); } V8SetReturnValueFast(info, element, document); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.cpp b/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.cpp index 7d65429..3fccbf22 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.cpp
@@ -74,7 +74,7 @@ v8::Local<v8::Value> receiver; if (filter->IsFunction()) { UseCounter::Count(CurrentExecutionContext(isolate), - UseCounter::kNodeFilterIsFunction); + WebFeature::kNodeFilterIsFunction); callback = v8::Local<v8::Function>::Cast(filter); receiver = v8::Undefined(isolate); } else { @@ -89,7 +89,7 @@ return NodeFilter::kFilterReject; } UseCounter::Count(CurrentExecutionContext(isolate), - UseCounter::kNodeFilterIsObject); + WebFeature::kNodeFilterIsObject); callback = v8::Local<v8::Function>::Cast(value); receiver = filter; }
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8DocumentCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8DocumentCustom.cpp index c5bcce37..d0d3d6f 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8DocumentCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8DocumentCustom.cpp
@@ -108,19 +108,19 @@ v8::Local<v8::Value> v8_window = info[0]; if (IsUndefinedOrNull(v8_window)) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentCreateTouchWindowNull); + WebFeature::kDocumentCreateTouchWindowNull); } else if (!ToDOMWindow(info.GetIsolate(), v8_window)) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentCreateTouchWindowWrongType); + WebFeature::kDocumentCreateTouchWindowWrongType); } v8::Local<v8::Value> v8_target = info[1]; if (IsUndefinedOrNull(v8_target)) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentCreateTouchTargetNull); + WebFeature::kDocumentCreateTouchTargetNull); } else if (!V8EventTarget::hasInstance(v8_target, info.GetIsolate())) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentCreateTouchTargetWrongType); + WebFeature::kDocumentCreateTouchTargetWrongType); } }
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8EventTargetCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8EventTargetCustom.cpp index 875dbec..788a365 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8EventTargetCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8EventTargetCustom.cpp
@@ -41,11 +41,11 @@ EventTarget*) { if (info.Length() >= 3 && info[2]->IsObject()) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kAddEventListenerThirdArgumentIsObject); + WebFeature::kAddEventListenerThirdArgumentIsObject); } if (info.Length() >= 4) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kAddEventListenerFourArguments); + WebFeature::kAddEventListenerFourArguments); } } @@ -62,11 +62,11 @@ EventTarget*) { if (info.Length() >= 3 && info[2]->IsObject()) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kRemoveEventListenerThirdArgumentIsObject); + WebFeature::kRemoveEventListenerThirdArgumentIsObject); } if (info.Length() >= 4) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kRemoveEventListenerFourArguments); + WebFeature::kRemoveEventListenerFourArguments); } }
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp index 64f898c..e382a47 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp
@@ -63,9 +63,9 @@ HTMLAllCollection* collection, v8::Local<v8::Value> argument, const CallbackInfo& info, - UseCounter::Feature named_feature, - UseCounter::Feature indexed_feature, - UseCounter::Feature indexed_with_non_number_feature) { + WebFeature named_feature, + WebFeature indexed_feature, + WebFeature indexed_with_non_number_feature) { v8::Local<v8::Uint32> index; if (!argument->ToArrayIndex(info.GetIsolate()->GetCurrentContext()) .ToLocal(&index)) { @@ -95,41 +95,41 @@ const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 1) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentAllItemNoArguments); + WebFeature::kDocumentAllItemNoArguments); return; } HTMLAllCollection* impl = V8HTMLAllCollection::toImpl(info.Holder()); V8SetReturnValue( - info, GetItem(impl, info[0], info, UseCounter::kDocumentAllItemNamed, - UseCounter::kDocumentAllItemIndexed, - UseCounter::kDocumentAllItemIndexedWithNonNumber)); + info, GetItem(impl, info[0], info, WebFeature::kDocumentAllItemNamed, + WebFeature::kDocumentAllItemIndexed, + WebFeature::kDocumentAllItemIndexedWithNonNumber)); } void V8HTMLAllCollection::legacyCallCustom( const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 1) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentAllLegacyCallNoArguments); + WebFeature::kDocumentAllLegacyCallNoArguments); return; } UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentAllLegacyCall); + WebFeature::kDocumentAllLegacyCall); HTMLAllCollection* impl = V8HTMLAllCollection::toImpl(info.Holder()); if (info.Length() == 1) { V8SetReturnValue( info, - GetItem(impl, info[0], info, UseCounter::kDocumentAllLegacyCallNamed, - UseCounter::kDocumentAllLegacyCallIndexed, - UseCounter::kDocumentAllLegacyCallIndexedWithNonNumber)); + GetItem(impl, info[0], info, WebFeature::kDocumentAllLegacyCallNamed, + WebFeature::kDocumentAllLegacyCallIndexed, + WebFeature::kDocumentAllLegacyCallIndexedWithNonNumber)); return; } UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kDocumentAllLegacyCallTwoArguments); + WebFeature::kDocumentAllLegacyCallTwoArguments); // If there is a second argument it is the index of the item we want. TOSTRING_VOID(V8StringResource<>, name, info[0]);
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLPlugInElementCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLPlugInElementCustom.cpp index a4482fa9..d21de18 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLPlugInElementCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLPlugInElementCustom.cpp
@@ -51,14 +51,14 @@ if (!state->World().IsMainWorld()) { if (state->World().IsIsolatedWorld()) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kPluginInstanceAccessFromIsolatedWorld); + WebFeature::kPluginInstanceAccessFromIsolatedWorld); } // The plugin system cannot deal with multiple worlds, so block any // non-main world access. return; } UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kPluginInstanceAccessFromMainWorld); + WebFeature::kPluginInstanceAccessFromMainWorld); HTMLPlugInElement* impl = ElementType::toImpl(info.Holder()); v8::Local<v8::Object> instance = impl->PluginWrapper(); @@ -121,7 +121,7 @@ const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kHTMLEmbedElementGetter); + WebFeature::kHTMLEmbedElementGetter); GetScriptableObjectProperty<V8HTMLEmbedElement>(name, info); } @@ -129,7 +129,7 @@ const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kHTMLObjectElementGetter); + WebFeature::kHTMLObjectElementGetter); GetScriptableObjectProperty<V8HTMLObjectElement>(name, info); } @@ -138,7 +138,7 @@ v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kHTMLEmbedElementSetter); + WebFeature::kHTMLEmbedElementSetter); SetScriptableObjectProperty<V8HTMLEmbedElement>(name, value, info); } @@ -147,7 +147,7 @@ v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kHTMLObjectElementSetter); + WebFeature::kHTMLObjectElementSetter); SetScriptableObjectProperty<V8HTMLObjectElement>(name, value, info); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp index 9e4b7b8..fca0a09 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp
@@ -211,7 +211,7 @@ LocalDOMWindow* source = CurrentDOMWindow(info.GetIsolate()); DCHECK(window); - UseCounter::Count(source->GetFrame(), UseCounter::kWindowPostMessage); + UseCounter::Count(source->GetFrame(), WebFeature::kWindowPostMessage); // If called directly by WebCore we don't have a calling context. if (!source) { @@ -313,7 +313,7 @@ Frame* child = frame->Tree().ScopedChild(name); if (child) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), - UseCounter::kNamedAccessOnWindow_ChildBrowsingContext); + WebFeature::kNamedAccessOnWindow_ChildBrowsingContext); // step 3. Remove each browsing context from childBrowsingContexts whose // active document's origin is not same origin with activeDocument's origin @@ -327,7 +327,7 @@ UseCounter::Count( CurrentExecutionContext(info.GetIsolate()), - UseCounter:: + WebFeature:: kNamedAccessOnWindow_ChildBrowsingContext_CrossOriginNameMismatch); // In addition to the above spec'ed case, we return the child window // regardless of step 3 due to crbug.com/701489 for the time being. @@ -361,14 +361,14 @@ if (!has_named_item && has_id_item && !doc->ContainsMultipleElementsWithId(name)) { - UseCounter::Count(doc, UseCounter::kDOMClobberedVariableAccessed); + UseCounter::Count(doc, WebFeature::kDOMClobberedVariableAccessed); V8SetReturnValueFast(info, doc->getElementById(name), window); return; } HTMLCollection* items = doc->WindowNamedItems(name); if (!items->IsEmpty()) { - UseCounter::Count(doc, UseCounter::kDOMClobberedVariableAccessed); + UseCounter::Count(doc, WebFeature::kDOMClobberedVariableAccessed); // TODO(esprehn): Firefox doesn't return an HTMLCollection here if there's // multiple with the same name, but Chrome and Safari does. What's the
diff --git a/third_party/WebKit/Source/bindings/templates/constants.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/constants.cpp.tmpl index ff8dc55..2223379 100644 --- a/third_party/WebKit/Source/bindings/templates/constants.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/constants.cpp.tmpl
@@ -2,10 +2,10 @@ {% macro constant_getter_callback(constant) %} void {{v8_class_or_partial}}::{{constant.name}}ConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) { {% if constant.deprecate_as %} - Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), UseCounter::k{{constant.deprecate_as}}); + Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{constant.deprecate_as}}); {% endif %} {% if constant.measure_as %} - UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), UseCounter::k{{constant.measure_as('ConstantGetter')}}); + UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::k{{constant.measure_as('ConstantGetter')}}); {% endif %} {% if constant.idl_type in ('Double', 'Float') %} V8SetReturnValue(info, {{constant.value}});
diff --git a/third_party/WebKit/Source/bindings/templates/dictionary_v8.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/dictionary_v8.cpp.tmpl index 7b718cb..c47cf8f 100644 --- a/third_party/WebKit/Source/bindings/templates/dictionary_v8.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/dictionary_v8.cpp.tmpl
@@ -74,7 +74,7 @@ {% endif %} } else { {% if member.deprecate_as %} - Deprecation::CountDeprecation(CurrentExecutionContext(isolate), UseCounter::k{{member.deprecate_as}}); + Deprecation::CountDeprecation(CurrentExecutionContext(isolate), WebFeature::k{{member.deprecate_as}}); {% endif %} {{v8_value_to_local_cpp_value(member) | indent}} {% if member.is_interface_type %}
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp index 882d358..4fbca80 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp
@@ -60,12 +60,12 @@ } // namespace TestConstantsV8Internal void V8TestConstants::DEPRECATED_CONSTANTConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) { - Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), UseCounter::kConstant); + Deprecation::CountDeprecation(CurrentExecutionContext(info.GetIsolate()), WebFeature::kConstant); V8SetReturnValueInt(info, 1); } void V8TestConstants::MEASURED_CONSTANTConstantGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info) { - UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), UseCounter::kConstant); + UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kConstant); V8SetReturnValueInt(info, 1); }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp index bda6439..8c7f0e9 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp
@@ -154,7 +154,7 @@ if (deprecatedCreateMemberValue.IsEmpty() || deprecatedCreateMemberValue->IsUndefined()) { // Do nothing. } else { - Deprecation::CountDeprecation(CurrentExecutionContext(isolate), UseCounter::kCreateMember); + Deprecation::CountDeprecation(CurrentExecutionContext(isolate), WebFeature::kCreateMember); bool deprecatedCreateMember = NativeValueTraits<IDLBoolean>::NativeValue(isolate, deprecatedCreateMemberValue, exceptionState); if (exceptionState.HadException()) return;
diff --git a/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl b/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl index 5345c5b6..1d5b5f8 100644 --- a/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl
@@ -21,7 +21,7 @@ if (type == "{{event|script_name}}"{% if event.RuntimeEnabled %} && RuntimeEnabledFeatures::{{event.RuntimeEnabled}}(){% endif %}) { {% endif %} {% if not event|script_name|create_event_whitelist %} - UseCounter::Count(executionContext, UseCounter::k{{event|script_name|measure_name}}); + UseCounter::Count(executionContext, WebFeature::k{{event|script_name|measure_name}}); {% endif %} return {{event|cpp_name}}::Create(); }
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index 9324450..5941535 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1240,10 +1240,10 @@ "fileapi/FileTest.cpp", "frame/DOMTimerTest.cpp", "frame/FrameTest.cpp", - "frame/FrameViewTest.cpp", "frame/HistoryTest.cpp", "frame/ImageBitmapTest.cpp", "frame/LocalFrameTest.cpp", + "frame/LocalFrameViewTest.cpp", "frame/OriginsUsingFeaturesTest.cpp", "frame/PerformanceMonitorTest.cpp", "frame/RootFrameViewportTest.cpp",
diff --git a/third_party/WebKit/Source/core/animation/Animation.cpp b/third_party/WebKit/Source/core/animation/Animation.cpp index 4ce267c..19b5e30 100644 --- a/third_party/WebKit/Source/core/animation/Animation.cpp +++ b/third_party/WebKit/Source/core/animation/Animation.cpp
@@ -1115,7 +1115,7 @@ EventTargetWithInlineData::AddedEventListener(event_type, registered_listener); if (event_type == EventTypeNames::finish) - UseCounter::Count(GetExecutionContext(), UseCounter::kAnimationFinishEvent); + UseCounter::Count(GetExecutionContext(), WebFeature::kAnimationFinishEvent); } void Animation::PauseForTesting(double pause_time) {
diff --git a/third_party/WebKit/Source/core/animation/AnimationInputHelpers.cpp b/third_party/WebKit/Source/core/animation/AnimationInputHelpers.cpp index a8f7d556..2871b80e 100644 --- a/third_party/WebKit/Source/core/animation/AnimationInputHelpers.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationInputHelpers.cpp
@@ -238,10 +238,10 @@ // for easing. See http://crbug.com/601672 if (string == "function (a){return a}") { UseCounter::Count(*document, - UseCounter::kWebAnimationsEasingAsFunctionLinear); + WebFeature::kWebAnimationsEasingAsFunctionLinear); } else { UseCounter::Count(*document, - UseCounter::kWebAnimationsEasingAsFunctionOther); + WebFeature::kWebAnimationsEasingAsFunctionOther); } } }
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffect.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffect.cpp index 4773aca..ec087542 100644 --- a/third_party/WebKit/Source/core/animation/KeyframeEffect.cpp +++ b/third_party/WebKit/Source/core/animation/KeyframeEffect.cpp
@@ -62,7 +62,7 @@ if (element) { UseCounter::Count( element->GetDocument(), - UseCounter::kAnimationConstructorKeyframeListEffectObjectTiming); + WebFeature::kAnimationConstructorKeyframeListEffectObjectTiming); } Timing timing; Document* document = element ? &element->GetDocument() : nullptr; @@ -83,7 +83,7 @@ if (element) { UseCounter::Count( element->GetDocument(), - UseCounter::kAnimationConstructorKeyframeListEffectNoTiming); + WebFeature::kAnimationConstructorKeyframeListEffectNoTiming); } return Create(element, EffectInput::Convert(element, effect_input, execution_context,
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp index fd12a41..fac358b 100644 --- a/third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp +++ b/third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp
@@ -127,7 +127,7 @@ } if (updated && has_neutral_compositable_keyframe) { UseCounter::Count(element.GetDocument(), - UseCounter::kSyntheticKeyframesInCompositedCSSAnimation); + WebFeature::kSyntheticKeyframesInCompositedCSSAnimation); } return updated; }
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp index 23560ae..b2b42cd 100644 --- a/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp +++ b/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp
@@ -45,7 +45,7 @@ if (element) { UseCounter::Count( element->GetDocument(), - UseCounter::kAnimationConstructorKeyframeListEffectObjectTiming); + WebFeature::kAnimationConstructorKeyframeListEffectObjectTiming); } Timing timing; Document* document = element ? &element->GetDocument() : nullptr; @@ -66,7 +66,7 @@ if (element) { UseCounter::Count( element->GetDocument(), - UseCounter::kAnimationConstructorKeyframeListEffectNoTiming); + WebFeature::kAnimationConstructorKeyframeListEffectNoTiming); } return Create(element, EffectInput::Convert(element, effect_input, execution_context,
diff --git a/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp b/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp index 05800646..e34b3c4 100644 --- a/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp +++ b/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp
@@ -184,7 +184,7 @@ StringKeyframeEffectModel::Create(keyframes, &keyframes[0]->Easing()); if (animation_index > 0 && model->HasSyntheticKeyframes()) { UseCounter::Count(element_for_scoping->GetDocument(), - UseCounter::kCSSAnimationsStackedNeutralKeyframe); + WebFeature::kCSSAnimationsStackedNeutralKeyframe); } return model; }
diff --git a/third_party/WebKit/Source/core/css/CSSFontSelector.cpp b/third_party/WebKit/Source/core/css/CSSFontSelector.cpp index 4ac4e17..152ef01b 100644 --- a/third_party/WebKit/Source/core/css/CSSFontSelector.cpp +++ b/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
@@ -176,7 +176,7 @@ void CSSFontSelector::ReportNotDefGlyph() const { DCHECK(document_); - UseCounter::Count(document_, UseCounter::kFontShapingNotDefGlyphObserved); + UseCounter::Count(document_, WebFeature::kFontShapingNotDefGlyphObserved); } DEFINE_TRACE(CSSFontSelector) {
diff --git a/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp b/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp index 77cc53b..0f5ea96 100644 --- a/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp +++ b/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
@@ -178,7 +178,7 @@ CSSStyleSheet::SingleOwnerDocument(parentStyleSheet()); if (parent_document) { UseCounter::Count(*parent_document, - UseCounter::kCSSKeyframesRuleAnonymousIndexedGetter); + WebFeature::kCSSKeyframesRuleAnonymousIndexedGetter); } return Item(index); }
diff --git a/third_party/WebKit/Source/core/css/CSSMatrix.cpp b/third_party/WebKit/Source/core/css/CSSMatrix.cpp index 227272c..c123e4b 100644 --- a/third_party/WebKit/Source/core/css/CSSMatrix.cpp +++ b/third_party/WebKit/Source/core/css/CSSMatrix.cpp
@@ -44,10 +44,10 @@ CSSMatrix* CSSMatrix::Create(ExecutionContext* execution_context, const String& s, ExceptionState& exception_state) { - UseCounter::Count(execution_context, UseCounter::kWebKitCSSMatrix); + UseCounter::Count(execution_context, WebFeature::kWebKitCSSMatrix); if (!s.IsEmpty()) { UseCounter::Count(execution_context, - UseCounter::kWebkitCSSMatrixConstructFromString); + WebFeature::kWebkitCSSMatrixConstructFromString); } return new CSSMatrix(s, exception_state); }
diff --git a/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp b/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp index a7ad425..da74bde 100644 --- a/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp +++ b/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp
@@ -163,8 +163,7 @@ case CSSSyntaxType::kInteger: return ConsumeInteger(range); case CSSSyntaxType::kAngle: - return ConsumeAngle(range, *context, - WTF::Optional<UseCounter::Feature>()); + return ConsumeAngle(range, *context, WTF::Optional<WebFeature>()); case CSSSyntaxType::kTime: return ConsumeTime(range, ValueRange::kValueRangeAll); case CSSSyntaxType::kResolution:
diff --git a/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp b/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp index 62b2b59..625c78bc 100644 --- a/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp +++ b/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp
@@ -370,7 +370,7 @@ MediaFeaturePrefix op, const MediaValues& media_values) { UseCounter::Count(media_values.GetDocument(), - UseCounter::kPrefixedDevicePixelRatioMediaFeature); + WebFeature::kPrefixedDevicePixelRatioMediaFeature); return (!value.IsValid() || value.unit == CSSPrimitiveValue::UnitType::kNumber) && @@ -534,7 +534,7 @@ MediaFeaturePrefix, const MediaValues& media_values) { UseCounter::Count(media_values.GetDocument(), - UseCounter::kPrefixedMinDevicePixelRatioMediaFeature); + WebFeature::kPrefixedMinDevicePixelRatioMediaFeature); return DevicePixelRatioMediaFeatureEval(value, kMinPrefix, media_values); } @@ -544,7 +544,7 @@ MediaFeaturePrefix, const MediaValues& media_values) { UseCounter::Count(media_values.GetDocument(), - UseCounter::kPrefixedMaxDevicePixelRatioMediaFeature); + WebFeature::kPrefixedMaxDevicePixelRatioMediaFeature); return DevicePixelRatioMediaFeatureEval(value, kMaxPrefix, media_values); } @@ -613,7 +613,7 @@ MediaFeaturePrefix op, const MediaValues& media_values) { UseCounter::Count(media_values.GetDocument(), - UseCounter::kPrefixedTransform3dMediaFeature); + WebFeature::kPrefixedTransform3dMediaFeature); bool return_value_if_no_parameter; int have3d_rendering;
diff --git a/third_party/WebKit/Source/core/css/SelectorChecker.cpp b/third_party/WebKit/Source/core/css/SelectorChecker.cpp index f533d5e..8548b6a 100644 --- a/third_party/WebKit/Source/core/css/SelectorChecker.cpp +++ b/third_party/WebKit/Source/core/css/SelectorChecker.cpp
@@ -419,7 +419,7 @@ if (!is_ua_rule_ && mode_ != kQueryingRules && context.selector->GetPseudoType() == CSSSelector::kPseudoShadow) { Deprecation::CountDeprecation(context.element->GetDocument(), - UseCounter::kCSSSelectorPseudoShadow); + WebFeature::kCSSSelectorPseudoShadow); } // If we're in the same tree-scope as the scoping element, then following // a shadow descendant combinator would escape that and thus the scope. @@ -438,7 +438,7 @@ case CSSSelector::kShadowDeep: { if (!is_ua_rule_ && mode_ != kQueryingRules) { Deprecation::CountDeprecation(context.element->GetDocument(), - UseCounter::kCSSDeepCombinator); + WebFeature::kCSSDeepCombinator); } if (ShadowRoot* root = context.element->ContainingShadowRoot()) { if (root->GetType() == ShadowRootType::kUserAgent) @@ -454,7 +454,7 @@ kSelectorMatches) { if (context.element->IsInShadowTree()) { UseCounter::Count(context.element->GetDocument(), - UseCounter::kCSSDeepCombinatorAndShadow); + WebFeature::kCSSDeepCombinatorAndShadow); } return kSelectorMatches; } @@ -469,7 +469,7 @@ MatchStatus match = MatchSelector(next_context, result); if (match == kSelectorMatches && context.element->IsInShadowTree()) { UseCounter::Count(context.element->GetDocument(), - UseCounter::kCSSDeepCombinatorAndShadow); + WebFeature::kCSSDeepCombinatorAndShadow); } if (match == kSelectorMatches || match == kSelectorFailsCompletely) return match; @@ -482,7 +482,7 @@ case CSSSelector::kShadowPiercingDescendant: { DCHECK_EQ(mode_, kQueryingRules); UseCounter::Count(context.element->GetDocument(), - UseCounter::kCSSShadowPiercingDescendantCombinator); + WebFeature::kCSSShadowPiercingDescendantCombinator); // TODO(kochi): parentOrOpenShadowHostElement() is necessary because // SelectorQuery can pass V0 shadow roots. All closed shadow roots are // already filtered out, thus once V0 is removed this logic can use @@ -657,7 +657,7 @@ AttributeValueMatches(attribute_item, match, selector_value, kTextCaseASCIIInsensitive)) { UseCounter::Count(element.GetDocument(), - UseCounter::kCaseInsensitiveAttrSelectorMatch); + WebFeature::kCaseInsensitiveAttrSelectorMatch); return true; } if (selector_attr.NamespaceURI() != g_star_atom)
diff --git a/third_party/WebKit/Source/core/css/StyleSheetList.cpp b/third_party/WebKit/Source/core/css/StyleSheetList.cpp index a204fdeb..b1ed63c3 100644 --- a/third_party/WebKit/Source/core/css/StyleSheetList.cpp +++ b/third_party/WebKit/Source/core/css/StyleSheetList.cpp
@@ -63,7 +63,7 @@ CSSStyleSheet* StyleSheetList::AnonymousNamedGetter(const AtomicString& name) { if (GetDocument()) { UseCounter::Count(*GetDocument(), - UseCounter::kStyleSheetListAnonymousNamedGetter); + WebFeature::kStyleSheetListAnonymousNamedGetter); } HTMLStyleElement* item = GetNamedItem(name); if (!item)
diff --git a/third_party/WebKit/Source/core/css/parser/CSSAtRuleID.cpp b/third_party/WebKit/Source/core/css/parser/CSSAtRuleID.cpp index 4e9575c..d7b1963b 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSAtRuleID.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSAtRuleID.cpp
@@ -36,43 +36,43 @@ } void CountAtRule(const CSSParserContext* context, CSSAtRuleID rule_id) { - UseCounter::Feature feature; + WebFeature feature; switch (rule_id) { case kCSSAtRuleCharset: - feature = UseCounter::kCSSAtRuleCharset; + feature = WebFeature::kCSSAtRuleCharset; break; case kCSSAtRuleFontFace: - feature = UseCounter::kCSSAtRuleFontFace; + feature = WebFeature::kCSSAtRuleFontFace; break; case kCSSAtRuleImport: - feature = UseCounter::kCSSAtRuleImport; + feature = WebFeature::kCSSAtRuleImport; break; case kCSSAtRuleKeyframes: - feature = UseCounter::kCSSAtRuleKeyframes; + feature = WebFeature::kCSSAtRuleKeyframes; break; case kCSSAtRuleMedia: - feature = UseCounter::kCSSAtRuleMedia; + feature = WebFeature::kCSSAtRuleMedia; break; case kCSSAtRuleNamespace: - feature = UseCounter::kCSSAtRuleNamespace; + feature = WebFeature::kCSSAtRuleNamespace; break; case kCSSAtRulePage: - feature = UseCounter::kCSSAtRulePage; + feature = WebFeature::kCSSAtRulePage; break; case kCSSAtRuleSupports: - feature = UseCounter::kCSSAtRuleSupports; + feature = WebFeature::kCSSAtRuleSupports; break; case kCSSAtRuleViewport: - feature = UseCounter::kCSSAtRuleViewport; + feature = WebFeature::kCSSAtRuleViewport; break; case kCSSAtRuleWebkitKeyframes: - feature = UseCounter::kCSSAtRuleWebkitKeyframes; + feature = WebFeature::kCSSAtRuleWebkitKeyframes; break; case kCSSAtRuleApply: - feature = UseCounter::kCSSAtRuleApply; + feature = WebFeature::kCSSAtRuleApply; break; case kCSSAtRuleInvalid:
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserContext.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserContext.cpp index 5d36453..fe11bce 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserContext.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserContext.cpp
@@ -165,12 +165,12 @@ return KURL(BaseURL(), url, Charset()); } -void CSSParserContext::Count(UseCounter::Feature feature) const { +void CSSParserContext::Count(WebFeature feature) const { if (IsUseCounterRecordingEnabled()) UseCounter::Count(*document_, feature); } -void CSSParserContext::CountDeprecation(UseCounter::Feature feature) const { +void CSSParserContext::CountDeprecation(WebFeature feature) const { if (IsUseCounterRecordingEnabled()) Deprecation::CountDeprecation(*document_, feature); }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserContext.h b/third_party/WebKit/Source/core/css/parser/CSSParserContext.h index 2e3b2ae..d096d52 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserContext.h +++ b/third_party/WebKit/Source/core/css/parser/CSSParserContext.h
@@ -82,9 +82,9 @@ KURL CompleteURL(const String& url) const; - void Count(UseCounter::Feature) const; + void Count(WebFeature) const; void Count(CSSParserMode, CSSPropertyID) const; - void CountDeprecation(UseCounter::Feature) const; + void CountDeprecation(WebFeature) const; bool IsUseCounterRecordingEnabled() const { return document_; } bool IsDocumentHandleEqual(const Document* other) const;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp index c2f9d0d..73ac4128 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp
@@ -705,7 +705,7 @@ if (name_token.GetType() == kIdentToken) { name = name_token.Value().ToString(); } else if (name_token.GetType() == kStringToken && webkit_prefixed) { - context_->Count(UseCounter::kQuotedKeyframesRule); + context_->Count(WebFeature::kQuotedKeyframesRule); name = name_token.Value().ToString(); } else { return nullptr; // Parse error; expected ident token in @keyframes header
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index 506fb5b..fa4a3331 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -607,7 +607,7 @@ parsed_value = ParseSingleShadow(args, context->Mode(), false); } else { if (args.AtEnd()) { - context->Count(UseCounter::kCSSFilterFunctionNoArguments); + context->Count(WebFeature::kCSSFilterFunctionNoArguments); return filter_value; } if (filter_type == CSSValueBrightness) { @@ -617,7 +617,7 @@ parsed_value = ConsumeNumber(args, kValueRangeAll); } else if (filter_type == CSSValueHueRotate) { parsed_value = - ConsumeAngle(args, *context, UseCounter::kUnitlessZeroAngleFilter); + ConsumeAngle(args, *context, WebFeature::kUnitlessZeroAngleFilter); } else if (filter_type == CSSValueBlur) { parsed_value = ConsumeLength(args, kHTMLStandardMode, kValueRangeNonNegative); @@ -687,14 +687,13 @@ static CSSValue* ConsumeOffsetRotate(CSSParserTokenRange& range, const CSSParserContext& context) { - CSSValue* angle = - ConsumeAngle(range, context, Optional<UseCounter::Feature>()); + CSSValue* angle = ConsumeAngle(range, context, Optional<WebFeature>()); CSSValue* keyword = ConsumeIdent<CSSValueAuto, CSSValueReverse>(range); if (!angle && !keyword) return nullptr; if (!angle) { - angle = ConsumeAngle(range, context, Optional<UseCounter::Feature>()); + angle = ConsumeAngle(range, context, Optional<WebFeature>()); } CSSValueList* list = CSSValueList::CreateSpaceSeparated(); @@ -744,7 +743,7 @@ double perspective; if (!ConsumeNumberRaw(range, perspective)) return nullptr; - context->Count(UseCounter::kUnitlessPerspectiveInPerspectiveProperty); + context->Count(WebFeature::kUnitlessPerspectiveInPerspectiveProperty); parsed_value = CSSPrimitiveValue::Create( perspective, CSSPrimitiveValue::UnitType::kPixels); } @@ -1525,31 +1524,31 @@ return; switch (property) { case CSSPropertyWebkitAppearance: { - UseCounter::Feature feature; + WebFeature feature; if (value_id == CSSValueNone) { - feature = UseCounter::kCSSValueAppearanceNone; + feature = WebFeature::kCSSValueAppearanceNone; } else { - feature = UseCounter::kCSSValueAppearanceNotNone; + feature = WebFeature::kCSSValueAppearanceNotNone; if (value_id == CSSValueButton) - feature = UseCounter::kCSSValueAppearanceButton; + feature = WebFeature::kCSSValueAppearanceButton; else if (value_id == CSSValueCaret) - feature = UseCounter::kCSSValueAppearanceCaret; + feature = WebFeature::kCSSValueAppearanceCaret; else if (value_id == CSSValueCheckbox) - feature = UseCounter::kCSSValueAppearanceCheckbox; + feature = WebFeature::kCSSValueAppearanceCheckbox; else if (value_id == CSSValueMenulist) - feature = UseCounter::kCSSValueAppearanceMenulist; + feature = WebFeature::kCSSValueAppearanceMenulist; else if (value_id == CSSValueMenulistButton) - feature = UseCounter::kCSSValueAppearanceMenulistButton; + feature = WebFeature::kCSSValueAppearanceMenulistButton; else if (value_id == CSSValueListbox) - feature = UseCounter::kCSSValueAppearanceListbox; + feature = WebFeature::kCSSValueAppearanceListbox; else if (value_id == CSSValueRadio) - feature = UseCounter::kCSSValueAppearanceRadio; + feature = WebFeature::kCSSValueAppearanceRadio; else if (value_id == CSSValueSearchfield) - feature = UseCounter::kCSSValueAppearanceSearchField; + feature = WebFeature::kCSSValueAppearanceSearchField; else if (value_id == CSSValueTextfield) - feature = UseCounter::kCSSValueAppearanceTextField; + feature = WebFeature::kCSSValueAppearanceTextField; else - feature = UseCounter::kCSSValueAppearanceOthers; + feature = WebFeature::kCSSValueAppearanceOthers; } context->Count(feature); break; @@ -1558,13 +1557,13 @@ case CSSPropertyWebkitUserModify: { switch (value_id) { case CSSValueReadOnly: - context->Count(UseCounter::kCSSValueUserModifyReadOnly); + context->Count(WebFeature::kCSSValueUserModifyReadOnly); break; case CSSValueReadWrite: - context->Count(UseCounter::kCSSValueUserModifyReadWrite); + context->Count(WebFeature::kCSSValueUserModifyReadWrite); break; case CSSValueReadWritePlaintextOnly: - context->Count(UseCounter::kCSSValueUserModifyReadWritePlaintextOnly); + context->Count(WebFeature::kCSSValueUserModifyReadWritePlaintextOnly); break; default: NOTREACHED(); @@ -1628,13 +1627,13 @@ case CSSPropertyScrollSnapDestination: // TODO(crbug.com/724912): Retire scroll-snap-destination return ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - Optional<UseCounter::Feature>()); + Optional<WebFeature>()); case CSSPropertyObjectPosition: return ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionObjectPosition); + WebFeature::kThreeValuedPositionObjectPosition); case CSSPropertyPerspectiveOrigin: return ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionPerspectiveOrigin); + WebFeature::kThreeValuedPositionPerspectiveOrigin); case CSSPropertyWebkitHyphenateCharacter: case CSSPropertyWebkitLocale: return ConsumeLocale(range_); @@ -2603,7 +2602,7 @@ CSSValue* position_x = nullptr; CSSValue* position_y = nullptr; if (!ConsumePosition(range, *context, unitless, - UseCounter::kThreeValuedPositionBackground, position_x, + WebFeature::kThreeValuedPositionBackground, position_x, position_y)) return false; AddBackgroundValue(result_x, position_x); @@ -2685,7 +2684,7 @@ } else if (property == CSSPropertyBackgroundPositionX || property == CSSPropertyWebkitMaskPositionX) { if (!ConsumePosition(range_, *context_, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionBackground, + WebFeature::kThreeValuedPositionBackground, value, value_y)) continue; } else if (property == CSSPropertyBackgroundSize ||
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp index 0bf3411..524e343 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
@@ -332,10 +332,9 @@ return ConsumeLengthOrPercent(range, context.Mode(), value_range, unitless); } -CSSPrimitiveValue* ConsumeAngle( - CSSParserTokenRange& range, - const CSSParserContext& context, - WTF::Optional<UseCounter::Feature> unitlessZeroFeature) { +CSSPrimitiveValue* ConsumeAngle(CSSParserTokenRange& range, + const CSSParserContext& context, + WTF::Optional<WebFeature> unitlessZeroFeature) { const CSSParserToken& token = range.Peek(); if (token.GetType() == kDimensionToken) { switch (token.GetUnitType()) { @@ -733,7 +732,7 @@ bool ConsumePosition(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless, - WTF::Optional<UseCounter::Feature> threeValuePosition, + WTF::Optional<WebFeature> threeValuePosition, CSSValue*& result_x, CSSValue*& result_y) { bool horizontal_edge = false; @@ -804,11 +803,10 @@ return true; } -CSSValuePair* ConsumePosition( - CSSParserTokenRange& range, - const CSSParserContext& context, - UnitlessQuirk unitless, - WTF::Optional<UseCounter::Feature> threeValuePosition) { +CSSValuePair* ConsumePosition(CSSParserTokenRange& range, + const CSSParserContext& context, + UnitlessQuirk unitless, + WTF::Optional<WebFeature> threeValuePosition) { CSSValue* result_x = nullptr; CSSValue* result_y = nullptr; if (ConsumePosition(range, context, unitless, threeValuePosition, result_x, @@ -979,7 +977,7 @@ UnitlessQuirk) { const CSSParserToken& token = range.Peek(); if (token.GetType() == kDimensionToken || token.GetType() == kNumberToken) { - return ConsumeAngle(range, context, WTF::Optional<UseCounter::Feature>()); + return ConsumeAngle(range, context, WTF::Optional<WebFeature>()); } if (token.GetType() == kPercentageToken) return ConsumePercent(range, value_range); @@ -1155,7 +1153,7 @@ if (args.Peek().Id() == CSSValueAt) { args.ConsumeIncludingWhitespace(); ConsumePosition(args, context, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionGradient, center_x, + WebFeature::kThreeValuedPositionGradient, center_x, center_y); if (!(center_x && center_y)) return nullptr; @@ -1182,7 +1180,7 @@ CSSGradientType gradient_type) { bool expect_comma = true; const CSSPrimitiveValue* angle = - ConsumeAngle(args, context, UseCounter::kUnitlessZeroAngleGradient); + ConsumeAngle(args, context, WebFeature::kUnitlessZeroAngleGradient); const CSSIdentifierValue* end_x = nullptr; const CSSIdentifierValue* end_y = nullptr; if (!angle) { @@ -1222,8 +1220,8 @@ const CSSPrimitiveValue* from_angle = nullptr; if (ConsumeIdent<CSSValueFrom>(args)) { - if (!(from_angle = ConsumeAngle(args, context, - WTF::Optional<UseCounter::Feature>()))) + if (!(from_angle = + ConsumeAngle(args, context, WTF::Optional<WebFeature>()))) return nullptr; } @@ -1231,7 +1229,7 @@ CSSValue* center_y = nullptr; if (ConsumeIdent<CSSValueAt>(args)) { if (!ConsumePosition(args, context, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionGradient, center_x, + WebFeature::kThreeValuedPositionGradient, center_x, center_y)) return nullptr; } @@ -1337,11 +1335,11 @@ } else if (id == CSSValueRepeatingRadialGradient) { result = ConsumeRadialGradient(args, *context, kRepeating); } else if (id == CSSValueWebkitLinearGradient) { - context->Count(UseCounter::kDeprecatedWebKitLinearGradient); + context->Count(WebFeature::kDeprecatedWebKitLinearGradient); result = ConsumeLinearGradient(args, *context, kNonRepeating, kCSSPrefixedLinearGradient); } else if (id == CSSValueWebkitRepeatingLinearGradient) { - context->Count(UseCounter::kDeprecatedWebKitRepeatingLinearGradient); + context->Count(WebFeature::kDeprecatedWebKitRepeatingLinearGradient); result = ConsumeLinearGradient(args, *context, kRepeating, kCSSPrefixedLinearGradient); } else if (id == CSSValueRepeatingLinearGradient) { @@ -1351,13 +1349,13 @@ result = ConsumeLinearGradient(args, *context, kNonRepeating, kCSSLinearGradient); } else if (id == CSSValueWebkitGradient) { - context->Count(UseCounter::kDeprecatedWebKitGradient); + context->Count(WebFeature::kDeprecatedWebKitGradient); result = ConsumeDeprecatedGradient(args, context->Mode()); } else if (id == CSSValueWebkitRadialGradient) { - context->Count(UseCounter::kDeprecatedWebKitRadialGradient); + context->Count(WebFeature::kDeprecatedWebKitRadialGradient); result = ConsumeDeprecatedRadialGradient(args, *context, kNonRepeating); } else if (id == CSSValueWebkitRepeatingRadialGradient) { - context->Count(UseCounter::kDeprecatedWebKitRepeatingRadialGradient); + context->Count(WebFeature::kDeprecatedWebKitRepeatingRadialGradient); result = ConsumeDeprecatedRadialGradient(args, *context, kRepeating); } else if (id == CSSValueConicGradient) { result = ConsumeConicGradient(args, *context, kNonRepeating);
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h index 3d42a0b..fe5e17ad 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h
@@ -57,10 +57,9 @@ ValueRange, UnitlessQuirk = UnitlessQuirk::kForbid); -CSSPrimitiveValue* ConsumeAngle( - CSSParserTokenRange&, - const CSSParserContext&, - WTF::Optional<UseCounter::Feature> unitlessZeroFeature); +CSSPrimitiveValue* ConsumeAngle(CSSParserTokenRange&, + const CSSParserContext&, + WTF::Optional<WebFeature> unitlessZeroFeature); CSSPrimitiveValue* ConsumeTime(CSSParserTokenRange&, ValueRange); CSSPrimitiveValue* ConsumeResolution(CSSParserTokenRange&); @@ -84,15 +83,14 @@ CSSValue* ConsumeLineWidth(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk); -CSSValuePair* ConsumePosition( - CSSParserTokenRange&, - const CSSParserContext&, - UnitlessQuirk, - WTF::Optional<UseCounter::Feature> threeValuePosition); +CSSValuePair* ConsumePosition(CSSParserTokenRange&, + const CSSParserContext&, + UnitlessQuirk, + WTF::Optional<WebFeature> threeValuePosition); bool ConsumePosition(CSSParserTokenRange&, const CSSParserContext&, UnitlessQuirk, - WTF::Optional<UseCounter::Feature> threeValuePosition, + WTF::Optional<WebFeature> threeValuePosition, CSSValue*& result_x, CSSValue*& result_y); bool ConsumeOneOrTwoValuedPosition(CSSParserTokenRange&,
diff --git a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp index a198872..1896a476 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSSelectorParser.cpp
@@ -835,44 +835,44 @@ selector = CSSSelectorList::Next(*selector)) { for (const CSSSelector* current = selector; current; current = current->TagHistory()) { - UseCounter::Feature feature = UseCounter::kNumberOfFeatures; + WebFeature feature = WebFeature::kNumberOfFeatures; switch (current->GetPseudoType()) { case CSSSelector::kPseudoAny: - feature = UseCounter::kCSSSelectorPseudoAny; + feature = WebFeature::kCSSSelectorPseudoAny; break; case CSSSelector::kPseudoUnresolved: - feature = UseCounter::kCSSSelectorPseudoUnresolved; + feature = WebFeature::kCSSSelectorPseudoUnresolved; break; case CSSSelector::kPseudoDefined: - feature = UseCounter::kCSSSelectorPseudoDefined; + feature = WebFeature::kCSSSelectorPseudoDefined; break; case CSSSelector::kPseudoSlotted: - feature = UseCounter::kCSSSelectorPseudoSlotted; + feature = WebFeature::kCSSSelectorPseudoSlotted; break; case CSSSelector::kPseudoContent: - feature = UseCounter::kCSSSelectorPseudoContent; + feature = WebFeature::kCSSSelectorPseudoContent; break; case CSSSelector::kPseudoHost: - feature = UseCounter::kCSSSelectorPseudoHost; + feature = WebFeature::kCSSSelectorPseudoHost; break; case CSSSelector::kPseudoHostContext: - feature = UseCounter::kCSSSelectorPseudoHostContext; + feature = WebFeature::kCSSSelectorPseudoHostContext; break; case CSSSelector::kPseudoFullScreenAncestor: - feature = UseCounter::kCSSSelectorPseudoFullScreenAncestor; + feature = WebFeature::kCSSSelectorPseudoFullScreenAncestor; break; case CSSSelector::kPseudoFullScreen: - feature = UseCounter::kCSSSelectorPseudoFullScreen; + feature = WebFeature::kCSSSelectorPseudoFullScreen; break; case CSSSelector::kPseudoListBox: if (context_->Mode() != kUASheetMode) - feature = UseCounter::kCSSSelectorInternalPseudoListBox; + feature = WebFeature::kCSSSelectorInternalPseudoListBox; break; case CSSSelector::kPseudoWebKitCustomElement: if (context_->Mode() != kUASheetMode) { if (current->Value() == "-internal-media-controls-overlay-cast-button") { - feature = UseCounter:: + feature = WebFeature:: kCSSSelectorInternalMediaControlsOverlayCastButton; } } @@ -880,21 +880,21 @@ case CSSSelector::kPseudoSpatialNavigationFocus: if (context_->Mode() != kUASheetMode) { feature = - UseCounter::kCSSSelectorInternalPseudoSpatialNavigationFocus; + WebFeature::kCSSSelectorInternalPseudoSpatialNavigationFocus; } break; case CSSSelector::kPseudoReadOnly: if (context_->Mode() != kUASheetMode) - feature = UseCounter::kCSSSelectorPseudoReadOnly; + feature = WebFeature::kCSSSelectorPseudoReadOnly; break; case CSSSelector::kPseudoReadWrite: if (context_->Mode() != kUASheetMode) - feature = UseCounter::kCSSSelectorPseudoReadWrite; + feature = WebFeature::kCSSSelectorPseudoReadWrite; break; default: break; } - if (feature != UseCounter::kNumberOfFeatures) { + if (feature != WebFeature::kNumberOfFeatures) { if (!Deprecation::DeprecationMessage(feature).IsEmpty() && style_sheet_->AnyOwnerDocument()) { Deprecation::CountDeprecation(*style_sheet_->AnyOwnerDocument(), @@ -904,7 +904,7 @@ } } if (current->Relation() == CSSSelector::kIndirectAdjacent) - context_->Count(UseCounter::kCSSSelectorIndirectAdjacent); + context_->Count(WebFeature::kCSSSelectorIndirectAdjacent); if (current->SelectorList()) RecordUsageAndDeprecations(*current->SelectorList()); }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPICursor.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPICursor.cpp index 9f01751..7df161d 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPICursor.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPICursor.cpp
@@ -48,9 +48,9 @@ CSSValueID id = range.Peek().Id(); if (!range.AtEnd()) { if (id == CSSValueWebkitZoomIn) - context.Count(UseCounter::kPrefixedCursorZoomIn); + context.Count(WebFeature::kPrefixedCursorZoomIn); else if (id == CSSValueWebkitZoomOut) - context.Count(UseCounter::kPrefixedCursorZoomOut); + context.Count(WebFeature::kPrefixedCursorZoomOut); } CSSValue* cursor_type = nullptr; if (id == CSSValueHand) {
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIImageOrientation.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIImageOrientation.cpp index 7624d16..c87c1ad7 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIImageOrientation.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIImageOrientation.cpp
@@ -21,7 +21,7 @@ return CSSPropertyParserHelpers::ConsumeIdent(range); if (range.Peek().GetType() != kNumberToken) { CSSPrimitiveValue* angle = CSSPropertyParserHelpers::ConsumeAngle( - range, context, WTF::Optional<UseCounter::Feature>()); + range, context, WTF::Optional<WebFeature>()); if (angle && angle->GetDoubleValue() == 0) return angle; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetAnchor.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetAnchor.cpp index bf605632..16b4d72 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetAnchor.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetAnchor.cpp
@@ -22,7 +22,7 @@ if (id == CSSValueAuto) return ConsumeIdent(range); return ConsumePosition(range, context, UnitlessQuirk::kForbid, - Optional<UseCounter::Feature>()); + Optional<WebFeature>()); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPosition.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPosition.cpp index ad45dccf..2b3a2b1 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPosition.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIOffsetPosition.cpp
@@ -22,11 +22,11 @@ if (id == CSSValueAuto) return ConsumeIdent(range); CSSValue* value = ConsumePosition(range, context, UnitlessQuirk::kForbid, - Optional<UseCounter::Feature>()); + Optional<WebFeature>()); // Count when we receive a valid position other than 'auto'. if (value && value->IsValuePair()) - context.Count(UseCounter::kCSSOffsetInEffect); + context.Count(WebFeature::kCSSOffsetInEffect); return value; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIRotate.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIRotate.cpp index 38910196..ad59521a9 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIRotate.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIRotate.cpp
@@ -36,7 +36,7 @@ } CSSValue* rotation = CSSPropertyParserHelpers::ConsumeAngle( - range, context, WTF::Optional<UseCounter::Feature>()); + range, context, WTF::Optional<WebFeature>()); if (!rotation) return nullptr; list->Append(*rotation);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIScrollSnapCoordinate.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIScrollSnapCoordinate.cpp index bc15860..95a03eb3 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIScrollSnapCoordinate.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIScrollSnapCoordinate.cpp
@@ -21,7 +21,7 @@ CSSValueList* positions = CSSValueList::CreateCommaSeparated(); do { CSSValue* position = ConsumePosition(range, context, UnitlessQuirk::kForbid, - Optional<UseCounter::Feature>()); + Optional<WebFeature>()); if (!position) return nullptr; positions->Append(*position);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransform.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransform.cpp index c2bf72f0..69efb48 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransform.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPITransform.cpp
@@ -44,7 +44,7 @@ perspective < 0) { return false; } - context->Count(UseCounter::kUnitlessPerspectiveInTransformProperty); + context->Count(WebFeature::kUnitlessPerspectiveInTransformProperty); parsed_value = CSSPrimitiveValue::Create( perspective, CSSPrimitiveValue::UnitType::kPixels); } @@ -96,14 +96,14 @@ case CSSValueSkewY: case CSSValueSkew: parsed_value = CSSPropertyParserHelpers::ConsumeAngle( - args, *context, UseCounter::kUnitlessZeroAngleTransform); + args, *context, WebFeature::kUnitlessZeroAngleTransform); if (!parsed_value) return nullptr; if (function_id == CSSValueSkew && CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) { transform_value->Append(*parsed_value); parsed_value = CSSPropertyParserHelpers::ConsumeAngle( - args, *context, UseCounter::kUnitlessZeroAngleTransform); + args, *context, WebFeature::kUnitlessZeroAngleTransform); if (!parsed_value) return nullptr; } @@ -168,7 +168,7 @@ return nullptr; } parsed_value = CSSPropertyParserHelpers::ConsumeAngle( - args, *context, UseCounter::kUnitlessZeroAngleTransform); + args, *context, WebFeature::kUnitlessZeroAngleTransform); if (!parsed_value) return nullptr; break;
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIZoom.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIZoom.cpp index 5c8de41b..cfa7e5a2 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIZoom.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIZoom.cpp
@@ -33,7 +33,7 @@ ToCSSPrimitiveValue(zoom)->GetDoubleValue() == 1) || (token.GetType() == kPercentageToken && ToCSSPrimitiveValue(zoom)->GetDoubleValue() == 100))) - context.Count(UseCounter::kCSSZoomNotEqualToOne); + context.Count(WebFeature::kCSSZoomNotEqualToOne); } return zoom; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationNameUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationNameUtils.cpp index 074d4dcf..4cac241 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationNameUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationNameUtils.cpp
@@ -18,7 +18,7 @@ if (allow_quoted_name && range.Peek().GetType() == kStringToken) { // Legacy support for strings in prefixed animations. - context->Count(UseCounter::kQuotedAnimationName); + context->Count(WebFeature::kQuotedAnimationName); const CSSParserToken& token = range.ConsumeIncludingWhitespace(); if (EqualIgnoringASCIICase(token.Value(), "none"))
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyLengthUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyLengthUtils.cpp index 88248843..569bd46d 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyLengthUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyLengthUtils.cpp
@@ -19,16 +19,16 @@ id == CSSValueFitContent) { switch (id) { case CSSValueWebkitMinContent: - context.Count(UseCounter::kCSSValuePrefixedMinContent); + context.Count(WebFeature::kCSSValuePrefixedMinContent); break; case CSSValueWebkitMaxContent: - context.Count(UseCounter::kCSSValuePrefixedMaxContent); + context.Count(WebFeature::kCSSValuePrefixedMaxContent); break; case CSSValueWebkitFillAvailable: - context.Count(UseCounter::kCSSValuePrefixedFillAvailable); + context.Count(WebFeature::kCSSValuePrefixedFillAvailable); break; case CSSValueWebkitFitContent: - context.Count(UseCounter::kCSSValuePrefixedFitContent); + context.Count(WebFeature::kCSSValuePrefixedFitContent); break; default: break;
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp index 373479c..711cf4b1 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyOffsetPathUtils.cpp
@@ -57,7 +57,7 @@ while (!function_args.AtEnd()) { if (!angle) { angle = CSSPropertyParserHelpers::ConsumeAngle( - function_args, context, WTF::Optional<UseCounter::Feature>()); + function_args, context, WTF::Optional<WebFeature>()); if (angle) continue; } @@ -96,7 +96,7 @@ // Count when we receive a valid path other than 'none'. if (value && !value->IsIdentifierValue()) - context.Count(UseCounter::kCSSOffsetInEffect); + context.Count(WebFeature::kCSSOffsetInEffect); return value; }
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyShapeUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyShapeUtils.cpp index 3c3d156..6cd69ac 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyShapeUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyShapeUtils.cpp
@@ -35,7 +35,7 @@ CSSValue* center_x = nullptr; CSSValue* center_y = nullptr; if (!ConsumePosition(args, context, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionBasicShape, center_x, + WebFeature::kThreeValuedPositionBasicShape, center_x, center_y)) return nullptr; shape->SetCenterX(center_x); @@ -59,7 +59,7 @@ CSSValue* center_x = nullptr; CSSValue* center_y = nullptr; if (!ConsumePosition(args, context, UnitlessQuirk::kForbid, - UseCounter::kThreeValuedPositionBasicShape, center_x, + WebFeature::kThreeValuedPositionBasicShape, center_x, center_y)) return nullptr; shape->SetCenterX(center_x);
diff --git a/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp b/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp index 0d1f58d..c603991 100644 --- a/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -76,44 +76,44 @@ const Document& document) { // This variable is always reassigned, but MSVC thinks it might be left // uninitialized. - UseCounter::Feature feature = UseCounter::kNumberOfFeatures; + WebFeature feature = WebFeature::kNumberOfFeatures; switch (operation_type) { case FilterOperation::NONE: case FilterOperation::BOX_REFLECT: NOTREACHED(); return; case FilterOperation::REFERENCE: - feature = UseCounter::kCSSFilterReference; + feature = WebFeature::kCSSFilterReference; break; case FilterOperation::GRAYSCALE: - feature = UseCounter::kCSSFilterGrayscale; + feature = WebFeature::kCSSFilterGrayscale; break; case FilterOperation::SEPIA: - feature = UseCounter::kCSSFilterSepia; + feature = WebFeature::kCSSFilterSepia; break; case FilterOperation::SATURATE: - feature = UseCounter::kCSSFilterSaturate; + feature = WebFeature::kCSSFilterSaturate; break; case FilterOperation::HUE_ROTATE: - feature = UseCounter::kCSSFilterHueRotate; + feature = WebFeature::kCSSFilterHueRotate; break; case FilterOperation::INVERT: - feature = UseCounter::kCSSFilterInvert; + feature = WebFeature::kCSSFilterInvert; break; case FilterOperation::OPACITY: - feature = UseCounter::kCSSFilterOpacity; + feature = WebFeature::kCSSFilterOpacity; break; case FilterOperation::BRIGHTNESS: - feature = UseCounter::kCSSFilterBrightness; + feature = WebFeature::kCSSFilterBrightness; break; case FilterOperation::CONTRAST: - feature = UseCounter::kCSSFilterContrast; + feature = WebFeature::kCSSFilterContrast; break; case FilterOperation::BLUR: - feature = UseCounter::kCSSFilterBlur; + feature = WebFeature::kCSSFilterBlur; break; case FilterOperation::DROP_SHADOW: - feature = UseCounter::kCSSFilterDropShadow; + feature = WebFeature::kCSSFilterDropShadow; break; }; UseCounter::Count(document, feature);
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp b/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp index 3468e468..d561f3f6 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp
@@ -359,11 +359,11 @@ if (style.PaddingBefore().IsPercentOrCalc() || style.PaddingAfter().IsPercentOrCalc()) { UseCounter::Count(document, - UseCounter::kFlexboxPercentagePaddingVertical); + WebFeature::kFlexboxPercentagePaddingVertical); } if (style.MarginBefore().IsPercentOrCalc() || style.MarginAfter().IsPercentOrCalc()) { - UseCounter::Count(document, UseCounter::kFlexboxPercentageMarginVertical); + UseCounter::Count(document, WebFeature::kFlexboxPercentageMarginVertical); } } }
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp index 5dea806fd..2c6c1ef 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -195,7 +195,7 @@ family_name = AtomicString(ToCSSFontFamilyValue(value).Value()); #if OS(MACOSX) if (family_name == FontCache::LegacySystemFontFamily()) { - UseCounter::Count(state.GetDocument(), UseCounter::kBlinkMacSystemFont); + UseCounter::Count(state.GetDocument(), WebFeature::kBlinkMacSystemFont); family_name = FontFamilyNames::system_ui; } #endif
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp index 6bdbd0c..f642b896 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -748,7 +748,7 @@ ToCSSIdentifierValue(*value).GetValueID() == CSSValueBlock) { UseCounter::Count( element->GetDocument(), - UseCounter::kSummaryElementWithDisplayBlockAuthorRule); + WebFeature::kSummaryElementWithDisplayBlockAuthorRule); } } }
diff --git a/third_party/WebKit/Source/core/dom/ClassicScript.cpp b/third_party/WebKit/Source/core/dom/ClassicScript.cpp index a4b726bb..e54792f2 100644 --- a/third_party/WebKit/Source/core/dom/ClassicScript.cpp +++ b/third_party/WebKit/Source/core/dom/ClassicScript.cpp
@@ -31,15 +31,15 @@ !is_text && mime_type.StartsWith("application/", kTextCaseASCIIInsensitive); - UseCounter::Feature feature = + WebFeature feature = is_same_origin - ? (is_text ? UseCounter::kSameOriginTextScript - : is_application ? UseCounter::kSameOriginApplicationScript - : UseCounter::kSameOriginOtherScript) + ? (is_text ? WebFeature::kSameOriginTextScript + : is_application ? WebFeature::kSameOriginApplicationScript + : WebFeature::kSameOriginOtherScript) : (is_text - ? UseCounter::kCrossOriginTextScript - : is_application ? UseCounter::kCrossOriginApplicationScript - : UseCounter::kCrossOriginOtherScript); + ? WebFeature::kCrossOriginTextScript + : is_application ? WebFeature::kCrossOriginApplicationScript + : WebFeature::kCrossOriginOtherScript); UseCounter::Count(frame, feature); } @@ -82,13 +82,13 @@ "' because its MIME type ('" + mime_type + "') is not executable.")); if (mime_type.StartsWith("image/")) - UseCounter::Count(frame, UseCounter::kBlockedSniffingImageToScript); + UseCounter::Count(frame, WebFeature::kBlockedSniffingImageToScript); else if (mime_type.StartsWith("audio/")) - UseCounter::Count(frame, UseCounter::kBlockedSniffingAudioToScript); + UseCounter::Count(frame, WebFeature::kBlockedSniffingAudioToScript); else if (mime_type.StartsWith("video/")) - UseCounter::Count(frame, UseCounter::kBlockedSniffingVideoToScript); + UseCounter::Count(frame, WebFeature::kBlockedSniffingVideoToScript); else if (mime_type == "text/csv") - UseCounter::Count(frame, UseCounter::kBlockedSniffingCSVToScript); + UseCounter::Count(frame, WebFeature::kBlockedSniffingCSVToScript); return false; }
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 71537b4e..9daa4f8 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -418,8 +418,8 @@ // bindings is too slow. UseCounter::Count(document, is_valid_dom_name - ? UseCounter::kElementNameDOMValidHTMLParserInvalid - : UseCounter::kElementNameDOMInvalidHTMLParserValid); + ? WebFeature::kElementNameDOMValidHTMLParserInvalid + : WebFeature::kElementNameDOMInvalidHTMLParserValid); } return is_valid_dom_name; } @@ -784,7 +784,7 @@ if (string_or_options.isString()) { UseCounter::Count(document, - UseCounter::kDocumentCreateElement2ndArgStringHandling); + WebFeature::kDocumentCreateElement2ndArgStringHandling); return string_or_options.getAsString(); } @@ -1104,7 +1104,7 @@ } if (IsHTMLDocument()) { UseCounter::Count(*this, - UseCounter::kHTMLDocumentCreateProcessingInstruction); + WebFeature::kHTMLDocumentCreateProcessingInstruction); } return ProcessingInstruction::Create(*this, target, data); } @@ -1902,7 +1902,7 @@ // might want to try to eliminate some day (eg. for ScrollTopLeftInterop - // see http://crbug.com/157855). if (body_style && !body_style->IsOverflowVisible()) - UseCounter::Count(*this, UseCounter::kBodyScrollsInAdditionToViewport); + UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport); } } @@ -3546,7 +3546,7 @@ } void Document::ProcessBaseElement() { - UseCounter::Count(*this, UseCounter::kBaseElement); + UseCounter::Count(*this, WebFeature::kBaseElement); // Find the first href attribute in a base element and the first target // attribute in a base element. @@ -3567,7 +3567,7 @@ } if (GetContentSecurityPolicy()->IsActive()) { UseCounter::Count(*this, - UseCounter::kContentSecurityPolicyWithBaseElement); + WebFeature::kContentSecurityPolicyWithBaseElement); } } @@ -3582,13 +3582,13 @@ if (!base_element_url.IsEmpty()) { if (base_element_url.ProtocolIsData()) { - UseCounter::Count(*this, UseCounter::kBaseWithDataHref); + UseCounter::Count(*this, WebFeature::kBaseWithDataHref); AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "'data:' URLs may not be used as base URLs for a document.")); } if (!this->GetSecurityOrigin()->CanRequest(base_element_url)) - UseCounter::Count(*this, UseCounter::kBaseWithCrossOriginHref); + UseCounter::Count(*this, WebFeature::kBaseWithCrossOriginHref); } if (base_element_url != base_element_url_ && @@ -3600,9 +3600,9 @@ if (target) { if (target->Contains('\n') || target->Contains('\r')) - UseCounter::Count(*this, UseCounter::kBaseWithNewlinesInTarget); + UseCounter::Count(*this, WebFeature::kBaseWithNewlinesInTarget); if (target->Contains('<')) - UseCounter::Count(*this, UseCounter::kBaseWithOpenBracketInTarget); + UseCounter::Count(*this, WebFeature::kBaseWithOpenBracketInTarget); base_target_ = *target; } else { base_target_ = g_null_atom; @@ -4732,22 +4732,22 @@ void Document::AddListenerTypeIfNeeded(const AtomicString& event_type, EventTarget& event_target) { if (event_type == EventTypeNames::DOMSubtreeModified) { - UseCounter::Count(*this, UseCounter::kDOMSubtreeModifiedEvent); + UseCounter::Count(*this, WebFeature::kDOMSubtreeModifiedEvent); AddMutationEventListenerTypeIfEnabled(kDOMSubtreeModifiedListener); } else if (event_type == EventTypeNames::DOMNodeInserted) { - UseCounter::Count(*this, UseCounter::kDOMNodeInsertedEvent); + UseCounter::Count(*this, WebFeature::kDOMNodeInsertedEvent); AddMutationEventListenerTypeIfEnabled(kDOMNodeInsertedListener); } else if (event_type == EventTypeNames::DOMNodeRemoved) { - UseCounter::Count(*this, UseCounter::kDOMNodeRemovedEvent); + UseCounter::Count(*this, WebFeature::kDOMNodeRemovedEvent); AddMutationEventListenerTypeIfEnabled(kDOMNodeRemovedListener); } else if (event_type == EventTypeNames::DOMNodeRemovedFromDocument) { - UseCounter::Count(*this, UseCounter::kDOMNodeRemovedFromDocumentEvent); + UseCounter::Count(*this, WebFeature::kDOMNodeRemovedFromDocumentEvent); AddMutationEventListenerTypeIfEnabled(kDOMNodeRemovedFromDocumentListener); } else if (event_type == EventTypeNames::DOMNodeInsertedIntoDocument) { - UseCounter::Count(*this, UseCounter::kDOMNodeInsertedIntoDocumentEvent); + UseCounter::Count(*this, WebFeature::kDOMNodeInsertedIntoDocumentEvent); AddMutationEventListenerTypeIfEnabled(kDOMNodeInsertedIntoDocumentListener); } else if (event_type == EventTypeNames::DOMCharacterDataModified) { - UseCounter::Count(*this, UseCounter::kDOMCharacterDataModifiedEvent); + UseCounter::Count(*this, WebFeature::kDOMCharacterDataModifiedEvent); AddMutationEventListenerTypeIfEnabled(kDOMCharacterDataModifiedListener); } else if (event_type == EventTypeNames::webkitAnimationStart || event_type == EventTypeNames::animationstart) { @@ -4899,7 +4899,7 @@ void Document::setDomain(const String& raw_domain, ExceptionState& exception_state) { - UseCounter::Count(*this, UseCounter::kDocumentSetDomain); + UseCounter::Count(*this, WebFeature::kDocumentSetDomain); if (IsSandboxed(kSandboxDocumentDomain)) { exception_state.ThrowSecurityError( @@ -5335,18 +5335,18 @@ continue; // Count usage; perhaps we can lock this to secure contexts. - UseCounter::Feature osd_disposition; + WebFeature osd_disposition; RefPtr<SecurityOrigin> target = SecurityOrigin::Create(link_element->Href()); if (IsSecureContext()) { osd_disposition = target->IsPotentiallyTrustworthy() - ? UseCounter::kOpenSearchSecureOriginSecureTarget - : UseCounter::kOpenSearchSecureOriginInsecureTarget; + ? WebFeature::kOpenSearchSecureOriginSecureTarget + : WebFeature::kOpenSearchSecureOriginInsecureTarget; } else { osd_disposition = target->IsPotentiallyTrustworthy() - ? UseCounter::kOpenSearchInsecureOriginSecureTarget - : UseCounter::kOpenSearchInsecureOriginInsecureTarget; + ? WebFeature::kOpenSearchInsecureOriginSecureTarget + : WebFeature::kOpenSearchInsecureOriginInsecureTarget; } UseCounter::Count(*this, osd_disposition); @@ -5386,7 +5386,7 @@ bool new_value = design_mode_; if (DeprecatedEqualIgnoringCase(value, "on")) { new_value = true; - UseCounter::Count(*this, UseCounter::kDocumentDesignModeEnabeld); + UseCounter::Count(*this, WebFeature::kDocumentDesignModeEnabeld); } else if (DeprecatedEqualIgnoringCase(value, "off")) { new_value = false; } @@ -6302,7 +6302,7 @@ if (radius_x || radius_y || rotation_angle || force) { UseCounter::Count(*this, - UseCounter::kDocumentCreateTouchMoreThanSevenArguments); + WebFeature::kDocumentCreateTouchMoreThanSevenArguments); } // FIXME: It's not clear from the documentation at @@ -6677,11 +6677,11 @@ if (GetSandboxFlags() != kSandboxNone) { UseCounter::Count( *this, is_secure - ? UseCounter::kSecureContextCheckForSandboxedOriginPassed - : UseCounter::kSecureContextCheckForSandboxedOriginFailed); + ? WebFeature::kSecureContextCheckForSandboxedOriginPassed + : WebFeature::kSecureContextCheckForSandboxedOriginFailed); } - UseCounter::Count(*this, is_secure ? UseCounter::kSecureContextCheckPassed - : UseCounter::kSecureContextCheckFailed); + UseCounter::Count(*this, is_secure ? WebFeature::kSecureContextCheckPassed + : WebFeature::kSecureContextCheckFailed); return is_secure; } @@ -6706,7 +6706,7 @@ if (order == ShadowCascadeOrder::kShadowCascadeV0) { may_contain_v0_shadow_ = true; if (shadow_cascade_order_ == ShadowCascadeOrder::kShadowCascadeV1) - UseCounter::Count(*this, UseCounter::kMixedShadowRootV0AndV1); + UseCounter::Count(*this, WebFeature::kMixedShadowRootV0AndV1); } // For V0 -> V1 upgrade, we need style recalculation for the whole document. @@ -6715,7 +6715,7 @@ this->SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create(StyleChangeReason::kShadow)); - UseCounter::Count(*this, UseCounter::kMixedShadowRootV0AndV1); + UseCounter::Count(*this, WebFeature::kMixedShadowRootV0AndV1); } if (order > shadow_cascade_order_)
diff --git a/third_party/WebKit/Source/core/dom/DocumentOrShadowRoot.h b/third_party/WebKit/Source/core/dom/DocumentOrShadowRoot.h index 028eb226..88de3297 100644 --- a/third_party/WebKit/Source/core/dom/DocumentOrShadowRoot.h +++ b/third_party/WebKit/Source/core/dom/DocumentOrShadowRoot.h
@@ -45,7 +45,7 @@ } static Element* pointerLockElement(Document& document) { - UseCounter::Count(document, UseCounter::kDocumentPointerLockElement); + UseCounter::Count(document, WebFeature::kDocumentPointerLockElement); const Element* target = document.PointerLockElement(); if (!target) return nullptr; @@ -55,7 +55,7 @@ // unnecessary. if (target && target->IsInV0ShadowTree()) { UseCounter::Count(document, - UseCounter::kDocumentPointerLockElementInV0Shadow); + WebFeature::kDocumentPointerLockElementInV0Shadow); return const_cast<Element*>(target); } return document.AdjustedElement(*target); @@ -68,7 +68,7 @@ if (!shadow_root.IsV1()) return nullptr; UseCounter::Count(shadow_root.GetDocument(), - UseCounter::kShadowRootPointerLockElement); + WebFeature::kShadowRootPointerLockElement); const Element* target = shadow_root.GetDocument().PointerLockElement(); if (!target) return nullptr;
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp index 694da3a..042d9431 100644 --- a/third_party/WebKit/Source/core/dom/Element.cpp +++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -2310,15 +2310,15 @@ : ShadowRootType::kClosed; if (type == ShadowRootType::kClosed) - UseCounter::Count(GetDocument(), UseCounter::kElementAttachShadowClosed); + UseCounter::Count(GetDocument(), WebFeature::kElementAttachShadowClosed); else if (type == ShadowRootType::kOpen) - UseCounter::Count(GetDocument(), UseCounter::kElementAttachShadowOpen); + UseCounter::Count(GetDocument(), WebFeature::kElementAttachShadowOpen); ShadowRoot* shadow_root = CreateShadowRootInternal(type, exception_state); if (shadow_root_init_dict.hasDelegatesFocus()) { shadow_root->SetDelegatesFocus(shadow_root_init_dict.delegatesFocus()); - UseCounter::Count(GetDocument(), UseCounter::kShadowRootDelegatesFocus); + UseCounter::Count(GetDocument(), WebFeature::kShadowRootDelegatesFocus); } return shadow_root; @@ -2473,7 +2473,7 @@ attr_node->name() != attr_node->name().LowerASCII()) UseCounter::Count( GetDocument(), - UseCounter:: + WebFeature:: kNonHTMLElementSetAttributeNodeFromHTMLDocumentNameNotLowercase); SynchronizeAllAttributes();
diff --git a/third_party/WebKit/Source/core/dom/ElementFullscreen.cpp b/third_party/WebKit/Source/core/dom/ElementFullscreen.cpp index 34842ff..cbf182c 100644 --- a/third_party/WebKit/Source/core/dom/ElementFullscreen.cpp +++ b/third_party/WebKit/Source/core/dom/ElementFullscreen.cpp
@@ -16,7 +16,7 @@ void ElementFullscreen::webkitRequestFullscreen(Element& element) { if (element.IsInShadowTree()) { UseCounter::Count(element.GetDocument(), - UseCounter::kPrefixedElementRequestFullscreenInShadow); + WebFeature::kPrefixedElementRequestFullscreenInShadow); } Fullscreen::RequestFullscreen(element, Fullscreen::RequestType::kPrefixed); }
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp index 5edb42b4..98c91f3 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp +++ b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
@@ -226,9 +226,9 @@ void ExecutionContext::SetReferrerPolicy(ReferrerPolicy referrer_policy) { // When a referrer policy has already been set, the latest value takes // precedence. - UseCounter::Count(this, UseCounter::kSetReferrerPolicy); + UseCounter::Count(this, WebFeature::kSetReferrerPolicy); if (referrer_policy_ != kReferrerPolicyDefault) - UseCounter::Count(this, UseCounter::kResetReferrerPolicy); + UseCounter::Count(this, WebFeature::kResetReferrerPolicy); referrer_policy_ = referrer_policy; }
diff --git a/third_party/WebKit/Source/core/dom/Fullscreen.cpp b/third_party/WebKit/Source/core/dom/Fullscreen.cpp index 209f73cc..65159dc4 100644 --- a/third_party/WebKit/Source/core/dom/Fullscreen.cpp +++ b/third_party/WebKit/Source/core/dom/Fullscreen.cpp
@@ -98,7 +98,7 @@ // The algorithm is triggered by a user generated orientation change. if (ScopedOrientationChangeIndicator::ProcessingOrientationChange()) { UseCounter::Count(document, - UseCounter::kFullscreenAllowedByOrientationChange); + WebFeature::kFullscreenAllowedByOrientationChange); return true; } @@ -278,7 +278,7 @@ // shadow tree, even though it leaks the Shadow DOM. if (element->IsInV0ShadowTree()) { UseCounter::Count(scope.GetDocument(), - UseCounter::kDocumentFullscreenElementInV0Shadow); + WebFeature::kDocumentFullscreenElementInV0Shadow); return element; } } else if (!ToShadowRoot(scope.RootNode()).IsV1()) { @@ -303,7 +303,7 @@ // tree, even though it leaks the Shadow DOM. if (element->IsInV0ShadowTree()) { UseCounter::Count(document, - UseCounter::kDocumentFullscreenElementInV0Shadow); + WebFeature::kDocumentFullscreenElementInV0Shadow); return element; } return document.AdjustedElement(*element); @@ -364,9 +364,9 @@ // fullscreen element. if (!for_cross_process_descendant) { if (document.IsSecureContext()) { - UseCounter::Count(document, UseCounter::kFullscreenSecureOrigin); + UseCounter::Count(document, WebFeature::kFullscreenSecureOrigin); } else { - UseCounter::Count(document, UseCounter::kFullscreenInsecureOrigin); + UseCounter::Count(document, WebFeature::kFullscreenInsecureOrigin); HostsUsingFeatures::CountAnyWorld( document, HostsUsingFeatures::Feature::kFullscreenInsecureHost); } @@ -399,10 +399,10 @@ // are good candidates. See https://github.com/whatwg/fullscreen/pull/91 if (isHTMLDialogElement(element)) { UseCounter::Count(document, - UseCounter::kRequestFullscreenForDialogElement); + WebFeature::kRequestFullscreenForDialogElement); if (element.IsInTopLayer()) { UseCounter::Count( - document, UseCounter::kRequestFullscreenForDialogElementInTopLayer); + document, WebFeature::kRequestFullscreenForDialogElementInTopLayer); } } @@ -484,7 +484,7 @@ // 6. Optionally, perform some animation. if (From(document).pending_fullscreen_element_) { UseCounter::Count(document, - UseCounter::kFullscreenRequestWithPendingElement); + WebFeature::kFullscreenRequestWithPendingElement); } From(document).pending_fullscreen_element_ = &element; document.GetFrame()->GetChromeClient().EnterFullscreen(
diff --git a/third_party/WebKit/Source/core/dom/MessagePort.cpp b/third_party/WebKit/Source/core/dom/MessagePort.cpp index 9f1dad0..fb7e959b 100644 --- a/third_party/WebKit/Source/core/dom/MessagePort.cpp +++ b/third_party/WebKit/Source/core/dom/MessagePort.cpp
@@ -260,7 +260,7 @@ visited.insert(port); } - UseCounter::Count(context, UseCounter::kMessagePortsTransferred); + UseCounter::Count(context, WebFeature::kMessagePortsTransferred); // Passed-in ports passed validity checks, so we can disentangle them. MessagePortChannelArray port_array(ports.size());
diff --git a/third_party/WebKit/Source/core/dom/Node.cpp b/third_party/WebKit/Source/core/dom/Node.cpp index ae77970..1cf63d47 100644 --- a/third_party/WebKit/Source/core/dom/Node.cpp +++ b/third_party/WebKit/Source/core/dom/Node.cpp
@@ -2165,7 +2165,7 @@ if (IsDisabledFormControl(this) && event.IsMouseEvent() && !RuntimeEnabledFeatures::SendMouseEventsDisabledFormControlsEnabled()) { UseCounter::Count(GetDocument(), - UseCounter::kDispatchMouseEventOnDisabledFormControl); + WebFeature::kDispatchMouseEventOnDisabledFormControl); return; }
diff --git a/third_party/WebKit/Source/core/dom/PseudoElement.cpp b/third_party/WebKit/Source/core/dom/PseudoElement.cpp index 913858b..95892525 100644 --- a/third_party/WebKit/Source/core/dom/PseudoElement.cpp +++ b/third_party/WebKit/Source/core/dom/PseudoElement.cpp
@@ -94,7 +94,7 @@ if ((pseudo_id == kPseudoIdBefore || pseudo_id == kPseudoIdAfter) && parent->HasTagName(HTMLNames::inputTag)) { UseCounter::Count(parent->GetDocument(), - UseCounter::kPseudoBeforeAfterForInputElement); + WebFeature::kPseudoBeforeAfterForInputElement); } }
diff --git a/third_party/WebKit/Source/core/dom/SinkDocument.cpp b/third_party/WebKit/Source/core/dom/SinkDocument.cpp index 9fe219a..adb63ec 100644 --- a/third_party/WebKit/Source/core/dom/SinkDocument.cpp +++ b/third_party/WebKit/Source/core/dom/SinkDocument.cpp
@@ -48,9 +48,9 @@ : HTMLDocument(initializer) { SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kSinkDocument); + UseCounter::Count(*this, WebFeature::kSinkDocument); if (!IsInMainFrame()) - UseCounter::Count(*this, UseCounter::kSinkDocumentInFrame); + UseCounter::Count(*this, WebFeature::kSinkDocumentInFrame); } DocumentParser* SinkDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/dom/StyleEngineContext.cpp b/third_party/WebKit/Source/core/dom/StyleEngineContext.cpp index e1fa377..0afa2e2 100644 --- a/third_party/WebKit/Source/core/dom/StyleEngineContext.cpp +++ b/third_party/WebKit/Source/core/dom/StyleEngineContext.cpp
@@ -39,7 +39,7 @@ added_pending_sheet_before_body_ = !document.body(); if (!added_pending_sheet_before_body_) { UseCounter::Count(document, - UseCounter::kPendingStylesheetAddedAfterBodyStarted); + WebFeature::kPendingStylesheetAddedAfterBodyStarted); } } }
diff --git a/third_party/WebKit/Source/core/dom/custom/V0CustomElement.cpp b/third_party/WebKit/Source/core/dom/custom/V0CustomElement.cpp index 778df42a..2958ba2 100644 --- a/third_party/WebKit/Source/core/dom/custom/V0CustomElement.cpp +++ b/third_party/WebKit/Source/core/dom/custom/V0CustomElement.cpp
@@ -112,8 +112,8 @@ UseCounter::Count( element->GetDocument(), definition->Descriptor().IsTypeExtension() - ? UseCounter::kV0CustomElementsCreateTypeExtensionElement - : UseCounter::kV0CustomElementsCreateCustomTagElement); + ? WebFeature::kV0CustomElementsCreateTypeExtensionElement + : WebFeature::kV0CustomElementsCreateCustomTagElement); element->V0SetCustomElementDefinition(definition); V0CustomElementScheduler::ScheduleCallback( definition->Callbacks(), element,
diff --git a/third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistry.cpp b/third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistry.cpp index 4544c34f65..6ece6b0 100644 --- a/third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistry.cpp +++ b/third_party/WebKit/Source/core/dom/custom/V0CustomElementRegistry.cpp
@@ -112,15 +112,15 @@ if (valid_names & V0CustomElement::kEmbedderNames) { UseCounter::Count(document, - UseCounter::kV0CustomElementsRegisterEmbedderElement); + WebFeature::kV0CustomElementsRegisterEmbedderElement); } else if (tag_name.NamespaceURI() == SVGNames::svgNamespaceURI) { UseCounter::Count(document, - UseCounter::kV0CustomElementsRegisterSVGElement); + WebFeature::kV0CustomElementsRegisterSVGElement); } else { UseCounter::Count( document, descriptor.IsTypeExtension() - ? UseCounter::kV0CustomElementsRegisterHTMLTypeExtension - : UseCounter::kV0CustomElementsRegisterHTMLCustomTag); + ? WebFeature::kV0CustomElementsRegisterHTMLTypeExtension + : WebFeature::kV0CustomElementsRegisterHTMLCustomTag); } return definition;
diff --git a/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp b/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp index 2b0a30a1..8508993 100644 --- a/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp +++ b/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp
@@ -63,7 +63,7 @@ if (type == ShadowRootType::V0 && shadow_root_) { DCHECK_EQ(shadow_root_->GetType(), ShadowRootType::V0); Deprecation::CountDeprecation(shadow_host.GetDocument(), - UseCounter::kElementCreateShadowRootMultiple); + WebFeature::kElementCreateShadowRootMultiple); } if (shadow_root_) {
diff --git a/third_party/WebKit/Source/core/editing/DOMSelection.cpp b/third_party/WebKit/Source/core/editing/DOMSelection.cpp index 180773f..8b87be9 100644 --- a/third_party/WebKit/Source/core/editing/DOMSelection.cpp +++ b/third_party/WebKit/Source/core/editing/DOMSelection.cpp
@@ -88,7 +88,7 @@ frame_selection.DidSetSelectionDeprecated(); if (GetFrame() && GetFrame()->GetDocument() && focused_element != GetFrame()->GetDocument()->FocusedElement()) - UseCounter::Count(GetFrame(), UseCounter::kSelectionFuncionsChangeFocus); + UseCounter::Count(GetFrame(), WebFeature::kSelectionFuncionsChangeFocus); } const VisibleSelection& DOMSelection::GetVisibleSelection() const { @@ -241,7 +241,7 @@ // 1. If node is null, this method must behave identically as // removeAllRanges() and abort these steps. if (!node) { - UseCounter::Count(GetFrame(), UseCounter::kSelectionCollapseNull); + UseCounter::Count(GetFrame(), WebFeature::kSelectionCollapseNull); GetFrame()->Selection().Clear(); return; } @@ -364,12 +364,12 @@ // TODO(editing-dev): Behavior on where base or extent is null is still // under discussion: https://github.com/w3c/selection-api/issues/72 if (!base_node) { - UseCounter::Count(GetFrame(), UseCounter::kSelectionSetBaseAndExtentNull); + UseCounter::Count(GetFrame(), WebFeature::kSelectionSetBaseAndExtentNull); GetFrame()->Selection().Clear(); return; } if (!extent_node) { - UseCounter::Count(GetFrame(), UseCounter::kSelectionSetBaseAndExtentNull); + UseCounter::Count(GetFrame(), WebFeature::kSelectionSetBaseAndExtentNull); extent_offset = 0; } @@ -464,7 +464,7 @@ GetFrame()->Selection().Modify(alter, direction, granularity); if (GetFrame() && GetFrame()->GetDocument() && focused_element != GetFrame()->GetDocument()->FocusedElement()) - UseCounter::Count(GetFrame(), UseCounter::kSelectionFuncionsChangeFocus); + UseCounter::Count(GetFrame(), WebFeature::kSelectionFuncionsChangeFocus); } // https://www.w3.org/TR/selection-api/#dom-selection-extend @@ -667,7 +667,7 @@ // warning message for a while, and continue to collect the usage data. // <https://code.google.com/p/chromium/issues/detail?id=353069>. Deprecation::CountDeprecation(GetFrame(), - UseCounter::kSelectionAddRangeIntersect); + WebFeature::kSelectionAddRangeIntersect); } // https://www.w3.org/TR/selection-api/#dom-selection-deletefromdocument
diff --git a/third_party/WebKit/Source/core/editing/Editor.cpp b/third_party/WebKit/Source/core/editing/Editor.cpp index 23432fb..e31a15b 100644 --- a/third_party/WebKit/Source/core/editing/Editor.cpp +++ b/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -1289,10 +1289,10 @@ static void CountEditingEvent(ExecutionContext* execution_context, const Event* event, - UseCounter::Feature feature_on_input, - UseCounter::Feature feature_on_text_area, - UseCounter::Feature feature_on_content_editable, - UseCounter::Feature feature_on_non_node) { + WebFeature feature_on_input, + WebFeature feature_on_text_area, + WebFeature feature_on_content_editable, + WebFeature feature_on_non_node) { EventTarget* event_target = event->target(); Node* node = event_target->ToNode(); if (!node) { @@ -1331,29 +1331,29 @@ if (event->type() == EventTypeNames::textInput) { CountEditingEvent(execution_context, event, - UseCounter::kTextInputEventOnInput, - UseCounter::kTextInputEventOnTextArea, - UseCounter::kTextInputEventOnContentEditable, - UseCounter::kTextInputEventOnNotNode); + WebFeature::kTextInputEventOnInput, + WebFeature::kTextInputEventOnTextArea, + WebFeature::kTextInputEventOnContentEditable, + WebFeature::kTextInputEventOnNotNode); return; } if (event->type() == EventTypeNames::webkitBeforeTextInserted) { CountEditingEvent(execution_context, event, - UseCounter::kWebkitBeforeTextInsertedOnInput, - UseCounter::kWebkitBeforeTextInsertedOnTextArea, - UseCounter::kWebkitBeforeTextInsertedOnContentEditable, - UseCounter::kWebkitBeforeTextInsertedOnNotNode); + WebFeature::kWebkitBeforeTextInsertedOnInput, + WebFeature::kWebkitBeforeTextInsertedOnTextArea, + WebFeature::kWebkitBeforeTextInsertedOnContentEditable, + WebFeature::kWebkitBeforeTextInsertedOnNotNode); return; } if (event->type() == EventTypeNames::webkitEditableContentChanged) { CountEditingEvent( execution_context, event, - UseCounter::kWebkitEditableContentChangedOnInput, - UseCounter::kWebkitEditableContentChangedOnTextArea, - UseCounter::kWebkitEditableContentChangedOnContentEditable, - UseCounter::kWebkitEditableContentChangedOnNotNode); + WebFeature::kWebkitEditableContentChangedOnInput, + WebFeature::kWebkitEditableContentChangedOnTextArea, + WebFeature::kWebkitEditableContentChangedOnContentEditable, + WebFeature::kWebkitEditableContentChangedOnNotNode); } } @@ -1808,7 +1808,7 @@ kJSMessageSource, kWarningMessageLevel, "document.execCommand() doesn't work with an invalid HTML structure. It " "is corrected automatically.")); - UseCounter::Count(document, UseCounter::kExecCommandAltersHTMLStructure); + UseCounter::Count(document, WebFeature::kExecCommandAltersHTMLStructure); Element* root = HTMLHtmlElement::Create(document); if (existing_head)
diff --git a/third_party/WebKit/Source/core/editing/commands/DocumentExecCommand.cpp b/third_party/WebKit/Source/core/editing/commands/DocumentExecCommand.cpp index d49bb32b..bd98b83 100644 --- a/third_party/WebKit/Source/core/editing/commands/DocumentExecCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/DocumentExecCommand.cpp
@@ -62,7 +62,7 @@ return false; } if (FocusedElement() && IsTextControlElement(*FocusedElement())) - UseCounter::Count(*this, UseCounter::kExecCommandOnInputOrTextarea); + UseCounter::Count(*this, WebFeature::kExecCommandOnInputOrTextarea); // We don't allow recursive |execCommand()| to protect against attack code. // Recursive call of |execCommand()| could be happened by moving iframe
diff --git a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp index b93ff4e..8f2fb52 100644 --- a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp
@@ -116,7 +116,7 @@ interchange_newline_class_string) return false; UseCounter::Count(node->GetDocument(), - UseCounter::kEditingAppleInterchangeNewline); + WebFeature::kEditingAppleInterchangeNewline); return true; }
diff --git a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp index 01c8e349..d5c752d 100644 --- a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp +++ b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp
@@ -220,11 +220,11 @@ if (!document) return; if (behavior_.ForInnerText()) - UseCounter::Count(document, UseCounter::kInnerTextWithShadowTree); + UseCounter::Count(document, WebFeature::kInnerTextWithShadowTree); if (behavior_.ForSelectionToString()) - UseCounter::Count(document, UseCounter::kSelectionToStringWithShadowTree); + UseCounter::Count(document, WebFeature::kSelectionToStringWithShadowTree); if (behavior_.ForWindowFind()) - UseCounter::Count(document, UseCounter::kWindowFindWithShadowTree); + UseCounter::Count(document, WebFeature::kWindowFindWithShadowTree); } template <typename Strategy>
diff --git a/third_party/WebKit/Source/core/events/Event.cpp b/third_party/WebKit/Source/core/events/Event.cpp index ab9741b6..18fc718 100644 --- a/third_party/WebKit/Source/core/events/Event.cpp +++ b/third_party/WebKit/Source/core/events/Event.cpp
@@ -142,10 +142,10 @@ bool return_value = !defaultPrevented(); if (return_value) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEventGetReturnValueTrue); + WebFeature::kEventGetReturnValueTrue); } else { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEventGetReturnValueFalse); + WebFeature::kEventGetReturnValueFalse); } return return_value; } @@ -153,10 +153,10 @@ void Event::setLegacyReturnValue(ScriptState* script_state, bool return_value) { if (return_value) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEventSetReturnValueTrue); + WebFeature::kEventSetReturnValueTrue); } else { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEventSetReturnValueFalse); + WebFeature::kEventSetReturnValueFalse); } SetDefaultPrevented(!return_value); }
diff --git a/third_party/WebKit/Source/core/events/EventDispatcher.cpp b/third_party/WebKit/Source/core/events/EventDispatcher.cpp index e3ec465..951b3459 100644 --- a/third_party/WebKit/Source/core/events/EventDispatcher.cpp +++ b/third_party/WebKit/Source/core/events/EventDispatcher.cpp
@@ -308,7 +308,7 @@ event_->type() == EventTypeNames::mousedown && isHTMLSelectElement(*node_)) { UseCounter::Count(node_->GetDocument(), - UseCounter::kUntrustedMouseDownEventDispatchedToSelect); + WebFeature::kUntrustedMouseDownEventDispatchedToSelect); } }
diff --git a/third_party/WebKit/Source/core/events/EventTarget.cpp b/third_party/WebKit/Source/core/events/EventTarget.cpp index f6f2cdee..c7041b86 100644 --- a/third_party/WebKit/Source/core/events/EventTarget.cpp +++ b/third_party/WebKit/Source/core/events/EventTarget.cpp
@@ -199,8 +199,8 @@ if (options.hasPassive()) { UseCounter::Count(executing_window->document(), options.passive() - ? UseCounter::kAddEventListenerPassiveTrue - : UseCounter::kAddEventListenerPassiveFalse); + ? WebFeature::kAddEventListenerPassiveTrue + : WebFeature::kAddEventListenerPassiveFalse); } } @@ -240,7 +240,7 @@ options.setPassive(true); if (executing_window) { UseCounter::Count(executing_window->document(), - UseCounter::kSmoothScrollJSInterventionActivated); + WebFeature::kSmoothScrollJSInterventionActivated); } return; } @@ -345,22 +345,22 @@ if (event_type == EventTypeNames::auxclick) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { UseCounter::Count(executing_window->document(), - UseCounter::kAuxclickAddListenerCount); + WebFeature::kAuxclickAddListenerCount); } } else if (event_type == EventTypeNames::appinstalled) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { UseCounter::Count(executing_window->document(), - UseCounter::kAppInstalledEventAddListener); + WebFeature::kAppInstalledEventAddListener); } } else if (EventUtil::IsPointerEventType(event_type)) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { UseCounter::Count(executing_window->document(), - UseCounter::kPointerEventAddListenerCount); + WebFeature::kPointerEventAddListenerCount); } } else if (event_type == EventTypeNames::slotchange) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { UseCounter::Count(executing_window->document(), - UseCounter::kSlotChangeEventAddListener); + WebFeature::kSlotChangeEventAddListener); } } else if (EventUtil::IsDOMMutationEventType(event_type)) { if (ExecutionContext* context = GetExecutionContext()) { @@ -543,33 +543,33 @@ const AtomicString& legacy_type_name, EventListenerVector* listeners_vector, EventListenerVector* legacy_listeners_vector) { - UseCounter::Feature unprefixed_feature; - UseCounter::Feature prefixed_feature; - UseCounter::Feature prefixed_and_unprefixed_feature; + WebFeature unprefixed_feature; + WebFeature prefixed_feature; + WebFeature prefixed_and_unprefixed_feature; if (legacy_type_name == EventTypeNames::webkitTransitionEnd) { - prefixed_feature = UseCounter::kPrefixedTransitionEndEvent; - unprefixed_feature = UseCounter::kUnprefixedTransitionEndEvent; + prefixed_feature = WebFeature::kPrefixedTransitionEndEvent; + unprefixed_feature = WebFeature::kUnprefixedTransitionEndEvent; prefixed_and_unprefixed_feature = - UseCounter::kPrefixedAndUnprefixedTransitionEndEvent; + WebFeature::kPrefixedAndUnprefixedTransitionEndEvent; } else if (legacy_type_name == EventTypeNames::webkitAnimationEnd) { - prefixed_feature = UseCounter::kPrefixedAnimationEndEvent; - unprefixed_feature = UseCounter::kUnprefixedAnimationEndEvent; + prefixed_feature = WebFeature::kPrefixedAnimationEndEvent; + unprefixed_feature = WebFeature::kUnprefixedAnimationEndEvent; prefixed_and_unprefixed_feature = - UseCounter::kPrefixedAndUnprefixedAnimationEndEvent; + WebFeature::kPrefixedAndUnprefixedAnimationEndEvent; } else if (legacy_type_name == EventTypeNames::webkitAnimationStart) { - prefixed_feature = UseCounter::kPrefixedAnimationStartEvent; - unprefixed_feature = UseCounter::kUnprefixedAnimationStartEvent; + prefixed_feature = WebFeature::kPrefixedAnimationStartEvent; + unprefixed_feature = WebFeature::kUnprefixedAnimationStartEvent; prefixed_and_unprefixed_feature = - UseCounter::kPrefixedAndUnprefixedAnimationStartEvent; + WebFeature::kPrefixedAndUnprefixedAnimationStartEvent; } else if (legacy_type_name == EventTypeNames::webkitAnimationIteration) { - prefixed_feature = UseCounter::kPrefixedAnimationIterationEvent; - unprefixed_feature = UseCounter::kUnprefixedAnimationIterationEvent; + prefixed_feature = WebFeature::kPrefixedAnimationIterationEvent; + unprefixed_feature = WebFeature::kUnprefixedAnimationIterationEvent; prefixed_and_unprefixed_feature = - UseCounter::kPrefixedAndUnprefixedAnimationIterationEvent; + WebFeature::kPrefixedAndUnprefixedAnimationIterationEvent; } else if (legacy_type_name == EventTypeNames::mousewheel) { - prefixed_feature = UseCounter::kMouseWheelEvent; - unprefixed_feature = UseCounter::kWheelEvent; - prefixed_and_unprefixed_feature = UseCounter::kMouseWheelAndWheelEvent; + prefixed_feature = WebFeature::kMouseWheelEvent; + unprefixed_feature = WebFeature::kWheelEvent; + prefixed_and_unprefixed_feature = WebFeature::kMouseWheelAndWheelEvent; } else { return; } @@ -631,7 +631,7 @@ bool EventTarget::CheckTypeThenUseCount(const Event* event, const AtomicString& event_type_to_count, - const UseCounter::Feature feature) { + const WebFeature feature) { if (event->type() == event_type_to_count) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) UseCounter::Count(executing_window->document(), feature); @@ -650,46 +650,46 @@ // excludes new event listeners. if (CheckTypeThenUseCount(event, EventTypeNames::beforeunload, - UseCounter::kDocumentBeforeUnloadFired)) { + WebFeature::kDocumentBeforeUnloadFired)) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { if (executing_window != executing_window->top()) { UseCounter::Count(executing_window->document(), - UseCounter::kSubFrameBeforeUnloadFired); + WebFeature::kSubFrameBeforeUnloadFired); } } } else if (CheckTypeThenUseCount(event, EventTypeNames::unload, - UseCounter::kDocumentUnloadFired)) { + WebFeature::kDocumentUnloadFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::DOMFocusIn, - UseCounter::kDOMFocusInOutEvent)) { + WebFeature::kDOMFocusInOutEvent)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::DOMFocusOut, - UseCounter::kDOMFocusInOutEvent)) { + WebFeature::kDOMFocusInOutEvent)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::focusin, - UseCounter::kFocusInOutEvent)) { + WebFeature::kFocusInOutEvent)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::focusout, - UseCounter::kFocusInOutEvent)) { + WebFeature::kFocusInOutEvent)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::textInput, - UseCounter::kTextInputFired)) { + WebFeature::kTextInputFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::touchstart, - UseCounter::kTouchStartFired)) { + WebFeature::kTouchStartFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::mousedown, - UseCounter::kMouseDownFired)) { + WebFeature::kMouseDownFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerdown, - UseCounter::kPointerDownFired)) { + WebFeature::kPointerDownFired)) { if (LocalDOMWindow* executing_window = this->ExecutingWindow()) { if (event->IsPointerEvent() && static_cast<PointerEvent*>(event)->pointerType() == "touch") { UseCounter::Count(executing_window->document(), - UseCounter::kPointerDownFiredForTouch); + WebFeature::kPointerDownFiredForTouch); } } } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerenter, - UseCounter::kPointerEnterLeaveFired)) { + WebFeature::kPointerEnterLeaveFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerleave, - UseCounter::kPointerEnterLeaveFired)) { + WebFeature::kPointerEnterLeaveFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerover, - UseCounter::kPointerOverOutFired)) { + WebFeature::kPointerOverOutFired)) { } else if (CheckTypeThenUseCount(event, EventTypeNames::pointerout, - UseCounter::kPointerOverOutFired)) { + WebFeature::kPointerOverOutFired)) { } ExecutionContext* context = GetExecutionContext();
diff --git a/third_party/WebKit/Source/core/events/EventTarget.h b/third_party/WebKit/Source/core/events/EventTarget.h index 3462258..54f46ff 100644 --- a/third_party/WebKit/Source/core/events/EventTarget.h +++ b/third_party/WebKit/Source/core/events/EventTarget.h
@@ -215,7 +215,7 @@ // event type matches. bool CheckTypeThenUseCount(const Event*, const AtomicString&, - const UseCounter::Feature); + const WebFeature); bool FireEventListeners(Event*, EventTargetData*, EventListenerVector&); void CountLegacyEvents(const AtomicString& legacy_type_name,
diff --git a/third_party/WebKit/Source/core/events/TouchEvent.cpp b/third_party/WebKit/Source/core/events/TouchEvent.cpp index 7248df4..e89b7c2 100644 --- a/third_party/WebKit/Source/core/events/TouchEvent.cpp +++ b/third_party/WebKit/Source/core/events/TouchEvent.cpp
@@ -269,7 +269,7 @@ if (view() && view()->IsLocalDOMWindow() && view()->GetFrame()) { UseCounter::Count( ToLocalFrame(view()->GetFrame()), - UseCounter::kUncancelableTouchEventPreventDefaulted); + WebFeature::kUncancelableTouchEventPreventDefaulted); } if (native_event_ && @@ -280,7 +280,7 @@ if (view() && view()->IsLocalDOMWindow() && view()->GetFrame()) { UseCounter::Count( ToLocalFrame(view()->GetFrame()), - UseCounter:: + WebFeature:: kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted); } message_source = kInterventionMessageSource; @@ -328,12 +328,12 @@ switch (HandlingPassive()) { case PassiveMode::kNotPassiveDefault: UseCounter::Count(ToLocalFrame(view()->GetFrame()), - UseCounter::kTouchEventPreventedNoTouchAction); + WebFeature::kTouchEventPreventedNoTouchAction); break; case PassiveMode::kPassiveForcedDocumentLevel: UseCounter::Count( ToLocalFrame(view()->GetFrame()), - UseCounter::kTouchEventPreventedForcedDocumentPassiveNoTouchAction); + WebFeature::kTouchEventPreventedForcedDocumentPassiveNoTouchAction); break; default: break;
diff --git a/third_party/WebKit/Source/core/events/TouchEventTest.cpp b/third_party/WebKit/Source/core/events/TouchEventTest.cpp index 5b450149..020e218b 100644 --- a/third_party/WebKit/Source/core/events/TouchEventTest.cpp +++ b/third_party/WebKit/Source/core/events/TouchEventTest.cpp
@@ -87,10 +87,10 @@ EXPECT_THAT(MessageSources(), ElementsAre(kJSMessageSource)); EXPECT_TRUE(UseCounter::IsCounted( - GetDocument(), UseCounter::kUncancelableTouchEventPreventDefaulted)); + GetDocument(), WebFeature::kUncancelableTouchEventPreventDefaulted)); EXPECT_FALSE(UseCounter::IsCounted( GetDocument(), - UseCounter:: + WebFeature:: kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted)); } @@ -110,10 +110,10 @@ EXPECT_THAT(MessageSources(), ElementsAre(kInterventionMessageSource)); EXPECT_TRUE(UseCounter::IsCounted( - GetDocument(), UseCounter::kUncancelableTouchEventPreventDefaulted)); + GetDocument(), WebFeature::kUncancelableTouchEventPreventDefaulted)); EXPECT_TRUE(UseCounter::IsCounted( GetDocument(), - UseCounter:: + WebFeature:: kUncancelableTouchEventDueToMainThreadResponsivenessPreventDefaulted)); }
diff --git a/third_party/WebKit/Source/core/events/VisualViewportResizeEvent.cpp b/third_party/WebKit/Source/core/events/VisualViewportResizeEvent.cpp index 060f05d..85f8019 100644 --- a/third_party/WebKit/Source/core/events/VisualViewportResizeEvent.cpp +++ b/third_party/WebKit/Source/core/events/VisualViewportResizeEvent.cpp
@@ -18,7 +18,7 @@ void VisualViewportResizeEvent::DoneDispatchingEventAtCurrentTarget() { UseCounter::Count(currentTarget()->GetExecutionContext(), - UseCounter::kVisualViewportResizeFired); + WebFeature::kVisualViewportResizeFired); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/events/VisualViewportScrollEvent.cpp b/third_party/WebKit/Source/core/events/VisualViewportScrollEvent.cpp index 3c10f1f..0dcd9cc 100644 --- a/third_party/WebKit/Source/core/events/VisualViewportScrollEvent.cpp +++ b/third_party/WebKit/Source/core/events/VisualViewportScrollEvent.cpp
@@ -18,7 +18,7 @@ void VisualViewportScrollEvent::DoneDispatchingEventAtCurrentTarget() { UseCounter::Count(currentTarget()->GetExecutionContext(), - UseCounter::kVisualViewportScrollFired); + WebFeature::kVisualViewportScrollFired); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp index c03a778..8c31ca6 100644 --- a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp +++ b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp
@@ -79,10 +79,10 @@ case kWebWorkerCreationErrorNone: return; case kWebWorkerCreationErrorSecureContextMismatch: - UseCounter::Feature feature = + WebFeature feature = is_secure_context - ? UseCounter::kNonSecureSharedWorkerAccessedFromSecureContext - : UseCounter::kSecureSharedWorkerAccessedFromNonSecureContext; + ? WebFeature::kNonSecureSharedWorkerAccessedFromSecureContext + : WebFeature::kSecureSharedWorkerAccessedFromNonSecureContext; UseCounter::Count(document, feature); return; } @@ -97,7 +97,7 @@ void CountFeature(uint32_t feature) override { UseCounter::Count(worker_->GetExecutionContext(), - static_cast<UseCounter::Feature>(feature)); + static_cast<WebFeature>(feature)); } Persistent<SharedWorker> worker_;
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp index 5582006..05febfd 100644 --- a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp +++ b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp
@@ -110,17 +110,6 @@ // Public methods -------------------------------------------------------------- -LocalFrameView* WebPluginContainerImpl::ParentFrameView() const { - if (!is_attached_) - return nullptr; - - LocalFrame* frame = element_->GetDocument().GetFrame(); - if (!frame) - return nullptr; - - return frame->View(); -} - void WebPluginContainerImpl::Attach() { DCHECK(!is_attached_); is_attached_ = true; @@ -142,10 +131,6 @@ void WebPluginContainerImpl::Paint(GraphicsContext& context, const CullRect& cull_rect) const { - LocalFrameView* parent = ParentFrameView(); - if (!parent) - return; - // Don't paint anything if the plugin doesn't intersect. if (!cull_rect.IntersectsCullRect(frame_rect_)) return; @@ -170,21 +155,22 @@ // The plugin is positioned in the root frame's coordinates, so it needs to // be painted in them too. - IntPoint origin = parent->ContentsToRootFrame(IntPoint(0, 0)); + IntPoint origin = ParentFrameView().ContentsToRootFrame(IntPoint(0, 0)); context.Translate(static_cast<float>(-origin.X()), static_cast<float>(-origin.Y())); WebCanvas* canvas = context.Canvas(); - IntRect window_rect = parent->ContentsToRootFrame(cull_rect.rect_); + IntRect window_rect = ParentFrameView().ContentsToRootFrame(cull_rect.rect_); web_plugin_->Paint(canvas, window_rect); context.Restore(); } void WebPluginContainerImpl::InvalidateRect(const IntRect& rect) { - LocalFrameView* parent = ParentFrameView(); - if (!parent) + // InvalidateRect can be called from Dispose when this plugin is no longer + // attached. In this case, we return immediately. + if (!is_attached_) return; LayoutBox* layout_object = ToLayoutBox(element_->GetLayoutObject()); @@ -284,7 +270,6 @@ element_->ResetInstance(); web_plugin_ = plugin; - is_disposed_ = false; } float WebPluginContainerImpl::DeviceScaleFactor() { @@ -446,9 +431,8 @@ } void WebPluginContainerImpl::ReportGeometry() { - LocalFrameView* parent = ParentFrameView(); - // We cannot compute geometry without a parent or layoutObject. - if (!parent || !element_ || !element_->GetLayoutObject() || !web_plugin_) + // We cannot compute geometry without a layoutObject. + if (!element_ || !element_->GetLayoutObject() || !web_plugin_) return; IntRect window_rect, clip_rect, unobscured_rect; @@ -523,12 +507,12 @@ } bool WebPluginContainerImpl::IsRectTopmost(const WebRect& rect) { - // Disallow access to the frame during dispose(), because it is not guaranteed + // Disallow access to the frame during Dispose(), because it is not guaranteed // to be valid memory once this object has started disposal. In particular, // we might be being disposed because the frame has already be deleted and // then something else dropped the // last reference to the this object. - if (is_disposed_ || !element_) + if (!is_attached_ || !element_) return false; LocalFrame* frame = element_->GetDocument().GetFrame(); @@ -593,8 +577,9 @@ if (Page* page = element_->GetDocument().GetPage()) { if (ScrollingCoordinator* scrolling_coordinator = page->GetScrollingCoordinator()) { - LocalFrameView* parent = ParentFrameView(); - if (parent) + // Only call scrolling_coordinator if attached. SetWantsWheelEvents can + // be called from Plugin Initialization when it is not yet attached. + if (is_attached_) scrolling_coordinator->NotifyGeometryChanged(); } } @@ -602,23 +587,18 @@ WebPoint WebPluginContainerImpl::RootFrameToLocalPoint( const WebPoint& point_in_root_frame) { - LocalFrameView* parent = ParentFrameView(); - if (!parent) - return point_in_root_frame; - WebPoint point_in_content = parent->RootFrameToContents(point_in_root_frame); + WebPoint point_in_content = + ParentFrameView().RootFrameToContents(point_in_root_frame); return RoundedIntPoint(element_->GetLayoutObject()->AbsoluteToLocal( FloatPoint(point_in_content), kUseTransforms)); } WebPoint WebPluginContainerImpl::LocalToRootFramePoint( const WebPoint& point_in_local) { - LocalFrameView* parent = ParentFrameView(); - if (!parent) - return point_in_local; IntPoint absolute_point = RoundedIntPoint(element_->GetLayoutObject()->LocalToAbsolute( FloatPoint(point_in_local), kUseTransforms)); - return parent->ContentsToRootFrame(absolute_point); + return ParentFrameView().ContentsToRootFrame(absolute_point); } void WebPluginContainerImpl::DidReceiveResponse( @@ -687,7 +667,6 @@ WebPluginContainerImpl::WebPluginContainerImpl(HTMLPlugInElement& element, WebPlugin* web_plugin) : WebPluginContainerBase(element.GetDocument().GetFrame()), - is_attached_(false), element_(element), web_plugin_(web_plugin), web_layer_(nullptr), @@ -695,15 +674,20 @@ wants_wheel_events_(false), self_visible_(false), parent_visible_(false), - is_disposed_(false) {} + is_attached_(false) {} WebPluginContainerImpl::~WebPluginContainerImpl() { // The plugin container must have been disposed of by now. DCHECK(!web_plugin_); } +LocalFrameView& WebPluginContainerImpl::ParentFrameView() const { + DCHECK(is_attached_); + return *element_->GetDocument().GetFrame()->View(); +} + void WebPluginContainerImpl::Dispose() { - is_disposed_ = true; + is_attached_ = false; RequestTouchEventType(kTouchEventRequestTypeNone); SetWantsWheelEvents(false); @@ -728,12 +712,12 @@ void WebPluginContainerImpl::HandleMouseEvent(MouseEvent* event) { // We cache the parent LocalFrameView here as the plugin widget could be // deleted in the call to HandleEvent. See http://b/issue?id=1362948 - LocalFrameView* parent = ParentFrameView(); + LocalFrameView& parent = ParentFrameView(); // TODO(dtapuska): Move WebMouseEventBuilder into the anonymous namespace // in this class. WebMouseEventBuilder transformed_event( - parent, LayoutItem(element_->GetLayoutObject()), *event); + &parent, LayoutItem(element_->GetLayoutObject()), *event); if (transformed_event.GetType() == WebInputEvent::kUndefined) return; @@ -749,11 +733,11 @@ // A windowless plugin can change the cursor in response to a mouse move // event. We need to reflect the changed cursor in the frame view as the // mouse is moved in the boundaries of the windowless plugin. - Page* page = parent->GetFrame().GetPage(); + Page* page = parent.GetFrame().GetPage(); if (!page) return; page->GetChromeClient().SetCursorForPlugin( - cursor_info, &parent->GetFrame().LocalFrameRoot()); + cursor_info, &parent.GetFrame().LocalFrameRoot()); } void WebPluginContainerImpl::HandleDragEvent(MouseEvent* event) { @@ -790,8 +774,7 @@ WebFloatPoint absolute_location = event->NativeEvent().PositionInRootFrame(); // Translate the root frame position to content coordinates. - if (LocalFrameView* parent = ParentFrameView()) - absolute_location = parent->RootFrameToContents(absolute_location); + absolute_location = ParentFrameView().RootFrameToContents(absolute_location); IntPoint local_point = RoundedIntPoint(element_->GetLayoutObject()->AbsoluteToLocal( @@ -850,13 +833,13 @@ const WebTouchEvent* touch_event = static_cast<const WebTouchEvent*>(&event); WebTouchEvent transformed_event = touch_event->FlattenTransform(); + LocalFrameView& parent = ParentFrameView(); for (unsigned i = 0; i < transformed_event.touches_length; ++i) { WebFloatPoint absolute_location = transformed_event.touches[i].PositionInWidget(); // Translate the root frame position to content coordinates. - if (LocalFrameView* parent = ParentFrameView()) - absolute_location = parent->RootFrameToContents(absolute_location); + absolute_location = parent.RootFrameToContents(absolute_location); IntPoint local_point = RoundedIntPoint(element_->GetLayoutObject()->AbsoluteToLocal( @@ -936,9 +919,8 @@ } void WebPluginContainerImpl::SynthesizeMouseEventIfPossible(TouchEvent* event) { - LocalFrameView* parent = ParentFrameView(); WebMouseEventBuilder web_event( - parent, LayoutItem(element_->GetLayoutObject()), *event); + &ParentFrameView(), LayoutItem(element_->GetLayoutObject()), *event); if (web_event.GetType() == WebInputEvent::kUndefined) return; @@ -950,13 +932,9 @@ } void WebPluginContainerImpl::FocusPlugin() { - if (Page* current_page = GetFrame()->GetPage()) { - current_page->GetFocusController().SetFocusedElement(element_, GetFrame()); - } else { - GetFrame()->GetDocument()->SetFocusedElement( - element_, FocusParams(SelectionBehaviorOnFocus::kNone, - kWebFocusTypeNone, nullptr)); - } + LocalFrame* frame = element_->GetDocument().GetFrame(); + DCHECK(is_attached_ && frame && frame->GetPage()); + frame->GetPage()->GetFocusController().SetFocusedElement(element_, frame); } void WebPluginContainerImpl::IssuePaintInvalidations() {
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.h b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.h index a8096fe9..0af41d2 100644 --- a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.h +++ b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.h
@@ -187,7 +187,7 @@ void Dispose() override; private: - LocalFrameView* ParentFrameView() const; + LocalFrameView& ParentFrameView() const; // Sets |windowRect| to the content rect of the plugin in screen space. // Sets |clippedAbsoluteRect| to the visible rect for the plugin, clipped to // the visible screen of the root frame, in local space of the plugin. @@ -224,7 +224,6 @@ friend class WebPluginContainerTest; - bool is_attached_; Member<HTMLPlugInElement> element_; WebPlugin* web_plugin_; WebLayer* web_layer_; @@ -234,7 +233,7 @@ bool wants_wheel_events_; bool self_visible_; bool parent_visible_; - bool is_disposed_; + bool is_attached_; }; DEFINE_TYPE_CASTS(WebPluginContainerImpl,
diff --git a/third_party/WebKit/Source/core/fileapi/Blob.cpp b/third_party/WebKit/Source/core/fileapi/Blob.cpp index 795a698..33f38374 100644 --- a/third_party/WebKit/Source/core/fileapi/Blob.cpp +++ b/third_party/WebKit/Source/core/fileapi/Blob.cpp
@@ -96,7 +96,7 @@ DCHECK(options.hasEndings()); bool normalize_line_endings_to_native = options.endings() == "native"; if (normalize_line_endings_to_native) - UseCounter::Count(context, UseCounter::kFileAPINativeLineEndings); + UseCounter::Count(context, WebFeature::kFileAPINativeLineEndings); std::unique_ptr<BlobData> blob_data = BlobData::Create(); blob_data->SetContentType(NormalizeType(options.type()));
diff --git a/third_party/WebKit/Source/core/fileapi/File.cpp b/third_party/WebKit/Source/core/fileapi/File.cpp index cb17626..51f2e35 100644 --- a/third_party/WebKit/Source/core/fileapi/File.cpp +++ b/third_party/WebKit/Source/core/fileapi/File.cpp
@@ -133,7 +133,7 @@ DCHECK(options.hasEndings()); bool normalize_line_endings_to_native = options.endings() == "native"; if (normalize_line_endings_to_native) - UseCounter::Count(context, UseCounter::kFileAPINativeLineEndings); + UseCounter::Count(context, WebFeature::kFileAPINativeLineEndings); std::unique_ptr<BlobData> blob_data = BlobData::Create(); blob_data->SetContentType(NormalizeType(options.type()));
diff --git a/third_party/WebKit/Source/core/fileapi/URLFileAPI.cpp b/third_party/WebKit/Source/core/fileapi/URLFileAPI.cpp index 4483c6d7..d7669235 100644 --- a/third_party/WebKit/Source/core/fileapi/URLFileAPI.cpp +++ b/third_party/WebKit/Source/core/fileapi/URLFileAPI.cpp
@@ -31,7 +31,7 @@ return String(); } - UseCounter::Count(execution_context, UseCounter::kCreateObjectURLBlob); + UseCounter::Count(execution_context, WebFeature::kCreateObjectURLBlob); return DOMURL::CreatePublicURL(execution_context, blob, blob->Uuid()); }
diff --git a/third_party/WebKit/Source/core/frame/DOMWindow.cpp b/third_party/WebKit/Source/core/frame/DOMWindow.cpp index 792f78e..1d00e718 100644 --- a/third_party/WebKit/Source/core/frame/DOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/DOMWindow.cpp
@@ -224,17 +224,17 @@ if (MixedContentChecker::IsMixedContent(source_document->GetSecurityOrigin(), target_url)) { UseCounter::Count(source->GetFrame(), - UseCounter::kPostMessageFromSecureToInsecure); + WebFeature::kPostMessageFromSecureToInsecure); } else if (MixedContentChecker::IsMixedContent( GetFrame()->GetSecurityContext()->GetSecurityOrigin(), source_document->Url())) { UseCounter::Count(source->GetFrame(), - UseCounter::kPostMessageFromInsecureToSecure); + WebFeature::kPostMessageFromInsecureToSecure); if (MixedContentChecker::IsMixedContent( GetFrame()->Tree().Top().GetSecurityContext()->GetSecurityOrigin(), source_document->Url())) { UseCounter::Count(source->GetFrame(), - UseCounter::kPostMessageFromInsecureToSecureToplevel); + WebFeature::kPostMessageFromInsecureToSecureToplevel); } } @@ -243,7 +243,7 @@ SecurityViolationReportingPolicy::kSuppressReporting)) { UseCounter::Count( source->GetFrame(), - UseCounter::kPostMessageOutgoingWouldBeBlockedByConnectSrc); + WebFeature::kPostMessageOutgoingWouldBeBlockedByConnectSrc); } MessageEvent* event =
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.h b/third_party/WebKit/Source/core/frame/Deprecation.h index a8b4028..99fe14d 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.h +++ b/third_party/WebKit/Source/core/frame/Deprecation.h
@@ -42,37 +42,12 @@ static void CountDeprecation(const LocalFrame*, WebFeature); static void CountDeprecation(ExecutionContext*, WebFeature); static void CountDeprecation(const Document&, WebFeature); - static void CountDeprecation(const LocalFrame* frame, - UseCounter::Feature feature) { - return CountDeprecation(frame, static_cast<WebFeature>(feature)); - } - static void CountDeprecation(ExecutionContext* exec_context, - UseCounter::Feature feature) { - return CountDeprecation(exec_context, static_cast<WebFeature>(feature)); - } - static void CountDeprecation(const Document& document, - UseCounter::Feature feature) { - return CountDeprecation(document, static_cast<WebFeature>(feature)); - } // Count only features if they're being used in an iframe which does not // have script access into the top level document. static void CountDeprecationCrossOriginIframe(const LocalFrame*, WebFeature); static void CountDeprecationCrossOriginIframe(const Document&, WebFeature); static String DeprecationMessage(WebFeature); - static void CountDeprecationCrossOriginIframe(const LocalFrame* frame, - UseCounter::Feature feature) { - return CountDeprecationCrossOriginIframe(frame, - static_cast<WebFeature>(feature)); - } - static void CountDeprecationCrossOriginIframe(const Document& document, - UseCounter::Feature feature) { - return CountDeprecationCrossOriginIframe(document, - static_cast<WebFeature>(feature)); - } - static String DeprecationMessage(UseCounter::Feature feature) { - return DeprecationMessage(static_cast<WebFeature>(feature)); - } // Note: this is only public for tests. bool IsSuppressed(CSSPropertyID unresolved_property);
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index de9e5809..90e2efa 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -696,7 +696,7 @@ sender, RedirectStatus::kNoRedirect, SecurityViolationReportingPolicy::kSuppressReporting)) { UseCounter::Count( - GetFrame(), UseCounter::kPostMessageIncomingWouldBeBlockedByConnectSrc); + GetFrame(), WebFeature::kPostMessageIncomingWouldBeBlockedByConnectSrc); } DispatchEvent(event); @@ -728,7 +728,7 @@ if (script_state && v8::MicrotasksScope::IsRunningMicrotasks(script_state->GetIsolate())) { - UseCounter::Count(document(), UseCounter::kDuring_Microtask_Print); + UseCounter::Count(document(), WebFeature::kDuring_Microtask_Print); } if (GetFrame()->IsLoading()) { @@ -737,7 +737,7 @@ } UseCounter::CountCrossOriginIframe(*document(), - UseCounter::kCrossOriginWindowPrint); + WebFeature::kCrossOriginWindowPrint); should_print_when_finished_loading_ = false; page->GetChromeClient().Print(GetFrame()); @@ -754,7 +754,7 @@ return; if (document()->IsSandboxed(kSandboxModals)) { - UseCounter::Count(document(), UseCounter::kDialogInSandboxedContext); + UseCounter::Count(document(), WebFeature::kDialogInSandboxedContext); GetFrameConsole()->AddMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Ignored call to 'alert()'. The document is sandboxed, and the " @@ -764,27 +764,27 @@ switch (document()->GetEngagementLevel()) { case mojom::blink::EngagementLevel::NONE: - UseCounter::Count(document(), UseCounter::kAlertEngagementNone); + UseCounter::Count(document(), WebFeature::kAlertEngagementNone); break; case mojom::blink::EngagementLevel::MINIMAL: - UseCounter::Count(document(), UseCounter::kAlertEngagementMinimal); + UseCounter::Count(document(), WebFeature::kAlertEngagementMinimal); break; case mojom::blink::EngagementLevel::LOW: - UseCounter::Count(document(), UseCounter::kAlertEngagementLow); + UseCounter::Count(document(), WebFeature::kAlertEngagementLow); break; case mojom::blink::EngagementLevel::MEDIUM: - UseCounter::Count(document(), UseCounter::kAlertEngagementMedium); + UseCounter::Count(document(), WebFeature::kAlertEngagementMedium); break; case mojom::blink::EngagementLevel::HIGH: - UseCounter::Count(document(), UseCounter::kAlertEngagementHigh); + UseCounter::Count(document(), WebFeature::kAlertEngagementHigh); break; case mojom::blink::EngagementLevel::MAX: - UseCounter::Count(document(), UseCounter::kAlertEngagementMax); + UseCounter::Count(document(), WebFeature::kAlertEngagementMax); break; } if (v8::MicrotasksScope::IsRunningMicrotasks(script_state->GetIsolate())) { - UseCounter::Count(document(), UseCounter::kDuring_Microtask_Alert); + UseCounter::Count(document(), WebFeature::kDuring_Microtask_Alert); } document()->UpdateStyleAndLayoutTree(); @@ -794,7 +794,7 @@ return; UseCounter::CountCrossOriginIframe(*document(), - UseCounter::kCrossOriginWindowAlert); + WebFeature::kCrossOriginWindowAlert); page->GetChromeClient().OpenJavaScriptAlert(GetFrame(), message); } @@ -804,7 +804,7 @@ return false; if (document()->IsSandboxed(kSandboxModals)) { - UseCounter::Count(document(), UseCounter::kDialogInSandboxedContext); + UseCounter::Count(document(), WebFeature::kDialogInSandboxedContext); GetFrameConsole()->AddMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Ignored call to 'confirm()'. The document is sandboxed, and the " @@ -814,27 +814,27 @@ switch (document()->GetEngagementLevel()) { case mojom::blink::EngagementLevel::NONE: - UseCounter::Count(document(), UseCounter::kConfirmEngagementNone); + UseCounter::Count(document(), WebFeature::kConfirmEngagementNone); break; case mojom::blink::EngagementLevel::MINIMAL: - UseCounter::Count(document(), UseCounter::kConfirmEngagementMinimal); + UseCounter::Count(document(), WebFeature::kConfirmEngagementMinimal); break; case mojom::blink::EngagementLevel::LOW: - UseCounter::Count(document(), UseCounter::kConfirmEngagementLow); + UseCounter::Count(document(), WebFeature::kConfirmEngagementLow); break; case mojom::blink::EngagementLevel::MEDIUM: - UseCounter::Count(document(), UseCounter::kConfirmEngagementMedium); + UseCounter::Count(document(), WebFeature::kConfirmEngagementMedium); break; case mojom::blink::EngagementLevel::HIGH: - UseCounter::Count(document(), UseCounter::kConfirmEngagementHigh); + UseCounter::Count(document(), WebFeature::kConfirmEngagementHigh); break; case mojom::blink::EngagementLevel::MAX: - UseCounter::Count(document(), UseCounter::kConfirmEngagementMax); + UseCounter::Count(document(), WebFeature::kConfirmEngagementMax); break; } if (v8::MicrotasksScope::IsRunningMicrotasks(script_state->GetIsolate())) { - UseCounter::Count(document(), UseCounter::kDuring_Microtask_Confirm); + UseCounter::Count(document(), WebFeature::kDuring_Microtask_Confirm); } document()->UpdateStyleAndLayoutTree(); @@ -844,7 +844,7 @@ return false; UseCounter::CountCrossOriginIframe(*document(), - UseCounter::kCrossOriginWindowConfirm); + WebFeature::kCrossOriginWindowConfirm); return page->GetChromeClient().OpenJavaScriptConfirm(GetFrame(), message); } @@ -856,7 +856,7 @@ return String(); if (document()->IsSandboxed(kSandboxModals)) { - UseCounter::Count(document(), UseCounter::kDialogInSandboxedContext); + UseCounter::Count(document(), WebFeature::kDialogInSandboxedContext); GetFrameConsole()->AddMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Ignored call to 'prompt()'. The document is sandboxed, and the " @@ -866,27 +866,27 @@ switch (document()->GetEngagementLevel()) { case mojom::blink::EngagementLevel::NONE: - UseCounter::Count(document(), UseCounter::kPromptEngagementNone); + UseCounter::Count(document(), WebFeature::kPromptEngagementNone); break; case mojom::blink::EngagementLevel::MINIMAL: - UseCounter::Count(document(), UseCounter::kPromptEngagementMinimal); + UseCounter::Count(document(), WebFeature::kPromptEngagementMinimal); break; case mojom::blink::EngagementLevel::LOW: - UseCounter::Count(document(), UseCounter::kPromptEngagementLow); + UseCounter::Count(document(), WebFeature::kPromptEngagementLow); break; case mojom::blink::EngagementLevel::MEDIUM: - UseCounter::Count(document(), UseCounter::kPromptEngagementMedium); + UseCounter::Count(document(), WebFeature::kPromptEngagementMedium); break; case mojom::blink::EngagementLevel::HIGH: - UseCounter::Count(document(), UseCounter::kPromptEngagementHigh); + UseCounter::Count(document(), WebFeature::kPromptEngagementHigh); break; case mojom::blink::EngagementLevel::MAX: - UseCounter::Count(document(), UseCounter::kPromptEngagementMax); + UseCounter::Count(document(), WebFeature::kPromptEngagementMax); break; } if (v8::MicrotasksScope::IsRunningMicrotasks(script_state->GetIsolate())) { - UseCounter::Count(document(), UseCounter::kDuring_Microtask_Prompt); + UseCounter::Count(document(), WebFeature::kDuring_Microtask_Prompt); } document()->UpdateStyleAndLayoutTree(); @@ -901,7 +901,7 @@ return return_value; UseCounter::CountCrossOriginIframe(*document(), - UseCounter::kCrossOriginWindowPrompt); + WebFeature::kCrossOriginWindowPrompt); return String(); } @@ -1436,10 +1436,10 @@ } if (event_type == EventTypeNames::unload) { - UseCounter::Count(document(), UseCounter::kDocumentUnloadRegistered); + UseCounter::Count(document(), WebFeature::kDocumentUnloadRegistered); AddUnloadEventListener(this); } else if (event_type == EventTypeNames::beforeunload) { - UseCounter::Count(document(), UseCounter::kDocumentBeforeUnloadRegistered); + UseCounter::Count(document(), WebFeature::kDocumentBeforeUnloadRegistered); if (AllowsBeforeUnloadListeners(this)) { // This is confusingly named. It doesn't actually add the listener. It // just increments a count so that we know we have listeners registered @@ -1449,7 +1449,7 @@ } else { // Subframes return false from allowsBeforeUnloadListeners. UseCounter::Count(document(), - UseCounter::kSubFrameBeforeUnloadRegistered); + WebFeature::kSubFrameBeforeUnloadRegistered); } } } @@ -1601,9 +1601,9 @@ if (!first_frame) return nullptr; - UseCounter::Count(*active_document, UseCounter::kDOMWindowOpen); + UseCounter::Count(*active_document, WebFeature::kDOMWindowOpen); if (!window_features_string.IsEmpty()) - UseCounter::Count(*active_document, UseCounter::kDOMWindowOpenFeatures); + UseCounter::Count(*active_document, WebFeature::kDOMWindowOpenFeatures); // Get the target frame for the special cases of _top and _parent. // In those cases, we schedule a location change right now and return early.
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index a60db701..079317a 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -944,9 +944,9 @@ // Top navigation in sandbox with or w/o 'allow-top-navigation'. if (target_frame != this && sandboxed && target_frame == Tree().Top()) { - UseCounter::Count(this, UseCounter::kTopNavInSandbox); + UseCounter::Count(this, WebFeature::kTopNavInSandbox); if (!has_user_gesture) { - UseCounter::Count(this, UseCounter::kTopNavInSandboxWithoutGesture); + UseCounter::Count(this, WebFeature::kTopNavInSandboxWithoutGesture); } } @@ -963,12 +963,12 @@ if (has_user_gesture) framebust_params |= kUserGestureBit; - UseCounter::Count(this, UseCounter::kTopNavigationFromSubFrame); + UseCounter::Count(this, WebFeature::kTopNavigationFromSubFrame); if (sandboxed) { // Sandboxed with 'allow-top-navigation'. - UseCounter::Count(this, UseCounter::kTopNavInSandboxWithPerm); + UseCounter::Count(this, WebFeature::kTopNavInSandboxWithPerm); if (!has_user_gesture) { UseCounter::Count(this, - UseCounter::kTopNavInSandboxWithPermButNoGesture); + WebFeature::kTopNavInSandboxWithPermButNoGesture); } }
diff --git a/third_party/WebKit/Source/core/frame/FrameViewTest.cpp b/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp similarity index 92% rename from third_party/WebKit/Source/core/frame/FrameViewTest.cpp rename to third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp index af789ec..32fe830d 100644 --- a/third_party/WebKit/Source/core/frame/FrameViewTest.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrameViewTest.cpp
@@ -50,19 +50,19 @@ }; typedef bool TestParamRootLayerScrolling; -class FrameViewTest +class LocalFrameViewTest : public testing::WithParamInterface<TestParamRootLayerScrolling>, private ScopedRootLayerScrollingForTest, public testing::Test { protected: - FrameViewTest() + LocalFrameViewTest() : ScopedRootLayerScrollingForTest(GetParam()), chrome_client_(new MockChromeClient) { EXPECT_CALL(ChromeClient(), AttachRootGraphicsLayer(_, _)) .Times(AnyNumber()); } - ~FrameViewTest() { + ~LocalFrameViewTest() { testing::Mock::VerifyAndClearExpectations(&ChromeClient()); } @@ -83,9 +83,9 @@ std::unique_ptr<DummyPageHolder> page_holder_; }; -INSTANTIATE_TEST_CASE_P(All, FrameViewTest, ::testing::Bool()); +INSTANTIATE_TEST_CASE_P(All, LocalFrameViewTest, ::testing::Bool()); -TEST_P(FrameViewTest, SetPaintInvalidationDuringUpdateAllLifecyclePhases) { +TEST_P(LocalFrameViewTest, SetPaintInvalidationDuringUpdateAllLifecyclePhases) { GetDocument().body()->setInnerHTML("<div id='a' style='color: blue'>A</div>"); GetDocument().View()->UpdateAllLifecyclePhases(); GetDocument().getElementById("a")->setAttribute(HTMLNames::styleAttr, @@ -95,7 +95,7 @@ EXPECT_FALSE(ChromeClient().has_scheduled_animation_); } -TEST_P(FrameViewTest, SetPaintInvalidationOutOfUpdateAllLifecyclePhases) { +TEST_P(LocalFrameViewTest, SetPaintInvalidationOutOfUpdateAllLifecyclePhases) { GetDocument().body()->setInnerHTML("<div id='a' style='color: blue'>A</div>"); GetDocument().View()->UpdateAllLifecyclePhases(); ChromeClient().has_scheduled_animation_ = false; @@ -117,7 +117,7 @@ // If we don't hide the tooltip on scroll, it can negatively impact scrolling // performance. See crbug.com/586852 for details. -TEST_P(FrameViewTest, HideTooltipWhenScrollPositionChanges) { +TEST_P(LocalFrameViewTest, HideTooltipWhenScrollPositionChanges) { GetDocument().body()->setInnerHTML( "<div style='width:1000px;height:1000px'></div>"); GetDocument().View()->UpdateAllLifecyclePhases(); @@ -139,7 +139,7 @@ // NoOverflowInIncrementVisuallyNonEmptyPixelCount tests fail if the number of // pixels is calculated in 32-bit integer, because 65536 * 65536 would become 0 // if it was calculated in 32-bit and thus it would be considered as empty. -TEST_P(FrameViewTest, NoOverflowInIncrementVisuallyNonEmptyPixelCount) { +TEST_P(LocalFrameViewTest, NoOverflowInIncrementVisuallyNonEmptyPixelCount) { EXPECT_FALSE(GetDocument().View()->IsVisuallyNonEmpty()); GetDocument().View()->IncrementVisuallyNonEmptyPixelCount( IntSize(65536, 65536)); @@ -150,7 +150,8 @@ // LocalFrameView::UpdateLayersAndCompositingAfterScrollIfNeeded during layout // caused a crash as the code was incorrectly assuming that the ancestor // overflow layer would always be valid. -TEST_P(FrameViewTest, ViewportConstrainedObjectsHandledCorrectlyDuringLayout) { +TEST_P(LocalFrameViewTest, + ViewportConstrainedObjectsHandledCorrectlyDuringLayout) { GetDocument().body()->setInnerHTML( "<style>.container { height: 200%; }" "#sticky { position: sticky; top: 0; height: 50px; }</style>" @@ -170,7 +171,7 @@ ScrollOffset(0, 100), kProgrammaticScroll); } -TEST_P(FrameViewTest, StyleChangeUpdatesViewportConstrainedObjects) { +TEST_P(LocalFrameViewTest, StyleChangeUpdatesViewportConstrainedObjects) { // When using root layer scrolling there is no concept of viewport constrained // objects, so skip this test. if (RuntimeEnabledFeatures::RootLayerScrollingEnabled())
diff --git a/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp b/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp index 2eb3569..8686087 100644 --- a/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp +++ b/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp
@@ -132,7 +132,7 @@ const Resource& resource) { if (!resource.IsEligibleForIntegrityCheck(document.GetSecurityOrigin())) { UseCounter::Count(document, - UseCounter::kSRIElementIntegrityAttributeButIneligible); + WebFeature::kSRIElementIntegrityAttributeButIneligible); LogErrorToConsole("Subresource Integrity: The resource '" + resource_url.ElidedString() + "' has an integrity attribute, but the resource " @@ -204,7 +204,7 @@ if (DigestsEqual(digest, converted_hash_vector)) { UseCounter::Count( &execution_context, - UseCounter::kSRIElementWithMatchingIntegrityAttribute); + WebFeature::kSRIElementWithMatchingIntegrityAttribute); return true; } } @@ -228,7 +228,7 @@ resource_url.ElidedString() + "'. The resource has been blocked."; } UseCounter::Count(&execution_context, - UseCounter::kSRIElementWithNonMatchingIntegrityAttribute); + WebFeature::kSRIElementWithNonMatchingIntegrityAttribute); return false; } @@ -360,7 +360,7 @@ *execution_context); UseCounter::Count( execution_context, - UseCounter::kSRIElementWithUnparsableIntegrityAttribute); + WebFeature::kSRIElementWithUnparsableIntegrityAttribute); } continue; } @@ -376,7 +376,7 @@ *execution_context); UseCounter::Count( execution_context, - UseCounter::kSRIElementWithUnparsableIntegrityAttribute); + WebFeature::kSRIElementWithUnparsableIntegrityAttribute); } continue; } @@ -393,7 +393,7 @@ *execution_context); UseCounter::Count( execution_context, - UseCounter::kSRIElementWithUnparsableIntegrityAttribute); + WebFeature::kSRIElementWithUnparsableIntegrityAttribute); } continue; }
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.cpp b/third_party/WebKit/Source/core/frame/UseCounter.cpp index 47aeb08f..e803c85 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.cpp +++ b/third_party/WebKit/Source/core/frame/UseCounter.cpp
@@ -1102,7 +1102,7 @@ UseCounter::UseCounter(Context context) : mute_count_(0), context_(context), - features_recorded_(kNumberOfFeatures), + features_recorded_(static_cast<int>(WebFeature::kNumberOfFeatures)), css_recorded_(numCSSPropertyIDs), animated_css_recorded_(numCSSPropertyIDs) {} @@ -1174,7 +1174,7 @@ css_recorded_.ClearAll(); animated_css_recorded_.ClearAll(); if (context_ != kDisabledContext && !mute_count_) { - FeaturesHistogram().Count(kPageVisits); + FeaturesHistogram().Count(static_cast<int>(WebFeature::kPageVisits)); if (context_ != kExtensionContext) { CssHistogram().Count(totalPagesMeasuredCSSSampleId()); AnimatedCSSHistogram().Count(totalPagesMeasuredCSSSampleId()); @@ -1331,13 +1331,13 @@ // So instead we just use a dedicated histogram for the SVG case. DEFINE_STATIC_LOCAL(blink::EnumerationHistogram, svg_histogram, ("Blink.UseCounter.SVGImage.Features", - blink::UseCounter::kNumberOfFeatures)); + static_cast<uint32_t>(WebFeature::kNumberOfFeatures))); DEFINE_STATIC_LOCAL(blink::EnumerationHistogram, extension_histogram, ("Blink.UseCounter.Extensions.Features", - blink::UseCounter::kNumberOfFeatures)); - DEFINE_STATIC_LOCAL( - blink::EnumerationHistogram, histogram, - ("Blink.UseCounter.Features", blink::UseCounter::kNumberOfFeatures)); + static_cast<uint32_t>(WebFeature::kNumberOfFeatures))); + DEFINE_STATIC_LOCAL(blink::EnumerationHistogram, histogram, + ("Blink.UseCounter.Features", + static_cast<uint32_t>(WebFeature::kNumberOfFeatures))); switch (context_) { case kSVGImageContext: return svg_histogram; @@ -1381,19 +1381,21 @@ */ static EnumerationHistogram& FeatureObserverHistogram() { - DEFINE_STATIC_LOCAL( - EnumerationHistogram, histogram, - ("WebCore.FeatureObserver", UseCounter::kNumberOfFeatures)); + DEFINE_STATIC_LOCAL(EnumerationHistogram, histogram, + ("WebCore.FeatureObserver", + static_cast<uint32_t>(WebFeature::kNumberOfFeatures))); return histogram; } UseCounter::LegacyCounter::LegacyCounter() - : feature_bits_(kNumberOfFeatures), css_bits_(numCSSPropertyIDs) {} + : feature_bits_(static_cast<int>(WebFeature::kNumberOfFeatures)), + css_bits_(numCSSPropertyIDs) {} UseCounter::LegacyCounter::~LegacyCounter() { // PageDestruction was intended to be used as a scale, but it's broken (due to // fast shutdown). See https://crbug.com/597963. - FeatureObserverHistogram().Count(kOBSOLETE_PageDestruction); + FeatureObserverHistogram().Count( + static_cast<int>(WebFeature::kOBSOLETE_PageDestruction)); UpdateMeasurements(); } @@ -1407,8 +1409,8 @@ void UseCounter::LegacyCounter::UpdateMeasurements() { EnumerationHistogram& feature_histogram = FeatureObserverHistogram(); - feature_histogram.Count(kPageVisits); - for (size_t i = 0; i < kNumberOfFeatures; ++i) { + feature_histogram.Count(static_cast<int>(WebFeature::kPageVisits)); + for (size_t i = 0; i < static_cast<int>(WebFeature::kNumberOfFeatures); ++i) { if (feature_bits_.QuickGet(i)) feature_histogram.Count(i); }
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.h b/third_party/WebKit/Source/core/frame/UseCounter.h index 49ea052..61fffbc1 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.h +++ b/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -78,10 +78,6 @@ UseCounter(Context = kDefaultContext); - enum Feature : uint32_t { -#include "public/platform/UseCounterFeature.def" - }; - // An interface to observe UseCounter changes. Note that this is never // notified when the counter is disabled by |m_muteCount| or when |m_context| // is kDisabledContext. @@ -99,16 +95,6 @@ static void Count(const LocalFrame*, WebFeature); static void Count(const Document&, WebFeature); static void Count(ExecutionContext*, WebFeature); - // TODO(lunalu): Deprecate Count() that takes UseCounter::Feature. - static void Count(const LocalFrame* frame, Feature feature) { - return Count(frame, static_cast<WebFeature>(feature)); - } - static void Count(const Document& document, Feature feature) { - return Count(document, static_cast<WebFeature>(feature)); - } - static void Count(ExecutionContext* exec_context, Feature feature) { - return Count(exec_context, static_cast<WebFeature>(feature)); - } void Count(CSSParserMode, CSSPropertyID); void Count(WebFeature, const LocalFrame*); @@ -119,16 +105,10 @@ // Count only features if they're being used in an iframe which does not // have script access into the top level document. static void CountCrossOriginIframe(const Document&, WebFeature); - static void CountCrossOriginIframe(const Document& doc, Feature feature) { - return CountCrossOriginIframe(doc, static_cast<WebFeature>(feature)); - } // Return whether the Feature was previously counted for this document. // NOTE: only for use in testing. static bool IsCounted(Document&, WebFeature); - static bool IsCounted(Document& doc, Feature feature) { - return IsCounted(doc, static_cast<WebFeature>(feature)); - } // Return whether the CSSPropertyID was previously counted for this document. // NOTE: only for use in testing. static bool IsCounted(Document&, const String&); @@ -152,17 +132,11 @@ void UnmuteForInspector(); void RecordMeasurement(WebFeature); - void RecordMeasurement(Feature feature) { - return RecordMeasurement(static_cast<WebFeature>(feature)); - } // Return whether the feature has been seen since the last page load // (except when muted). Does include features seen in documents which have // reporting disabled. bool HasRecordedMeasurement(WebFeature) const; - bool HasRecordedMeasurement(Feature feature) const { - return HasRecordedMeasurement(static_cast<WebFeature>(feature)); - } DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/core/frame/UseCounterTest.cpp b/third_party/WebKit/Source/core/frame/UseCounterTest.cpp index 9c4a330..672dec8 100644 --- a/third_party/WebKit/Source/core/frame/UseCounterTest.cpp +++ b/third_party/WebKit/Source/core/frame/UseCounterTest.cpp
@@ -35,7 +35,7 @@ int GetPageVisitsBucketforHistogram(const std::string& histogram_name) { if (histogram_name.find("CSS") == std::string::npos) - return blink::UseCounter::kPageVisits; + return static_cast<int>(blink::WebFeature::kPageVisits); // For CSS histograms, the page visits bucket should be 1. return 1; } @@ -258,7 +258,7 @@ HistogramTester histogram_tester; // The specific feature we use here isn't important. - UseCounter::Feature feature = UseCounter::Feature::kSVGSMILElementInDocument; + WebFeature feature = WebFeature::kSVGSMILElementInDocument; CSSPropertyID property = CSSPropertyFontWeight; CSSParserMode parser_mode = kHTMLStandardMode; @@ -293,7 +293,8 @@ EXPECT_TRUE(use_counter.HasRecordedMeasurement(feature)); use_counter.Count(parser_mode, property); EXPECT_TRUE(use_counter.IsCounted(property)); - histogram_tester.ExpectUniqueSample(kFeaturesHistogramName, feature, 1); + histogram_tester.ExpectUniqueSample(kFeaturesHistogramName, + static_cast<int>(feature), 1); histogram_tester.ExpectUniqueSample( kCSSHistogramName, UseCounter::MapCSSPropertyIdToCSSSampleIdForHistogram(property), 1); @@ -301,14 +302,15 @@ void ExpectHistograms(const HistogramTester& histogram_tester, int visits_count, - UseCounter::Feature feature, + WebFeature feature, int feature_count, CSSPropertyID property, int property_count) { histogram_tester.ExpectBucketCount(kFeaturesHistogramName, - UseCounter::kPageVisits, visits_count); - histogram_tester.ExpectBucketCount(kFeaturesHistogramName, feature, - feature_count); + static_cast<int>(WebFeature::kPageVisits), + visits_count); + histogram_tester.ExpectBucketCount(kFeaturesHistogramName, + static_cast<int>(feature), feature_count); histogram_tester.ExpectTotalCount(kFeaturesHistogramName, visits_count + feature_count); histogram_tester.ExpectBucketCount(kCSSHistogramName, 1, visits_count); @@ -325,81 +327,81 @@ HistogramTester histogram_tester; // Counters triggered before any load are always reported. - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 0, UseCounter::kFetch, 1, + ExpectHistograms(histogram_tester, 0, WebFeature::kFetch, 1, CSSPropertyFontWeight, 1); // Loading an internal page doesn't bump PageVisits and metrics not reported. use_counter.DidCommitLoad(URLTestHelpers::ToKURL(kInternalUrl)); - EXPECT_FALSE(use_counter.HasRecordedMeasurement(UseCounter::kFetch)); + EXPECT_FALSE(use_counter.HasRecordedMeasurement(WebFeature::kFetch)); EXPECT_FALSE(use_counter.IsCounted(CSSPropertyFontWeight)); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 0, UseCounter::kFetch, 1, + ExpectHistograms(histogram_tester, 0, WebFeature::kFetch, 1, CSSPropertyFontWeight, 1); // But the fact that the features were seen is still known. - EXPECT_TRUE(use_counter.HasRecordedMeasurement(UseCounter::kFetch)); + EXPECT_TRUE(use_counter.HasRecordedMeasurement(WebFeature::kFetch)); EXPECT_TRUE(use_counter.IsCounted(CSSPropertyFontWeight)); // Inspector muting then unmuting doesn't change the behavior. use_counter.MuteForInspector(); use_counter.UnmuteForInspector(); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 0, UseCounter::kFetch, 1, + ExpectHistograms(histogram_tester, 0, WebFeature::kFetch, 1, CSSPropertyFontWeight, 1); // If we now load a real web page, metrics are reported again. use_counter.DidCommitLoad(URLTestHelpers::ToKURL("http://foo.com/")); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 1, UseCounter::kFetch, 2, + ExpectHistograms(histogram_tester, 1, WebFeature::kFetch, 2, CSSPropertyFontWeight, 2); // HTTPs URLs are the same. use_counter.DidCommitLoad(URLTestHelpers::ToKURL(kHttpsUrl)); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 2, UseCounter::kFetch, 3, + ExpectHistograms(histogram_tester, 2, WebFeature::kFetch, 3, CSSPropertyFontWeight, 3); // Extensions aren't counted. use_counter.DidCommitLoad(URLTestHelpers::ToKURL(kExtensionUrl)); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 2, UseCounter::kFetch, 3, + ExpectHistograms(histogram_tester, 2, WebFeature::kFetch, 3, CSSPropertyFontWeight, 3); // Nor is devtools use_counter.DidCommitLoad( URLTestHelpers::ToKURL("chrome-devtools://1238ba908adf/")); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 2, UseCounter::kFetch, 3, + ExpectHistograms(histogram_tester, 2, WebFeature::kFetch, 3, CSSPropertyFontWeight, 3); // Nor are data URLs use_counter.DidCommitLoad( URLTestHelpers::ToKURL("data:text/plain,thisisaurl")); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 2, UseCounter::kFetch, 3, + ExpectHistograms(histogram_tester, 2, WebFeature::kFetch, 3, CSSPropertyFontWeight, 3); // Or empty URLs (a main frame with no Document) use_counter.DidCommitLoad(KURL()); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 2, UseCounter::kFetch, 3, + ExpectHistograms(histogram_tester, 2, WebFeature::kFetch, 3, CSSPropertyFontWeight, 3); // But file URLs are use_counter.DidCommitLoad(URLTestHelpers::ToKURL("file:///c/autoexec.bat")); - use_counter.RecordMeasurement(UseCounter::kFetch); + use_counter.RecordMeasurement(WebFeature::kFetch); use_counter.Count(kHTMLStandardMode, CSSPropertyFontWeight); - ExpectHistograms(histogram_tester, 3, UseCounter::kFetch, 4, + ExpectHistograms(histogram_tester, 3, WebFeature::kFetch, 4, CSSPropertyFontWeight, 4); } @@ -420,7 +422,7 @@ TEST_F(DeprecationTest, InspectorDisablesDeprecation) { // The specific feature we use here isn't important. - UseCounter::Feature feature = UseCounter::Feature::kCSSDeepCombinator; + WebFeature feature = WebFeature::kCSSDeepCombinator; CSSPropertyID property = CSSPropertyFontWeight; EXPECT_FALSE(deprecation_.IsSuppressed(property));
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index a3a696c..281ca456 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -841,7 +841,7 @@ if (result && !CheckSource(OperativeDirective(base_uri_.Get()), url, redirect_status)) { UseCounter::Count(policy_->GetDocument(), - UseCounter::kBaseWouldBeBlockedByDefaultSrc); + WebFeature::kBaseWouldBeBlockedByDefaultSrc); } return result; @@ -878,7 +878,7 @@ child_src_ && CheckSource(child_src_, url, redirect_status)) { Deprecation::CountDeprecation( policy_->GetDocument(), - UseCounter::kChildSrcAllowedWorkerThatScriptSrcBlocked); + WebFeature::kChildSrcAllowedWorkerThatScriptSrcBlocked); return true; }
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPSource.cpp b/third_party/WebKit/Source/core/frame/csp/CSPSource.cpp index 5aba84c6..3fb9dbfd 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPSource.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPSource.cpp
@@ -95,7 +95,7 @@ // relying on that behavior. if (document && equal_hosts) { UseCounter::Count(*document, - UseCounter::kCSPSourceWildcardWouldMatchExactHost); + WebFeature::kCSPSourceWildcardWouldMatchExactHost); } } else { // host-part = 1*host-char *( "." 1*host-char )
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 5ddc38f..8619a85 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -126,8 +126,8 @@ UseCounter::Count( element->GetDocument(), - nonceable ? UseCounter::kCleanScriptElementWithNonce - : UseCounter::kPotentiallyInjectedScriptElementWithNonce); + nonceable ? WebFeature::kCleanScriptElementWithNonce + : WebFeature::kPotentiallyInjectedScriptElementWithNonce); // This behavior is locked behind the experimental flag for the moment; if we // decide to ship it, drop this check. https://crbug.com/639293 @@ -136,16 +136,15 @@ nonceable; } -static UseCounter::Feature GetUseCounterType( - ContentSecurityPolicyHeaderType type) { +static WebFeature GetUseCounterType(ContentSecurityPolicyHeaderType type) { switch (type) { case kContentSecurityPolicyHeaderTypeEnforce: - return UseCounter::kContentSecurityPolicy; + return WebFeature::kContentSecurityPolicy; case kContentSecurityPolicyHeaderTypeReport: - return UseCounter::kContentSecurityPolicyReportOnly; + return WebFeature::kContentSecurityPolicyReportOnly; } NOTREACHED(); - return UseCounter::kNumberOfFeatures; + return WebFeature::kNumberOfFeatures; } ContentSecurityPolicy::ContentSecurityPolicy() @@ -181,7 +180,7 @@ // error messages, then poke at histograms. Document* document = this->GetDocument(); if (sandbox_mask_ != kSandboxNone) { - UseCounter::Count(execution_context_, UseCounter::kSandboxViaCSP); + UseCounter::Count(execution_context_, WebFeature::kSandboxViaCSP); if (document) document->EnforceSandboxFlags(sandbox_mask_); else @@ -201,7 +200,7 @@ if (insecure_request_policy_ & kUpgradeInsecureRequests) { UseCounter::Count(execution_context_, - UseCounter::kUpgradeInsecureRequestsEnabled); + WebFeature::kUpgradeInsecureRequestsEnabled); if (!execution_context_->Url().Host().IsEmpty()) { execution_context_->GetSecurityContext().AddInsecureNavigationUpgrade( execution_context_->Url().Host().Impl()->GetHash()); @@ -216,7 +215,7 @@ UseCounter::Count(execution_context_, GetUseCounterType(policy->HeaderType())); if (policy->AllowDynamic()) - UseCounter::Count(execution_context_, UseCounter::kCSPWithStrictDynamic); + UseCounter::Count(execution_context_, WebFeature::kCSPWithStrictDynamic); } // We disable 'eval()' even in the case of report-only policies, and rely on @@ -758,8 +757,8 @@ UseCounter::Count( GetDocument(), parser_disposition == kParserInserted - ? UseCounter::kScriptWithCSPBypassingSchemeParserInserted - : UseCounter::kScriptWithCSPBypassingSchemeNotParserInserted); + ? WebFeature::kScriptWithCSPBypassingSchemeParserInserted + : WebFeature::kScriptWithCSPBypassingSchemeNotParserInserted); } return IsAllowedByAll<&CSPDirectiveList::AllowScriptFromSource>( policies_, url, nonce, hashes, parser_disposition, redirect_status, @@ -978,7 +977,7 @@ // impact of this backwards-incompatible change. // TODO(mkwst): We reverted this. if (Document* document = this->GetDocument()) { - UseCounter::Count(*document, UseCounter::kWorkerSubjectToCSP); + UseCounter::Count(*document, WebFeature::kWorkerSubjectToCSP); if (IsAllowedByAll<&CSPDirectiveList::AllowWorkerFromSource>( policies_, url, redirect_status, SecurityViolationReportingPolicy::kSuppressReporting, @@ -989,7 +988,7 @@ SecurityViolationReportingPolicy::kSuppressReporting, check_header_type)) { UseCounter::Count(*document, - UseCounter::kWorkerAllowedByChildBlockedByScript); + WebFeature::kWorkerAllowedByChildBlockedByScript); } }
diff --git a/third_party/WebKit/Source/core/html/FormData.cpp b/third_party/WebKit/Source/core/html/FormData.cpp index c2e5cb1d..8314c4ea 100644 --- a/third_party/WebKit/Source/core/html/FormData.cpp +++ b/third_party/WebKit/Source/core/html/FormData.cpp
@@ -108,7 +108,7 @@ const String& filename) { if (!blob) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kFormDataAppendNull); + WebFeature::kFormDataAppendNull); } append(name, blob, filename); }
diff --git a/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp b/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp index a1e403c..8a230f1b 100644 --- a/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp
@@ -310,7 +310,7 @@ if (GetDocument().Fetcher()->Archive()) return; - UseCounter::Count(GetDocument(), UseCounter::kHTMLAnchorElementPingAttribute); + UseCounter::Count(GetDocument(), WebFeature::kHTMLAnchorElementPingAttribute); SpaceSplitString ping_urls(ping_value); for (unsigned i = 0; i < ping_urls.size(); i++) @@ -328,7 +328,7 @@ if (!isConnected()) { UseCounter::Count(GetDocument(), - UseCounter::kAnchorClickDispatchForNonConnectedNode); + WebFeature::kAnchorClickDispatchForNonConnectedNode); } StringBuilder url; @@ -353,7 +353,7 @@ kSupportReferrerPolicyLegacyKeywords, &policy) && !HasRel(kRelationNoReferrer)) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLAnchorElementReferrerPolicyAttribute); + WebFeature::kHTMLAnchorElementReferrerPolicyAttribute); request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( policy, completed_url, GetDocument().OutgoingReferrer())); }
diff --git a/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp b/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp index 791a7363..5fc8c30 100644 --- a/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp
@@ -193,7 +193,7 @@ EventParameterName())); } else if (name == onselectionchangeAttr) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLBodyElementOnSelectionChangeAttribute); + WebFeature::kHTMLBodyElementOnSelectionChangeAttribute); GetDocument().SetAttributeEventListener( EventTypeNames::selectionchange, CreateAttributeEventListener(GetDocument().GetFrame(), name, value,
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index dd6658a..d14730b3 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -145,7 +145,7 @@ did_fail_to_create_image_buffer_(false), image_buffer_is_clear_(false) { CanvasMetrics::CountCanvasContextUsage(CanvasMetrics::kCanvasCreated); - UseCounter::Count(document, UseCounter::kHTMLCanvasElement); + UseCounter::Count(document, WebFeature::kHTMLCanvasElement); } DEFINE_NODE_FACTORY(HTMLCanvasElement)
diff --git a/third_party/WebKit/Source/core/html/HTMLContentElement.cpp b/third_party/WebKit/Source/core/html/HTMLContentElement.cpp index 2298b52a..a6453a42 100644 --- a/third_party/WebKit/Source/core/html/HTMLContentElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLContentElement.cpp
@@ -52,7 +52,7 @@ should_parse_select_(false), is_valid_selector_(true), filter_(filter) { - UseCounter::Count(document, UseCounter::kHTMLContentElement); + UseCounter::Count(document, WebFeature::kHTMLContentElement); } HTMLContentElement::~HTMLContentElement() {}
diff --git a/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp b/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp index 8075ff6..0c931c3 100644 --- a/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp
@@ -43,7 +43,7 @@ : HTMLElement(HTMLNames::datalistTag, document) {} HTMLDataListElement* HTMLDataListElement::Create(Document& document) { - UseCounter::Count(document, UseCounter::kDataListElement); + UseCounter::Count(document, WebFeature::kDataListElement); return new HTMLDataListElement(document); }
diff --git a/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp b/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp index 655ff4e..df96443f 100644 --- a/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp
@@ -75,7 +75,7 @@ HTMLDetailsElement::HTMLDetailsElement(Document& document) : HTMLElement(detailsTag, document), is_open_(false) { - UseCounter::Count(document, UseCounter::kDetailsElement); + UseCounter::Count(document, WebFeature::kDetailsElement); } HTMLDetailsElement::~HTMLDetailsElement() {}
diff --git a/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp b/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp index aa1769a..1d9e1a6 100644 --- a/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
@@ -96,7 +96,7 @@ centering_mode_(kNotCentered), centered_position_(0), return_value_("") { - UseCounter::Count(document, UseCounter::kDialogElement); + UseCounter::Count(document, WebFeature::kDialogElement); } DEFINE_NODE_FACTORY(HTMLDialogElement) @@ -171,7 +171,7 @@ // See comment in |Fullscreen::RequestFullscreen|. if (Fullscreen::IsInFullscreenElementStack(*this)) { UseCounter::Count(GetDocument(), - UseCounter::kShowModalForElementInFullscreenStack); + WebFeature::kShowModalForElementInFullscreenStack); } GetDocument().AddToTopLayer(this);
diff --git a/third_party/WebKit/Source/core/html/HTMLElement.cpp b/third_party/WebKit/Source/core/html/HTMLElement.cpp index 7504a48..cdcb459 100644 --- a/third_party/WebKit/Source/core/html/HTMLElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLElement.cpp
@@ -188,11 +188,11 @@ // FIXME: Remove the following UseCounter code when we collect enough // data. - UseCounter::Count(GetDocument(), UseCounter::kLangAttribute); + UseCounter::Count(GetDocument(), WebFeature::kLangAttribute); if (isHTMLHtmlElement(*this)) - UseCounter::Count(GetDocument(), UseCounter::kLangAttributeOnHTML); + UseCounter::Count(GetDocument(), WebFeature::kLangAttributeOnHTML); else if (isHTMLBodyElement(*this)) - UseCounter::Count(GetDocument(), UseCounter::kLangAttributeOnBody); + UseCounter::Count(GetDocument(), WebFeature::kLangAttributeOnBody); String html_language = value.GetString(); size_t first_separator = html_language.find('-'); if (first_separator != kNotFound) @@ -206,7 +206,7 @@ ui_language = ui_language.Left(first_separator); if (!DeprecatedEqualIgnoringCase(html_language, ui_language)) { UseCounter::Count(GetDocument(), - UseCounter::kLangAttributeDoesNotMatchToUILocale); + WebFeature::kLangAttributeDoesNotMatchToUILocale); } } else { // The empty string means the language is explicitly unknown. @@ -248,10 +248,10 @@ CSSValueBreakWord); AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace); - UseCounter::Count(GetDocument(), UseCounter::kContentEditableTrue); + UseCounter::Count(GetDocument(), WebFeature::kContentEditableTrue); if (HasTagName(htmlTag)) { UseCounter::Count(GetDocument(), - UseCounter::kContentEditableTrueOnHTML); + WebFeature::kContentEditableTrueOnHTML); } } else if (DeprecatedEqualIgnoringCase(value, "plaintext-only")) { AddPropertyToPresentationAttributeStyle( @@ -261,7 +261,7 @@ AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace); UseCounter::Count(GetDocument(), - UseCounter::kContentEditablePlainTextOnly); + WebFeature::kContentEditablePlainTextOnly); } else if (DeprecatedEqualIgnoringCase(value, "false")) { AddPropertyToPresentationAttributeStyle( style, CSSPropertyWebkitUserModify, CSSValueReadOnly); @@ -270,7 +270,7 @@ AddPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay, CSSValueNone); } else if (name == draggableAttr) { - UseCounter::Count(GetDocument(), UseCounter::kDraggableAttribute); + UseCounter::Count(GetDocument(), WebFeature::kDraggableAttribute); if (DeprecatedEqualIgnoringCase(value, "true")) { AddPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement); @@ -465,7 +465,7 @@ } else if (params.name == langAttr) { PseudoStateChanged(CSSSelector::kPseudoLang); } else if (params.name == inertAttr) { - UseCounter::Count(GetDocument(), UseCounter::kInertAttribute); + UseCounter::Count(GetDocument(), WebFeature::kInertAttribute); } else if (params.name == nonceAttr) { if (params.new_value != g_empty_atom) setNonce(params.new_value); @@ -942,7 +942,7 @@ return; if (property_id == CSSPropertyWidth && (dimension.IsPercentage() || dimension.IsRelative())) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLElementDeprecatedWidth); + UseCounter::Count(GetDocument(), WebFeature::kHTMLElementDeprecatedWidth); } if (dimension.IsRelative()) return;
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp index 1a9bfaa8..c23b893 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
@@ -154,7 +154,7 @@ const QualifiedName& name = params.name; if (name == formAttr) { FormAttributeChanged(); - UseCounter::Count(GetDocument(), UseCounter::kFormAttribute); + UseCounter::Count(GetDocument(), WebFeature::kFormAttribute); } else if (name == readonlyAttr) { if (params.old_value.IsNull() != params.new_value.IsNull()) { SetNeedsWillValidateCheck(); @@ -167,10 +167,10 @@ } else if (name == requiredAttr) { if (params.old_value.IsNull() != params.new_value.IsNull()) RequiredAttributeChanged(); - UseCounter::Count(GetDocument(), UseCounter::kRequiredAttribute); + UseCounter::Count(GetDocument(), WebFeature::kRequiredAttribute); } else if (name == autofocusAttr) { HTMLElement::ParseAttribute(params); - UseCounter::Count(GetDocument(), UseCounter::kAutoFocusAttribute); + UseCounter::Count(GetDocument(), WebFeature::kAutoFocusAttribute); } else { HTMLElement::ParseAttribute(params); }
diff --git a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp index 64cde65c..f198a7e 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
@@ -76,7 +76,7 @@ was_demoted_(false) {} HTMLFormElement* HTMLFormElement::Create(Document& document) { - UseCounter::Count(document, UseCounter::kFormElement); + UseCounter::Count(document, WebFeature::kFormElement); return new HTMLFormElement(document); } @@ -236,7 +236,7 @@ } bool HTMLFormElement::ValidateInteractively() { - UseCounter::Count(GetDocument(), UseCounter::kFormValidationStarted); + UseCounter::Count(GetDocument(), WebFeature::kFormValidationStarted); for (const auto& element : ListedElements()) { if (element->IsFormControlElement()) ToHTMLFormControlElement(element)->HideVisibleValidationMessage(); @@ -247,7 +247,7 @@ &unhandled_invalid_controls, kCheckValidityDispatchInvalidEvent)) return true; UseCounter::Count(GetDocument(), - UseCounter::kFormValidationAbortedSubmission); + WebFeature::kFormValidationAbortedSubmission); // Because the form has invalid controls, we abort the form submission and // show a validation message on a focusable form control. @@ -260,7 +260,7 @@ if (unhandled->IsFocusable()) { unhandled->ShowValidationMessage(); UseCounter::Count(GetDocument(), - UseCounter::kFormValidationShowedMessage); + WebFeature::kFormValidationShowedMessage); break; } } @@ -307,7 +307,7 @@ if (element->IsFormControlElement() && ToHTMLFormControlElement(element)->BlocksFormSubmission()) { UseCounter::Count(GetDocument(), - UseCounter::kFormSubmittedWithUnclosedFormControl); + WebFeature::kFormSubmittedWithUnclosedFormControl); if (RuntimeEnabledFeatures::UnclosedFormControlIsInvalidEnabled()) { String tag_name = ToHTMLFormControlElement(element)->tagName(); GetDocument().AddConsoleMessage(ConsoleMessage::Create( @@ -331,7 +331,7 @@ if (submit_button && submit_button->FormNoValidate()) skip_validation = true; - UseCounter::Count(GetDocument(), UseCounter::kFormSubmissionStarted); + UseCounter::Count(GetDocument(), WebFeature::kFormSubmissionStarted); // Interactive validation must be done before dispatching the submit event. if (!skip_validation && !ValidateInteractively()) return; @@ -467,11 +467,11 @@ if (!target_frame->GetPage()) return; - UseCounter::Count(GetDocument(), UseCounter::kFormsSubmitted); + UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), - UseCounter::kMixedContentFormsSubmitted); + WebFeature::kMixedContentFormsSubmitted); } // TODO(lukasza): Investigate if the code below can uniformly handle remote @@ -530,7 +530,7 @@ if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), action_url)) { UseCounter::Count(GetDocument().GetFrame(), - UseCounter::kMixedContentFormPresent); + WebFeature::kMixedContentFormPresent); } } else if (name == targetAttr) { attributes_.SetTarget(params.new_value); @@ -582,7 +582,7 @@ if (!did_finish_parsing_children_) return; has_elements_associated_by_parser_ = true; - UseCounter::Count(GetDocument(), UseCounter::kFormAssociationByParser); + UseCounter::Count(GetDocument(), WebFeature::kFormAssociationByParser); } HTMLFormControlsCollection* HTMLFormElement::elements() { @@ -774,7 +774,7 @@ } else if (element_from_past && named_items.IsEmpty()) { named_items.push_back(element_from_past); UseCounter::Count(GetDocument(), - UseCounter::kFormNameAccessForPastNamesMap); + WebFeature::kFormNameAccessForPastNamesMap); } } @@ -818,14 +818,14 @@ !elements.IsEmpty() && isHTMLImageElement(*elements.front()); if (only_match_img) { UseCounter::Count(GetDocument(), - UseCounter::kFormNameAccessForImageElement); + WebFeature::kFormNameAccessForImageElement); // The following code has performance impact, but it should be small // because <img> access via <form> name getter is rarely used. for (auto& element : elements) { if (isHTMLImageElement(*element) && !element->IsDescendantOf(this)) { UseCounter::Count( GetDocument(), - UseCounter::kFormNameAccessForNonDescendantImageElement); + WebFeature::kFormNameAccessForNonDescendantImageElement); break; } } @@ -840,7 +840,7 @@ void HTMLFormElement::SetDemoted(bool demoted) { if (demoted) - UseCounter::Count(GetDocument(), UseCounter::kDemotedFormElement); + UseCounter::Count(GetDocument(), WebFeature::kDemotedFormElement); was_demoted_ = demoted; }
diff --git a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp index 6ab11c6c..112bed79 100644 --- a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
@@ -135,14 +135,14 @@ kOtherMessageSource, kErrorMessageLevel, "Error while parsing the 'sandbox' attribute: " + invalid_tokens)); } - UseCounter::Count(GetDocument(), UseCounter::kSandboxViaIFrame); + UseCounter::Count(GetDocument(), WebFeature::kSandboxViaIFrame); } else if (name == referrerpolicyAttr) { referrer_policy_ = kReferrerPolicyDefault; if (!value.IsNull()) { SecurityPolicy::ReferrerPolicyFromString( value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_); UseCounter::Count(GetDocument(), - UseCounter::kHTMLIFrameElementReferrerPolicyAttribute); + WebFeature::kHTMLIFrameElementReferrerPolicyAttribute); } } else if (name == allowfullscreenAttr) { bool old_allow_fullscreen = allow_fullscreen_; @@ -153,7 +153,7 @@ if (allow_fullscreen_ && ContentFrame()) { UseCounter::Count( GetDocument(), - UseCounter:: + WebFeature:: kHTMLIFrameElementAllowfullscreenAttributeSetAfterContentLoad); } FrameOwnerPropertiesChanged();
diff --git a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp index 38907b23..202313fe2 100644 --- a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
@@ -269,9 +269,9 @@ bool intrinsic_sizing_viewport_dependant = false; if (candidate.GetResourceWidth() > 0) { intrinsic_sizing_viewport_dependant = true; - UseCounter::Count(GetDocument(), UseCounter::kSrcsetWDescriptor); + UseCounter::Count(GetDocument(), WebFeature::kSrcsetWDescriptor); } else if (!candidate.SrcOrigin()) { - UseCounter::Count(GetDocument(), UseCounter::kSrcsetXDescriptor); + UseCounter::Count(GetDocument(), WebFeature::kSrcsetXDescriptor); } if (GetLayoutObject() && GetLayoutObject()->IsImage()) { LayoutImageItem(ToLayoutImage(GetLayoutObject())) @@ -320,7 +320,7 @@ params.new_value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_); UseCounter::Count(GetDocument(), - UseCounter::kHTMLImageElementReferrerPolicyAttribute); + WebFeature::kHTMLImageElementReferrerPolicyAttribute); } } else { HTMLElement::ParseAttribute(params); @@ -364,7 +364,7 @@ HTMLSourceElement* source = toHTMLSourceElement(child); if (!source->FastGetAttribute(srcAttr).IsNull()) { Deprecation::CountDeprecation(GetDocument(), - UseCounter::kPictureSourceSrc); + WebFeature::kPictureSourceSrc); } String srcset = source->FastGetAttribute(srcsetAttr); if (srcset.IsEmpty()) @@ -727,7 +727,7 @@ String sizes = element.FastGetAttribute(sizesAttr); bool exists = !sizes.IsNull(); if (exists) - UseCounter::Count(current_document, UseCounter::kSizes); + UseCounter::Count(current_document, WebFeature::kSizes); source_size = SizesAttributeParser(MediaValuesDynamic::Create(current_document), sizes) .length();
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp index 6cce7454..c946452 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -768,29 +768,29 @@ EventTypeNames::search, CreateAttributeEventListener(this, name, value, EventParameterName())); } else if (name == incrementalAttr) { - UseCounter::Count(GetDocument(), UseCounter::kIncrementalAttribute); + UseCounter::Count(GetDocument(), WebFeature::kIncrementalAttribute); } else if (name == minAttr) { input_type_view_->MinOrMaxAttributeChanged(); input_type_->SanitizeValueInResponseToMinOrMaxAttributeChange(); input_type_->InRangeChanged(); SetNeedsValidityCheck(); - UseCounter::Count(GetDocument(), UseCounter::kMinAttribute); + UseCounter::Count(GetDocument(), WebFeature::kMinAttribute); } else if (name == maxAttr) { input_type_view_->MinOrMaxAttributeChanged(); input_type_->SanitizeValueInResponseToMinOrMaxAttributeChange(); input_type_->InRangeChanged(); SetNeedsValidityCheck(); - UseCounter::Count(GetDocument(), UseCounter::kMaxAttribute); + UseCounter::Count(GetDocument(), WebFeature::kMaxAttribute); } else if (name == multipleAttr) { input_type_view_->MultipleAttributeChanged(); SetNeedsValidityCheck(); } else if (name == stepAttr) { input_type_view_->StepAttributeChanged(); SetNeedsValidityCheck(); - UseCounter::Count(GetDocument(), UseCounter::kStepAttribute); + UseCounter::Count(GetDocument(), WebFeature::kStepAttribute); } else if (name == patternAttr) { SetNeedsValidityCheck(); - UseCounter::Count(GetDocument(), UseCounter::kPatternAttribute); + UseCounter::Count(GetDocument(), WebFeature::kPatternAttribute); } else if (name == readonlyAttr) { TextControlElement::ParseAttribute(params); input_type_view_->ReadonlyAttributeChanged(); @@ -800,10 +800,10 @@ ResetListAttributeTargetObserver(); ListAttributeTargetChanged(); } - UseCounter::Count(GetDocument(), UseCounter::kListAttribute); + UseCounter::Count(GetDocument(), WebFeature::kListAttribute); } else if (name == webkitdirectoryAttr) { TextControlElement::ParseAttribute(params); - UseCounter::Count(GetDocument(), UseCounter::kPrefixedDirectoryAttribute); + UseCounter::Count(GetDocument(), WebFeature::kPrefixedDirectoryAttribute); } else { if (name == formactionAttr) LogUpdateAttributeIfIsolatedWorldAndInDocument("input", params);
diff --git a/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp b/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp index e80125c6..df06871d 100644 --- a/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
@@ -62,7 +62,7 @@ if (!element.IsFormControlElement()) { UseCounter::Count( GetDocument(), - UseCounter::kHTMLLabelElementControlForNonFormAssociatedElement); + WebFeature::kHTMLLabelElementControlForNonFormAssociatedElement); } return &element; } @@ -79,7 +79,7 @@ if (!element->IsFormControlElement()) { UseCounter::Count( GetDocument(), - UseCounter::kHTMLLabelElementControlForNonFormAssociatedElement); + WebFeature::kHTMLLabelElementControlForNonFormAssociatedElement); } return ToLabelableElement(element); }
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp index 7c3d856..2e459e0 100644 --- a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
@@ -86,7 +86,7 @@ SecurityPolicy::ReferrerPolicyFromString( value, kDoNotSupportReferrerPolicyLegacyKeywords, &referrer_policy_); UseCounter::Count(GetDocument(), - UseCounter::kHTMLLinkElementReferrerPolicyAttribute); + WebFeature::kHTMLLinkElementReferrerPolicyAttribute); } } else if (name == sizesAttr) { sizes_->DidUpdateAttributeValue(params.old_value, value); @@ -103,7 +103,7 @@ scope_ = value; Process(); } else if (name == disabledAttr) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLLinkElementDisabled); + UseCounter::Count(GetDocument(), WebFeature::kHTMLLinkElementDisabled); if (LinkStyle* link = GetLinkStyle()) link->SetDisabledState(!value.IsNull()); } else { @@ -154,7 +154,7 @@ } else { LinkStyle* link = LinkStyle::Create(this); if (FastHasAttribute(disabledAttr)) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLLinkElementDisabled); + UseCounter::Count(GetDocument(), WebFeature::kHTMLLinkElementDisabled); link->SetDisabledState(true); } link_ = link;
diff --git a/third_party/WebKit/Source/core/html/HTMLMapElement.cpp b/third_party/WebKit/Source/core/html/HTMLMapElement.cpp index 672873ae..eac6a12 100644 --- a/third_party/WebKit/Source/core/html/HTMLMapElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
@@ -37,7 +37,7 @@ inline HTMLMapElement::HTMLMapElement(Document& document) : HTMLElement(mapTag, document) { - UseCounter::Count(document, UseCounter::kMapElement); + UseCounter::Count(document, WebFeature::kMapElement); } DEFINE_NODE_FACTORY(HTMLMapElement)
diff --git a/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp b/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp index bacf866..d8cd66d3 100644 --- a/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
@@ -49,7 +49,7 @@ inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document) : HTMLElement(HTMLNames::marqueeTag, document) { - UseCounter::Count(document, UseCounter::kHTMLMarqueeElement); + UseCounter::Count(document, WebFeature::kHTMLMarqueeElement); } HTMLMarqueeElement* HTMLMarqueeElement::Create(Document& document) {
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index 661ba46..02d3af4 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -518,7 +518,7 @@ SetHasCustomStyleCallbacks(); AddElementToDocumentMap(this, &document); - UseCounter::Count(document, UseCounter::kHTMLMediaElement); + UseCounter::Count(document, WebFeature::kHTMLMediaElement); } HTMLMediaElement::~HTMLMediaElement() { @@ -623,11 +623,11 @@ } } else if (name == controlsAttr) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementControlsAttribute); + WebFeature::kHTMLMediaElementControlsAttribute); UpdateControlsVisibility(); } else if (name == controlslistAttr) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementControlsListAttribute); + WebFeature::kHTMLMediaElementControlsListAttribute); if (params.old_value != params.new_value) { controls_list_->DidUpdateAttributeValue(params.old_value, params.new_value); @@ -640,7 +640,7 @@ // This attribute is an extension described in the Remote Playback API spec. // Please see: https://w3c.github.io/remote-playback UseCounter::Count(GetDocument(), - UseCounter::kDisableRemotePlaybackAttribute); + WebFeature::kDisableRemotePlaybackAttribute); if (params.old_value != params.new_value) { if (web_media_player_) { web_media_player_->RequestRemotePlaybackDisabled( @@ -674,7 +674,7 @@ HTMLElement::InsertedInto(insertion_point); if (insertion_point->isConnected()) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLMediaElementInDocument); + UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementInDocument); if ((!getAttribute(srcAttr).IsEmpty() || src_object_) && network_state_ == kNetworkEmpty) { ignore_preload_none_ = false; @@ -920,7 +920,7 @@ // This is where that change would have an effect, and it is measured to // verify the assumption that it's a very rare situation. UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementLoadNetworkEmptyNotPaused); + WebFeature::kHTMLMediaElementLoadNetworkEmptyNotPaused); } // 7 - Set the playbackRate attribute to the value of the defaultPlaybackRate @@ -1779,7 +1779,7 @@ if (!jumped && initial_playback_position > 0) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementSeekToFragmentStart); + WebFeature::kHTMLMediaElementSeekToFragmentStart); Seek(initial_playback_position); jumped = true; } @@ -2177,7 +2177,7 @@ WebMediaPlayer::Preload HTMLMediaElement::PreloadType() const { const AtomicString& preload = FastGetAttribute(preloadAttr); if (DeprecatedEqualIgnoringCase(preload, "none")) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLMediaElementPreloadNone); + UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadNone); return WebMediaPlayer::kPreloadNone; } @@ -2189,25 +2189,25 @@ (current_src_.Protocol() != "blob" && current_src_.Protocol() != "data" && current_src_.Protocol() != "file")) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementPreloadForcedNone); + WebFeature::kHTMLMediaElementPreloadForcedNone); return WebMediaPlayer::kPreloadNone; } if (DeprecatedEqualIgnoringCase(preload, "metadata")) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementPreloadMetadata); + WebFeature::kHTMLMediaElementPreloadMetadata); return WebMediaPlayer::kPreloadMetaData; } // Force preload to 'metadata' on cellular connections. if (GetNetworkStateNotifier().IsCellularConnectionType()) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementPreloadForcedMetadata); + WebFeature::kHTMLMediaElementPreloadForcedMetadata); return WebMediaPlayer::kPreloadMetaData; } if (DeprecatedEqualIgnoringCase(preload, "auto")) { - UseCounter::Count(GetDocument(), UseCounter::kHTMLMediaElementPreloadAuto); + UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadAuto); return WebMediaPlayer::kPreloadAuto; } @@ -2220,7 +2220,7 @@ // TODO(foolip): Try to make "metadata" the default preload state: // https://crbug.com/310450 - UseCounter::Count(GetDocument(), UseCounter::kHTMLMediaElementPreloadDefault); + UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadDefault); return WebMediaPlayer::kPreloadAuto; } @@ -2520,7 +2520,7 @@ fragment_end_time_ = std::numeric_limits<double>::quiet_NaN(); if (!paused_) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLMediaElementPauseAtFragmentEnd); + WebFeature::kHTMLMediaElementPauseAtFragmentEnd); // changes paused to true and fires a simple event named pause at the // media element. PauseInternal(); @@ -3858,7 +3858,7 @@ void HTMLMediaElement::VideoWillBeDrawnToCanvas() const { DCHECK(IsHTMLVideoElement()); - UseCounter::Count(GetDocument(), UseCounter::kVideoInCanvas); + UseCounter::Count(GetDocument(), WebFeature::kVideoInCanvas); autoplay_policy_->VideoWillBeDrawnToCanvas(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp b/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp index 3208dce..fd8b57db 100644 --- a/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp
@@ -37,7 +37,7 @@ HTMLMeterElement::HTMLMeterElement(Document& document) : LabelableElement(meterTag, document) { - UseCounter::Count(document, UseCounter::kMeterElement); + UseCounter::Count(document, WebFeature::kMeterElement); } HTMLMeterElement::~HTMLMeterElement() {} @@ -52,11 +52,11 @@ switch (style.Appearance()) { case kMeterPart: UseCounter::Count(GetDocument(), - UseCounter::kMeterElementWithMeterAppearance); + WebFeature::kMeterElementWithMeterAppearance); break; case kNoControlPart: UseCounter::Count(GetDocument(), - UseCounter::kMeterElementWithNoneAppearance); + WebFeature::kMeterElementWithNoneAppearance); break; default: break;
diff --git a/third_party/WebKit/Source/core/html/HTMLOListElement.cpp b/third_party/WebKit/Source/core/html/HTMLOListElement.cpp index 0a0c69d..abf84ba2 100644 --- a/third_party/WebKit/Source/core/html/HTMLOListElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLOListElement.cpp
@@ -103,7 +103,7 @@ if (is_reversed_) { UseCounter::Count( GetDocument(), - UseCounter::kHTMLOListElementStartGetterReversedWithoutStartAttribute); + WebFeature::kHTMLOListElementStartGetterReversedWithoutStartAttribute); return ItemCount(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLPictureElement.cpp b/third_party/WebKit/Source/core/html/HTMLPictureElement.cpp index 2fcfdf1..52c474aa 100644 --- a/third_party/WebKit/Source/core/html/HTMLPictureElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLPictureElement.cpp
@@ -51,7 +51,7 @@ Node::InsertionNotificationRequest HTMLPictureElement::InsertedInto( ContainerNode* insertion_point) { - UseCounter::Count(GetDocument(), UseCounter::kPicture); + UseCounter::Count(GetDocument(), WebFeature::kPicture); return HTMLElement::InsertedInto(insertion_point); }
diff --git a/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp b/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp index 6dea51c..bf29c2b 100644 --- a/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp
@@ -39,7 +39,7 @@ HTMLProgressElement::HTMLProgressElement(Document& document) : LabelableElement(progressTag, document), value_(nullptr) { - UseCounter::Count(document, UseCounter::kProgressElement); + UseCounter::Count(document, WebFeature::kProgressElement); } HTMLProgressElement::~HTMLProgressElement() {} @@ -54,11 +54,11 @@ const ComputedStyle& style) { if (!style.HasAppearance()) { UseCounter::Count(GetDocument(), - UseCounter::kProgressElementWithNoneAppearance); + WebFeature::kProgressElementWithNoneAppearance); return LayoutObject::CreateObject(this, style); } UseCounter::Count(GetDocument(), - UseCounter::kProgressElementWithProgressBarAppearance); + WebFeature::kProgressElementWithProgressBarAppearance); return new LayoutProgress(this); }
diff --git a/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp b/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp index fedf413..48a21ca 100644 --- a/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
@@ -101,7 +101,7 @@ !Loader()->IsScriptTypeSupported( ScriptLoader::kDisallowLegacyTypeInTypeAttribute, script_type)) { UseCounter::Count(GetDocument(), - UseCounter::kScriptElementWithInvalidTypeHasSrc); + WebFeature::kScriptElementWithInvalidTypeHasSrc); } HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("script", srcAttr);
diff --git a/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp b/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp index 2856c80..81787af 100644 --- a/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp
@@ -42,7 +42,7 @@ inline HTMLShadowElement::HTMLShadowElement(Document& document) : InsertionPoint(HTMLNames::shadowTag, document) { - UseCounter::Count(document, UseCounter::kHTMLShadowElement); + UseCounter::Count(document, WebFeature::kHTMLShadowElement); } DEFINE_NODE_FACTORY(HTMLShadowElement)
diff --git a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp index 12eec94..9303949 100644 --- a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp
@@ -49,7 +49,7 @@ inline HTMLSlotElement::HTMLSlotElement(Document& document) : HTMLElement(slotTag, document) { - UseCounter::Count(document, UseCounter::kHTMLSlotElement); + UseCounter::Count(document, WebFeature::kHTMLSlotElement); SetHasCustomStyleCallbacks(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp b/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp index 2f61954..89a91e53 100644 --- a/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp
@@ -50,13 +50,13 @@ !ParseHTMLNonNegativeInteger(col_span_value, value)) return 1; // Counting for https://github.com/whatwg/html/issues/1198 - UseCounter::Count(GetDocument(), UseCounter::kHTMLTableCellElementColspan); + UseCounter::Count(GetDocument(), WebFeature::kHTMLTableCellElementColspan); if (value > 8190) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLTableCellElementColspanGreaterThan8190); + WebFeature::kHTMLTableCellElementColspanGreaterThan8190); } else if (value > 1000) { UseCounter::Count(GetDocument(), - UseCounter::kHTMLTableCellElementColspanGreaterThan1000); + WebFeature::kHTMLTableCellElementColspanGreaterThan1000); } return std::max(1u, std::min(value, MaxColSpan())); }
diff --git a/third_party/WebKit/Source/core/html/HTMLTableElement.cpp b/third_party/WebKit/Source/core/html/HTMLTableElement.cpp index d385368..1f1b8df 100644 --- a/third_party/WebKit/Source/core/html/HTMLTableElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTableElement.cpp
@@ -319,7 +319,7 @@ if (!url.IsEmpty()) { UseCounter::Count( GetDocument(), - UseCounter::kHTMLTableElementPresentationAttributeBackground); + WebFeature::kHTMLTableElementPresentationAttributeBackground); CSSImageValue* image_value = CSSImageValue::Create(url, GetDocument().CompleteURL(url), Referrer(GetDocument().OutgoingReferrer(),
diff --git a/third_party/WebKit/Source/core/html/HTMLTablePartElement.cpp b/third_party/WebKit/Source/core/html/HTMLTablePartElement.cpp index fbd48978..eb3bb193 100644 --- a/third_party/WebKit/Source/core/html/HTMLTablePartElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTablePartElement.cpp
@@ -59,7 +59,7 @@ if (!url.IsEmpty()) { UseCounter::Count( GetDocument(), - UseCounter::kHTMLTableElementPresentationAttributeBackground); + WebFeature::kHTMLTableElementPresentationAttributeBackground); CSSImageValue* image_value = CSSImageValue::Create(url, GetDocument().CompleteURL(url), Referrer(GetDocument().OutgoingReferrer(),
diff --git a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp index e987b6e..7f5a19e 100644 --- a/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp
@@ -197,10 +197,10 @@ } else if (name == accesskeyAttr) { // ignore for the moment } else if (name == maxlengthAttr) { - UseCounter::Count(GetDocument(), UseCounter::kTextAreaMaxLength); + UseCounter::Count(GetDocument(), WebFeature::kTextAreaMaxLength); SetNeedsValidityCheck(); } else if (name == minlengthAttr) { - UseCounter::Count(GetDocument(), UseCounter::kTextAreaMinLength); + UseCounter::Count(GetDocument(), WebFeature::kTextAreaMinLength); SetNeedsValidityCheck(); } else { TextControlElement::ParseAttribute(params);
diff --git a/third_party/WebKit/Source/core/html/HTMLUnknownElement.cpp b/third_party/WebKit/Source/core/html/HTMLUnknownElement.cpp index 2af0d17c..e6a6c4a8 100644 --- a/third_party/WebKit/Source/core/html/HTMLUnknownElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLUnknownElement.cpp
@@ -12,9 +12,9 @@ Document& document) : HTMLElement(tag_name, document) { if (tag_name.LocalName() == "data") - UseCounter::Count(document, UseCounter::kDataElement); + UseCounter::Count(document, WebFeature::kDataElement); else if (tag_name.LocalName() == "time") - UseCounter::Count(document, UseCounter::kTimeElement); + UseCounter::Count(document, WebFeature::kTimeElement); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp b/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp index 1509cde..469a3ca9 100644 --- a/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp +++ b/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp
@@ -58,7 +58,7 @@ // FIXME: Why do view-source pages need to load in quirks mode? SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kViewSourceDocument); + UseCounter::Count(*this, WebFeature::kViewSourceDocument); } DocumentParser* HTMLViewSourceDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/html/ImageDocument.cpp b/third_party/WebKit/Source/core/html/ImageDocument.cpp index d9f766a..b01b94c 100644 --- a/third_party/WebKit/Source/core/html/ImageDocument.cpp +++ b/third_party/WebKit/Source/core/html/ImageDocument.cpp
@@ -212,9 +212,9 @@ : kDesktop) { SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kImageDocument); + UseCounter::Count(*this, WebFeature::kImageDocument); if (!IsInMainFrame()) - UseCounter::Count(*this, UseCounter::kImageDocumentInFrame); + UseCounter::Count(*this, WebFeature::kImageDocumentInFrame); } DocumentParser* ImageDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/html/PluginDocument.cpp b/third_party/WebKit/Source/core/html/PluginDocument.cpp index dc091db..da1de23 100644 --- a/third_party/WebKit/Source/core/html/PluginDocument.cpp +++ b/third_party/WebKit/Source/core/html/PluginDocument.cpp
@@ -166,9 +166,9 @@ : HTMLDocument(initializer, kPluginDocumentClass) { SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kPluginDocument); + UseCounter::Count(*this, WebFeature::kPluginDocument); if (!IsInMainFrame()) - UseCounter::Count(*this, UseCounter::kPluginDocumentInFrame); + UseCounter::Count(*this, WebFeature::kPluginDocumentInFrame); } DocumentParser* PluginDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/html/TextControlElement.cpp b/third_party/WebKit/Source/core/html/TextControlElement.cpp index 082ff0bf6..a70ced7 100644 --- a/third_party/WebKit/Source/core/html/TextControlElement.cpp +++ b/third_party/WebKit/Source/core/html/TextControlElement.cpp
@@ -758,12 +758,12 @@ void TextControlElement::ParseAttribute( const AttributeModificationParams& params) { if (params.name == autocapitalizeAttr) - UseCounter::Count(GetDocument(), UseCounter::kAutocapitalizeAttribute); + UseCounter::Count(GetDocument(), WebFeature::kAutocapitalizeAttribute); if (params.name == placeholderAttr) { UpdatePlaceholderText(); UpdatePlaceholderVisibility(); - UseCounter::Count(GetDocument(), UseCounter::kPlaceholderAttribute); + UseCounter::Count(GetDocument(), WebFeature::kPlaceholderAttribute); } else { HTMLFormControlElementWithState::ParseAttribute(params); }
diff --git a/third_party/WebKit/Source/core/html/TextDocument.cpp b/third_party/WebKit/Source/core/html/TextDocument.cpp index a52fcd2..4be2ce8 100644 --- a/third_party/WebKit/Source/core/html/TextDocument.cpp +++ b/third_party/WebKit/Source/core/html/TextDocument.cpp
@@ -32,9 +32,9 @@ : HTMLDocument(initializer) { SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kTextDocument); + UseCounter::Count(*this, WebFeature::kTextDocument); if (!IsInMainFrame()) - UseCounter::Count(*this, UseCounter::kTextDocumentInFrame); + UseCounter::Count(*this, WebFeature::kTextDocumentInFrame); } DocumentParser* TextDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/html/canvas/ImageElementBase.cpp b/third_party/WebKit/Source/core/html/canvas/ImageElementBase.cpp index 0cd2059c..0c5ff992 100644 --- a/third_party/WebKit/Source/core/html/canvas/ImageElementBase.cpp +++ b/third_party/WebKit/Source/core/html/canvas/ImageElementBase.cpp
@@ -41,7 +41,7 @@ RefPtr<Image> source_image; if (CachedImage()->GetImage()->IsSVGImage()) { - UseCounter::Count(GetElement().GetDocument(), UseCounter::kSVGInCanvas2D); + UseCounter::Count(GetElement().GetDocument(), WebFeature::kSVGInCanvas2D); SVGImage* svg_image = ToSVGImage(CachedImage()->GetImage()); IntSize image_size = RoundedIntSize(svg_image->ConcreteObjectSize(default_object_size));
diff --git a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp index 613522e..30b6a5d 100644 --- a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp
@@ -112,7 +112,7 @@ void BaseCheckableInputType::ReadingChecked() const { if (is_in_click_handler_) { UseCounter::Count(GetElement().GetDocument(), - UseCounter::kReadingCheckedInClickHandler); + WebFeature::kReadingCheckedInClickHandler); } }
diff --git a/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp b/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp index 3d204c9..ad59b11 100644 --- a/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp
@@ -98,7 +98,7 @@ } void ColorInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeColor); + CountUsageIfVisible(WebFeature::kInputTypeColor); } const AtomicString& ColorInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/DateInputType.cpp b/third_party/WebKit/Source/core/html/forms/DateInputType.cpp index 96132e4f..c359b3a 100644 --- a/third_party/WebKit/Source/core/html/forms/DateInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
@@ -55,7 +55,7 @@ } void DateInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeDate); + CountUsageIfVisible(WebFeature::kInputTypeDate); } const AtomicString& DateInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp b/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp index 6f678ef..3aea2fc 100644 --- a/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp
@@ -53,7 +53,7 @@ } void DateTimeLocalInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeDateTimeLocal); + CountUsageIfVisible(WebFeature::kInputTypeDateTimeLocal); } const AtomicString& DateTimeLocalInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp b/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp index ed6b8b0..ea60079 100644 --- a/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp
@@ -163,14 +163,14 @@ } void EmailInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeEmail); + CountUsageIfVisible(WebFeature::kInputTypeEmail); bool has_max_length = GetElement().FastHasAttribute(HTMLNames::maxlengthAttr); if (has_max_length) - CountUsageIfVisible(UseCounter::kInputTypeEmailMaxLength); + CountUsageIfVisible(WebFeature::kInputTypeEmailMaxLength); if (GetElement().Multiple()) { - CountUsageIfVisible(UseCounter::kInputTypeEmailMultiple); + CountUsageIfVisible(WebFeature::kInputTypeEmailMultiple); if (has_max_length) - CountUsageIfVisible(UseCounter::kInputTypeEmailMultipleMaxLength); + CountUsageIfVisible(WebFeature::kInputTypeEmailMultipleMaxLength); } }
diff --git a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp index 9b9f2c5..5c8f224 100644 --- a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp
@@ -252,9 +252,9 @@ void FileInputType::CountUsage() { Document* document = &GetElement().GetDocument(); if (document->IsSecureContext()) - UseCounter::Count(*document, UseCounter::kInputTypeFileInsecureOrigin); + UseCounter::Count(*document, WebFeature::kInputTypeFileInsecureOrigin); else - UseCounter::Count(*document, UseCounter::kInputTypeFileSecureOrigin); + UseCounter::Count(*document, WebFeature::kInputTypeFileSecureOrigin); } void FileInputType::CreateShadowSubtree() {
diff --git a/third_party/WebKit/Source/core/html/forms/InputType.cpp b/third_party/WebKit/Source/core/html/forms/InputType.cpp index 5f1912e..7da9e95 100644 --- a/third_party/WebKit/Source/core/html/forms/InputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/InputType.cpp
@@ -82,8 +82,7 @@ using namespace HTMLNames; using InputTypeFactoryFunction = InputType* (*)(HTMLInputElement&); -using InputTypeFactoryMap = - HashMap<AtomicString, InputTypeFactoryFunction, CaseFoldingHash>; +using InputTypeFactoryMap = HashMap<AtomicString, InputTypeFactoryFunction>; static std::unique_ptr<InputTypeFactoryMap> CreateInputTypeFactoryMap() { std::unique_ptr<InputTypeFactoryMap> map = @@ -136,7 +135,8 @@ const AtomicString& type_name) { if (type_name.IsEmpty()) return InputTypeNames::text; - InputTypeFactoryMap::const_iterator it = FactoryMap()->find(type_name); + InputTypeFactoryMap::const_iterator it = + FactoryMap()->find(type_name.LowerASCII()); return it == FactoryMap()->end() ? InputTypeNames::text : it->key; } @@ -872,7 +872,7 @@ IGNORE_EXCEPTION_FOR_TESTING); } -void InputType::CountUsageIfVisible(UseCounter::Feature feature) const { +void InputType::CountUsageIfVisible(WebFeature feature) const { if (const ComputedStyle* style = GetElement().GetComputedStyle()) { if (style->Visibility() != EVisibility::kHidden) UseCounter::Count(GetElement().GetDocument(), feature);
diff --git a/third_party/WebKit/Source/core/html/forms/InputType.h b/third_party/WebKit/Source/core/html/forms/InputType.h index 8831cff..6e731b25 100644 --- a/third_party/WebKit/Source/core/html/forms/InputType.h +++ b/third_party/WebKit/Source/core/html/forms/InputType.h
@@ -235,7 +235,7 @@ ChromeClient* GetChromeClient() const; Locale& GetLocale() const; Decimal ParseToNumberOrNaN(const String&) const; - void CountUsageIfVisible(UseCounter::Feature) const; + void CountUsageIfVisible(WebFeature) const; // Derive the step base, following the HTML algorithm steps. Decimal FindStepBase(const Decimal&) const;
diff --git a/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp b/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp index 5966b500..18bd56a5 100644 --- a/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp
@@ -54,7 +54,7 @@ } void MonthInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeMonth); + CountUsageIfVisible(WebFeature::kInputTypeMonth); } const AtomicString& MonthInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp b/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp index 4c9a12e..7395a92 100644 --- a/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp
@@ -98,7 +98,7 @@ } void NumberInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeNumber); + CountUsageIfVisible(WebFeature::kInputTypeNumber); } const AtomicString& NumberInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp b/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp index 26936289..95b85d5a 100644 --- a/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp
@@ -48,9 +48,9 @@ } void PasswordInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypePassword); + CountUsageIfVisible(WebFeature::kInputTypePassword); if (GetElement().FastHasAttribute(HTMLNames::maxlengthAttr)) - CountUsageIfVisible(UseCounter::kInputTypePasswordMaxLength); + CountUsageIfVisible(WebFeature::kInputTypePasswordMaxLength); } const AtomicString& PasswordInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp b/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp index 711e0ad..9d531289 100644 --- a/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp
@@ -92,11 +92,11 @@ } void RangeInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeRange); + CountUsageIfVisible(WebFeature::kInputTypeRange); if (const ComputedStyle* style = GetElement().GetComputedStyle()) { if (style->Appearance() == kSliderVerticalPart) { UseCounter::Count(GetElement().GetDocument(), - UseCounter::kInputTypeRangeVerticalAppearance); + WebFeature::kInputTypeRangeVerticalAppearance); } } }
diff --git a/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp b/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp index d382084e..dd33e286 100644 --- a/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp
@@ -57,7 +57,7 @@ } void SearchInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeSearch); + CountUsageIfVisible(WebFeature::kInputTypeSearch); } LayoutObject* SearchInputType::CreateLayoutObject(const ComputedStyle&) const {
diff --git a/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp b/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp index f5e6cb4a..207bb10 100644 --- a/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp
@@ -41,7 +41,7 @@ namespace blink { InputType* SubmitInputType::Create(HTMLInputElement& element) { - UseCounter::Count(element.GetDocument(), UseCounter::kInputTypeSubmit); + UseCounter::Count(element.GetDocument(), WebFeature::kInputTypeSubmit); return new SubmitInputType(element); } @@ -81,7 +81,7 @@ void SubmitInputType::ValueAttributeChanged() { UseCounter::Count(GetElement().GetDocument(), - UseCounter::kInputTypeSubmitWithValue); + WebFeature::kInputTypeSubmitWithValue); BaseButtonInputType::ValueAttributeChanged(); }
diff --git a/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp b/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp index a8a0dbb..13e9fdb 100644 --- a/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp
@@ -39,7 +39,7 @@ } void TelephoneInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeTel); + CountUsageIfVisible(WebFeature::kInputTypeTel); } const AtomicString& TelephoneInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/TextInputType.cpp b/third_party/WebKit/Source/core/html/forms/TextInputType.cpp index 141837c..003b27c 100644 --- a/third_party/WebKit/Source/core/html/forms/TextInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/TextInputType.cpp
@@ -42,14 +42,14 @@ } void TextInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeText); + CountUsageIfVisible(WebFeature::kInputTypeText); if (GetElement().FastHasAttribute(maxlengthAttr)) - CountUsageIfVisible(UseCounter::kInputTypeTextMaxLength); + CountUsageIfVisible(WebFeature::kInputTypeTextMaxLength); const AtomicString& type = GetElement().FastGetAttribute(typeAttr); if (DeprecatedEqualIgnoringCase(type, InputTypeNames::datetime)) - CountUsageIfVisible(UseCounter::kInputTypeDateTimeFallback); + CountUsageIfVisible(WebFeature::kInputTypeDateTimeFallback); else if (DeprecatedEqualIgnoringCase(type, InputTypeNames::week)) - CountUsageIfVisible(UseCounter::kInputTypeWeekFallback); + CountUsageIfVisible(WebFeature::kInputTypeWeekFallback); } const AtomicString& TextInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp b/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp index 68a5484..0dfb36f 100644 --- a/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp
@@ -59,7 +59,7 @@ } void TimeInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeTime); + CountUsageIfVisible(WebFeature::kInputTypeTime); } const AtomicString& TimeInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/URLInputType.cpp b/third_party/WebKit/Source/core/html/forms/URLInputType.cpp index 4cd40d0..d47e95e 100644 --- a/third_party/WebKit/Source/core/html/forms/URLInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/URLInputType.cpp
@@ -42,7 +42,7 @@ } void URLInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeURL); + CountUsageIfVisible(WebFeature::kInputTypeURL); } const AtomicString& URLInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp b/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp index 7a3a959..6b7c211 100644 --- a/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp
@@ -52,7 +52,7 @@ } void WeekInputType::CountUsage() { - CountUsageIfVisible(UseCounter::kInputTypeWeek); + CountUsageIfVisible(WebFeature::kInputTypeWeek); } const AtomicString& WeekInputType::FormControlType() const {
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportChild.cpp b/third_party/WebKit/Source/core/html/imports/HTMLImportChild.cpp index e87afcc4..4e2258ef 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportChild.cpp +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportChild.cpp
@@ -80,7 +80,7 @@ StateWillChange(); if (GetDocument() && GetDocument()->GetStyleEngine().HasStyleSheets()) { UseCounter::Count(Root()->GetDocument(), - UseCounter::kHTMLImportsHasStyleSheets); + WebFeature::kHTMLImportsHasStyleSheets); } V0CustomElement::DidFinishLoadingImport(*(Root()->GetDocument())); }
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp b/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp index b57d36b..0aac3fa 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp
@@ -43,7 +43,7 @@ HTMLImportsController::HTMLImportsController(Document& master) : root_(HTMLImportTreeRoot::Create(&master)) { - UseCounter::Count(master, UseCounter::kHTMLImports); + UseCounter::Count(master, WebFeature::kHTMLImports); } void HTMLImportsController::Dispose() { @@ -77,7 +77,7 @@ : HTMLImport::kAsync; if (mode == HTMLImport::kAsync) { UseCounter::Count(Root()->GetDocument(), - UseCounter::kHTMLImportsAsyncAttribute); + WebFeature::kHTMLImportsAsyncAttribute); } HTMLImportChild* child = new HTMLImportChild(url, loader, mode);
diff --git a/third_party/WebKit/Source/core/html/media/AutoplayUmaHelper.cpp b/third_party/WebKit/Source/core/html/media/AutoplayUmaHelper.cpp index 9c7197b9..4bc1ec7 100644 --- a/third_party/WebKit/Source/core/html/media/AutoplayUmaHelper.cpp +++ b/third_party/WebKit/Source/core/html/media/AutoplayUmaHelper.cpp
@@ -262,7 +262,7 @@ void AutoplayUmaHelper::VideoWillBeDrawnToCanvas() { if (HasSource() && !IsVisible()) { UseCounter::Count(element_->GetDocument(), - UseCounter::kHiddenAutoplayedVideoInCanvas); + WebFeature::kHiddenAutoplayedVideoInCanvas); } }
diff --git a/third_party/WebKit/Source/core/html/media/MediaDocument.cpp b/third_party/WebKit/Source/core/html/media/MediaDocument.cpp index 4aa5b78..3e85538a 100644 --- a/third_party/WebKit/Source/core/html/media/MediaDocument.cpp +++ b/third_party/WebKit/Source/core/html/media/MediaDocument.cpp
@@ -265,9 +265,9 @@ : HTMLDocument(initializer, kMediaDocumentClass) { SetCompatibilityMode(kQuirksMode); LockCompatibilityMode(); - UseCounter::Count(*this, UseCounter::kMediaDocument); + UseCounter::Count(*this, WebFeature::kMediaDocument); if (!IsInMainFrame()) - UseCounter::Count(*this, UseCounter::kMediaDocumentInFrame); + UseCounter::Count(*this, WebFeature::kMediaDocumentInFrame); } DocumentParser* MediaDocument::CreateParser() {
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp index 06e1cce..9c23c3de 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp
@@ -322,7 +322,7 @@ // lists for each candidate. if (!ParseDescriptors(attribute, descriptor_tokens, result, document)) { if (document) { - UseCounter::Count(document, UseCounter::kSrcsetDroppedCandidate); + UseCounter::Count(document, WebFeature::kSrcsetDroppedCandidate); if (document->GetFrame()) document->GetFrame()->Console().AddMessage(ConsoleMessage::Create( kOtherMessageSource, kErrorMessageLevel,
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp b/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp index 73eb573da..d4254bd 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -619,7 +619,7 @@ if (tree_.IsFormElementPointerNonNull() && !IsParsingTemplateContents()) { ParseError(token); UseCounter::Count(tree_.CurrentNode()->GetDocument(), - UseCounter::kHTMLParseErrorNestedForm); + WebFeature::kHTMLParseErrorNestedForm); return; } ProcessFakePEndTagIfPInButtonScope();
diff --git a/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp b/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp index cc72791..1348968c 100644 --- a/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp +++ b/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp
@@ -386,13 +386,13 @@ header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) - UseCounter::Count(*document, UseCounter::kXSSAuditorDisabled); + UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) - UseCounter::Count(*document, UseCounter::kXSSAuditorEnabledFilter); + UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) - UseCounter::Count(*document, UseCounter::kXSSAuditorEnabledBlock); + UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) - UseCounter::Count(*document, UseCounter::kXSSAuditorInvalid); + UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset &&
diff --git a/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp b/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp index 8dd4d6f0..60960ebb 100644 --- a/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp +++ b/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -105,8 +105,8 @@ DCHECK(IsMainThread()); UseCounter::Count(document_, xss_info.did_block_entire_page_ - ? UseCounter::kXSSAuditorBlockedEntirePage - : UseCounter::kXSSAuditorBlockedScript); + ? WebFeature::kXSSAuditorBlockedEntirePage + : WebFeature::kXSSAuditorBlockedScript); document_->AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kErrorMessageLevel, xss_info.BuildConsoleError()));
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp index 4142018..de43cd7 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp
@@ -244,7 +244,7 @@ cue_background_box_(HTMLDivElement::Create(document)), snap_to_lines_(true), display_tree_should_change_(true) { - UseCounter::Count(document, UseCounter::kVTTCue); + UseCounter::Count(document, WebFeature::kVTTCue); cue_background_box_->SetShadowPseudoId(CueShadowPseudoId()); } @@ -636,7 +636,7 @@ display_parameters.direction = DetermineTextDirection(vtt_node_tree_.Get()); if (display_parameters.direction == CSSValueRtl) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderRtl); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderRtl); // Note: The 'text-align' property is also determined here so that // VTTCueBox::applyCSSProperties need not have access to a VTTCue. @@ -842,25 +842,25 @@ void VTTCue::UpdateDisplay(HTMLDivElement& container) { DCHECK(track() && track()->IsRendered() && IsActive()); - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRender); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRender); if (writing_direction_ != kHorizontal) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderVertical); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderVertical); if (!snap_to_lines_) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderSnapToLinesFalse); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderSnapToLinesFalse); if (!LineIsAuto()) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderLineNotAuto); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderLineNotAuto); if (TextPositionIsAuto()) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderPositionNot50); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderPositionNot50); if (cue_size_ != 100) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderSizeNot100); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderSizeNot100); if (cue_alignment_ != kCenter) - UseCounter::Count(GetDocument(), UseCounter::kVTTCueRenderAlignNotCenter); + UseCounter::Count(GetDocument(), WebFeature::kVTTCueRenderAlignNotCenter); VTTCueBox* display_box = GetDisplayTree(); if (!region()) {
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp index 5cd50acc..2acc6559 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
@@ -137,7 +137,7 @@ const ImageBitmapSourceUnion& bitmap_source, const ImageBitmapOptions& options, ExceptionState& exception_state) { - UseCounter::Feature feature = UseCounter::kCreateImageBitmap; + WebFeature feature = WebFeature::kCreateImageBitmap; UseCounter::Count(ExecutionContext::From(script_state), feature); ImageBitmapSource* bitmap_source_internal = ToImageBitmapSourceInternal( bitmap_source, exception_state, options, false); @@ -157,7 +157,7 @@ int sh, const ImageBitmapOptions& options, ExceptionState& exception_state) { - UseCounter::Feature feature = UseCounter::kCreateImageBitmap; + WebFeature feature = WebFeature::kCreateImageBitmap; UseCounter::Count(ExecutionContext::From(script_state), feature); ImageBitmapSource* bitmap_source_internal = ToImageBitmapSourceInternal( bitmap_source, exception_state, options, true);
diff --git a/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp b/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp index 8c94ecd..72639a8 100644 --- a/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp +++ b/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp
@@ -63,7 +63,7 @@ WebInputEvent::Modifiers modifiers, ScrollDirection* scroll_direction, ScrollGranularity* scroll_granularity, - UseCounter::Feature* scroll_use_uma) { + WebFeature* scroll_use_uma) { if (modifiers & WebInputEvent::kShiftKey || modifiers & WebInputEvent::kMetaKey) return false; @@ -90,42 +90,42 @@ case VKEY_LEFT: *scroll_direction = kScrollLeftIgnoringWritingMode; *scroll_granularity = kScrollByLine; - *scroll_use_uma = UseCounter::kScrollByKeyboardArrowKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardArrowKeys; break; case VKEY_RIGHT: *scroll_direction = kScrollRightIgnoringWritingMode; *scroll_granularity = kScrollByLine; - *scroll_use_uma = UseCounter::kScrollByKeyboardArrowKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardArrowKeys; break; case VKEY_UP: *scroll_direction = kScrollUpIgnoringWritingMode; *scroll_granularity = kScrollByLine; - *scroll_use_uma = UseCounter::kScrollByKeyboardArrowKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardArrowKeys; break; case VKEY_DOWN: *scroll_direction = kScrollDownIgnoringWritingMode; *scroll_granularity = kScrollByLine; - *scroll_use_uma = UseCounter::kScrollByKeyboardArrowKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardArrowKeys; break; case VKEY_HOME: *scroll_direction = kScrollUpIgnoringWritingMode; *scroll_granularity = kScrollByDocument; - *scroll_use_uma = UseCounter::kScrollByKeyboardHomeEndKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardHomeEndKeys; break; case VKEY_END: *scroll_direction = kScrollDownIgnoringWritingMode; *scroll_granularity = kScrollByDocument; - *scroll_use_uma = UseCounter::kScrollByKeyboardHomeEndKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardHomeEndKeys; break; case VKEY_PRIOR: // page up *scroll_direction = kScrollUpIgnoringWritingMode; *scroll_granularity = kScrollByPage; - *scroll_use_uma = UseCounter::kScrollByKeyboardPageUpDownKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardPageUpDownKeys; break; case VKEY_NEXT: // page down *scroll_direction = kScrollDownIgnoringWritingMode; *scroll_granularity = kScrollByPage; - *scroll_use_uma = UseCounter::kScrollByKeyboardPageUpDownKeys; + *scroll_use_uma = WebFeature::kScrollByKeyboardPageUpDownKeys; break; default: return false; @@ -332,7 +332,7 @@ if (scroll_manager_->LogicalScroll(direction, kScrollByPage, nullptr, possible_focused_node)) { UseCounter::Count(frame_->GetDocument(), - UseCounter::kScrollByKeyboardSpacebarKey); + WebFeature::kScrollByKeyboardSpacebarKey); event->SetDefaultHandled(); return; } @@ -349,10 +349,10 @@ if (!frame_->GetEditor().Behavior().ShouldNavigateBackOnBackspace()) return; - UseCounter::Count(frame_->GetDocument(), UseCounter::kBackspaceNavigatedBack); + UseCounter::Count(frame_->GetDocument(), WebFeature::kBackspaceNavigatedBack); if (frame_->GetPage()->GetChromeClient().HadFormInteraction()) { UseCounter::Count(frame_->GetDocument(), - UseCounter::kBackspaceNavigatedBackAfterFormInteraction); + WebFeature::kBackspaceNavigatedBackAfterFormInteraction); } bool handled_event = frame_->Loader().Client()->NavigateBackForward( event->shiftKey() ? 1 : -1); @@ -383,7 +383,7 @@ ScrollDirection scroll_direction; ScrollGranularity scroll_granularity; - UseCounter::Feature scroll_use_uma; + WebFeature scroll_use_uma; if (!MapKeyCodeForScroll(event->keyCode(), event->GetModifiers(), &scroll_direction, &scroll_granularity, &scroll_use_uma))
diff --git a/third_party/WebKit/Source/core/input/PointerEventManager.cpp b/third_party/WebKit/Source/core/input/PointerEventManager.cpp index 2a2c776..d18abbb 100644 --- a/third_party/WebKit/Source/core/input/PointerEventManager.cpp +++ b/third_party/WebKit/Source/core/input/PointerEventManager.cpp
@@ -169,9 +169,9 @@ return WebInputEventResult::kNotHandled; if (!check_for_listener || target->HasEventListeners(event_type)) { - UseCounter::Count(frame_, UseCounter::kPointerEventDispatch); + UseCounter::Count(frame_, WebFeature::kPointerEventDispatch); if (event_type == EventTypeNames::pointerdown) - UseCounter::Count(frame_, UseCounter::kPointerEventDispatchPointerDown); + UseCounter::Count(frame_, WebFeature::kPointerEventDispatchPointerDown); DCHECK(!dispatching_pointer_id_); AutoReset<int> dispatch_holder(&dispatching_pointer_id_, pointer_id); @@ -674,11 +674,11 @@ void PointerEventManager::SetPointerCapture(int pointer_id, EventTarget* target) { - UseCounter::Count(frame_, UseCounter::kPointerEventSetCapture); + UseCounter::Count(frame_, WebFeature::kPointerEventSetCapture); if (pointer_event_factory_.IsActiveButtonsState(pointer_id)) { if (pointer_id != dispatching_pointer_id_) { UseCounter::Count(frame_, - UseCounter::kPointerEventSetCaptureOutsideDispatch); + WebFeature::kPointerEventSetCaptureOutsideDispatch); } pending_pointer_capture_target_.Set(pointer_id, target); }
diff --git a/third_party/WebKit/Source/core/input/ScrollManager.cpp b/third_party/WebKit/Source/core/input/ScrollManager.cpp index 4f6ef4d..309d87ca 100644 --- a/third_party/WebKit/Source/core/input/ScrollManager.cpp +++ b/third_party/WebKit/Source/core/input/ScrollManager.cpp
@@ -328,9 +328,9 @@ CustomizedScroll(*scroll_gesture_handling_node_.Get(), *scroll_state); if (gesture_event.source_device == kWebGestureDeviceTouchscreen) - UseCounter::Count(frame_->GetDocument(), UseCounter::kScrollByTouch); + UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByTouch); else - UseCounter::Count(frame_->GetDocument(), UseCounter::kScrollByWheel); + UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByWheel); return WebInputEventResult::kHandledSystem; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp index 316c302..476208fc 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
@@ -4392,7 +4392,7 @@ StyleRef()); case kPagedFlowThread: // Paged overflow is currently done using the multicol implementation. - UseCounter::Count(GetDocument(), UseCounter::kCSSOverflowPaged); + UseCounter::Count(GetDocument(), WebFeature::kCSSOverflowPaged); return LayoutPagedFlowThread::CreateAnonymous(GetDocument(), StyleRef()); default: NOTREACHED();
diff --git a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp index d187b809..08dc8f7 100644 --- a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp
@@ -270,13 +270,13 @@ if (!IsAnonymous()) { const KURL& url = GetDocument().Url(); if (url.ProtocolIs("chrome")) { - UseCounter::Count(GetDocument(), UseCounter::kDeprecatedFlexboxChrome); + UseCounter::Count(GetDocument(), WebFeature::kDeprecatedFlexboxChrome); } else if (url.ProtocolIs("chrome-extension")) { UseCounter::Count(GetDocument(), - UseCounter::kDeprecatedFlexboxChromeExtension); + WebFeature::kDeprecatedFlexboxChromeExtension); } else { UseCounter::Count(GetDocument(), - UseCounter::kDeprecatedFlexboxWebContent); + WebFeature::kDeprecatedFlexboxWebContent); } } } @@ -1089,7 +1089,7 @@ void LayoutDeprecatedFlexibleBox::ApplyLineClamp(FlexBoxIterator& iterator, bool relayout_children) { - UseCounter::Count(GetDocument(), UseCounter::kLineClamp); + UseCounter::Count(GetDocument(), WebFeature::kLineClamp); int max_line_count = 0; for (LayoutBox* child = iterator.First(); child; child = iterator.Next()) {
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp index b433763..5e78690 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp
@@ -73,7 +73,7 @@ in_layout_(false) { DCHECK(!ChildrenInline()); if (!IsAnonymous()) - UseCounter::Count(GetDocument(), UseCounter::kCSSFlexibleBox); + UseCounter::Count(GetDocument(), WebFeature::kCSSFlexibleBox); } LayoutFlexibleBox::~LayoutFlexibleBox() {} @@ -164,7 +164,7 @@ if (previous_max_content_flex_fraction != -1 && max_content_flex_fraction != previous_max_content_flex_fraction) { UseCounter::Count(GetDocument(), - UseCounter::kFlexboxIntrinsicSizeAlgorithmIsDifferent); + WebFeature::kFlexboxIntrinsicSizeAlgorithmIsDifferent); } return max_content_flex_fraction; } @@ -926,7 +926,7 @@ child.ClearOverrideSize(); if (child.IsImage() || child.IsVideo() || child.IsCanvas()) - UseCounter::Count(GetDocument(), UseCounter::kAspectRatioFlexItem); + UseCounter::Count(GetDocument(), WebFeature::kAspectRatioFlexItem); Length flex_basis = FlexBasisForChild(child); if (MainAxisLengthIsDefinite(child, flex_basis))
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp index 99bc7c6..e267e106 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -58,7 +58,7 @@ : LayoutBlock(element), grid_(this), track_sizing_algorithm_(this, grid_) { DCHECK(!ChildrenInline()); if (!IsAnonymous()) - UseCounter::Count(GetDocument(), UseCounter::kCSSGridLayout); + UseCounter::Count(GetDocument(), WebFeature::kCSSGridLayout); } LayoutGrid::~LayoutGrid() {}
diff --git a/third_party/WebKit/Source/core/layout/LayoutImage.cpp b/third_party/WebKit/Source/core/layout/LayoutImage.cpp index 19761d5..7a2c66f 100644 --- a/third_party/WebKit/Source/core/layout/LayoutImage.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutImage.cpp
@@ -110,7 +110,7 @@ if (image_resource_->CachedImage() && image_resource_->CachedImage()->HasDevicePixelRatioHeaderValue()) { UseCounter::Count(&(View()->GetFrameView()->GetFrame()), - UseCounter::kClientHintsContentDPR); + WebFeature::kClientHintsContentDPR); image_device_pixel_ratio_ = 1 / image_resource_->CachedImage()->DevicePixelRatioHeaderValue(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutRuby.cpp b/third_party/WebKit/Source/core/layout/LayoutRuby.cpp index 47baca1..eeebdab5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutRuby.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutRuby.cpp
@@ -53,7 +53,7 @@ LayoutRubyAsInline::LayoutRubyAsInline(Element* element) : LayoutInline(element) { - UseCounter::Count(GetDocument(), UseCounter::kRenderRuby); + UseCounter::Count(GetDocument(), WebFeature::kRenderRuby); } LayoutRubyAsInline::~LayoutRubyAsInline() {} @@ -118,7 +118,7 @@ LayoutRubyAsBlock::LayoutRubyAsBlock(Element* element) : LayoutBlockFlow(element) { - UseCounter::Count(GetDocument(), UseCounter::kRenderRuby); + UseCounter::Count(GetDocument(), WebFeature::kRenderRuby); } LayoutRubyAsBlock::~LayoutRubyAsBlock() {}
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp index 9f31edd..baed2fc 100644 --- a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp
@@ -59,21 +59,21 @@ case kBackButtonEndPart: case kForwardButtonEndPart: UseCounter::Count(document, - UseCounter::kCSSSelectorPseudoScrollbarButton); + WebFeature::kCSSSelectorPseudoScrollbarButton); break; case kBackTrackPart: case kForwardTrackPart: UseCounter::Count(document, - UseCounter::kCSSSelectorPseudoScrollbarTrackPiece); + WebFeature::kCSSSelectorPseudoScrollbarTrackPiece); break; case kThumbPart: - UseCounter::Count(document, UseCounter::kCSSSelectorPseudoScrollbarThumb); + UseCounter::Count(document, WebFeature::kCSSSelectorPseudoScrollbarThumb); break; case kTrackBGPart: - UseCounter::Count(document, UseCounter::kCSSSelectorPseudoScrollbarTrack); + UseCounter::Count(document, WebFeature::kCSSSelectorPseudoScrollbarTrack); break; case kScrollbarBGPart: - UseCounter::Count(document, UseCounter::kCSSSelectorPseudoScrollbar); + UseCounter::Count(document, WebFeature::kCSSSelectorPseudoScrollbar); break; case kNoPart: case kAllParts:
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp index 37406594..8a1142c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp
@@ -969,14 +969,14 @@ if (!Table()->HasSameDirectionAs(row)) { UseCounter::Count(GetDocument(), - UseCounter::kTableRowDirectionDifferentFromTable); + WebFeature::kTableRowDirectionDifferentFromTable); } } } if (!Table()->HasSameDirectionAs(this)) { UseCounter::Count(GetDocument(), - UseCounter::kTableSectionDirectionDifferentFromTable); + WebFeature::kTableSectionDirectionDifferentFromTable); } ClearNeedsLayout();
diff --git a/third_party/WebKit/Source/core/layout/ScrollAnchor.cpp b/third_party/WebKit/Source/core/layout/ScrollAnchor.cpp index 460e7348..e37a881 100644 --- a/third_party/WebKit/Source/core/layout/ScrollAnchor.cpp +++ b/third_party/WebKit/Source/core/layout/ScrollAnchor.cpp
@@ -318,7 +318,7 @@ ("Layout.ScrollAnchor.AdjustedScrollOffset", 2)); adjusted_offset_histogram.Count(1); UseCounter::Count(ScrollerLayoutBox(scroller_)->GetDocument(), - UseCounter::kScrollAnchored); + WebFeature::kScrollAnchored); } void ScrollAnchor::ClearSelf() {
diff --git a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp index 6f0e83dde..873eaf3 100644 --- a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp +++ b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp
@@ -474,7 +474,7 @@ } if (page_info_.has_autosized_) - UseCounter::Count(*document_, UseCounter::kTextAutosizing); + UseCounter::Count(*document_, WebFeature::kTextAutosizing); return multiplier; }
diff --git a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp index 57ae9acc..1a3d2824 100644 --- a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp +++ b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp
@@ -845,7 +845,7 @@ if (style.Preserves3D() && style.HasOpacity() && owning_layer_.Has3DTransformedDescendant()) { UseCounter::Count(layout_object.GetDocument(), - UseCounter::kOpacityWithPreserve3DQuirk); + WebFeature::kOpacityWithPreserve3DQuirk); } return layer_config_changed;
diff --git a/third_party/WebKit/Source/core/layout/compositing/CompositingInputsUpdater.cpp b/third_party/WebKit/Source/core/layout/compositing/CompositingInputsUpdater.cpp index 5e542159..6e67bcdc 100644 --- a/third_party/WebKit/Source/core/layout/compositing/CompositingInputsUpdater.cpp +++ b/third_party/WebKit/Source/core/layout/compositing/CompositingInputsUpdater.cpp
@@ -191,7 +191,7 @@ if (layer_is_fixed_position && properties.filter_ancestor && layer->FixedToViewport()) { UseCounter::Count(layer->GetLayoutObject().GetDocument(), - UseCounter::kViewportFixedPositionUnderFilter); + WebFeature::kViewportFixedPositionUnderFilter); } properties.nearest_fixed_position_layer =
diff --git a/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp b/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp index 88790bb..8c45629 100644 --- a/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/BaseFetchContext.cpp
@@ -252,7 +252,7 @@ if (SchemeRegistry::ShouldTreatURLSchemeAsLegacy(url.Protocol()) && !SchemeRegistry::ShouldTreatURLSchemeAsLegacy( embedding_origin->Protocol())) { - CountDeprecation(UseCounter::kLegacyProtocolEmbeddedAsSubresource); + CountDeprecation(WebFeature::kLegacyProtocolEmbeddedAsSubresource); // TODO(mkwst): Enabled by default in M59. Drop the runtime-enabled check // in M60: https://www.chromestatus.com/feature/5709390967472128 @@ -264,7 +264,7 @@ resource_request.GetRequestContext() != WebURLRequest::kRequestContextXMLHttpRequest) { CountDeprecation( - UseCounter::kRequestedSubresourceWithEmbeddedCredentials); + WebFeature::kRequestedSubresourceWithEmbeddedCredentials); // TODO(mkwst): Remove the runtime-enabled check in M59: // https://www.chromestatus.com/feature/5669008342777856 if (RuntimeEnabledFeatures::BlockCredentialedSubresourcesEnabled()) @@ -280,7 +280,7 @@ return ResourceRequestBlockedReason::kMixedContent; if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) { - CountDeprecation(UseCounter::kCanRequestURLHTTPContainingNewline); + CountDeprecation(WebFeature::kCanRequestURLHTTPContainingNewline); if (RuntimeEnabledFeatures::RestrictCanRequestURLCharacterSetEnabled()) return ResourceRequestBlockedReason::kOther; }
diff --git a/third_party/WebKit/Source/core/loader/BaseFetchContext.h b/third_party/WebKit/Source/core/loader/BaseFetchContext.h index 3bd5eeb..22e8203 100644 --- a/third_party/WebKit/Source/core/loader/BaseFetchContext.h +++ b/third_party/WebKit/Source/core/loader/BaseFetchContext.h
@@ -68,8 +68,8 @@ ResourceRequestBlockedReason) const = 0; virtual bool ShouldBypassMainWorldCSP() const = 0; virtual bool IsSVGImageChromeClient() const = 0; - virtual void CountUsage(UseCounter::Feature) const = 0; - virtual void CountDeprecation(UseCounter::Feature) const = 0; + virtual void CountUsage(WebFeature) const = 0; + virtual void CountDeprecation(WebFeature) const = 0; virtual bool ShouldBlockFetchByMixedContentCheck( const ResourceRequest&, const KURL&,
diff --git a/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp index 154fb79..1dde4469 100644 --- a/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/BaseFetchContextTest.cpp
@@ -57,8 +57,8 @@ ResourceRequestBlockedReason) const override {} bool ShouldBypassMainWorldCSP() const override { return false; } bool IsSVGImageChromeClient() const override { return false; } - void CountUsage(UseCounter::Feature) const override {} - void CountDeprecation(UseCounter::Feature) const override {} + void CountUsage(WebFeature) const override {} + void CountDeprecation(WebFeature) const override {} bool ShouldBlockFetchByMixedContentCheck( const ResourceRequest&, const KURL&,
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index 3d67eac7..09aa0d7 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -614,7 +614,7 @@ DCHECK(!frame_->GetPage()->Suspended()); if (response.DidServiceWorkerNavigationPreload()) - UseCounter::Count(frame_, UseCounter::kServiceWorkerNavigationPreload); + UseCounter::Count(frame_, WebFeature::kServiceWorkerNavigationPreload); response_ = response; if (IsArchiveMIMEType(response_.MimeType()) && @@ -942,7 +942,7 @@ String referrer_policy_header = response_.HttpHeaderField(HTTPNames::Referrer_Policy); if (!referrer_policy_header.IsNull()) { - UseCounter::Count(*document, UseCounter::kReferrerPolicyHeader); + UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); }
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 9884feea..3eafdb78 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -821,7 +821,7 @@ if (response.WasFetchedViaServiceWorker()) { if (response.WasFetchedViaForeignFetch()) - loading_context_->RecordUseCount(UseCounter::kForeignFetchInterception); + loading_context_->RecordUseCount(WebFeature::kForeignFetchInterception); if (response.WasFallbackRequiredByServiceWorker()) { // At this point we must have m_fallbackRequestForServiceWorker. (For // SharedWorker the request won't be CORS or CORS-with-preflight,
diff --git a/third_party/WebKit/Source/core/loader/FormSubmission.cpp b/third_party/WebKit/Source/core/loader/FormSubmission.cpp index e85c2a8..b54218b 100644 --- a/third_party/WebKit/Source/core/loader/FormSubmission.cpp +++ b/third_party/WebKit/Source/core/loader/FormSubmission.cpp
@@ -200,7 +200,7 @@ if (document.GetInsecureRequestPolicy() & kUpgradeInsecureRequests && action_url.ProtocolIs("http")) { UseCounter::Count(document, - UseCounter::kUpgradeInsecureRequestsUpgradedRequest); + WebFeature::kUpgradeInsecureRequestsUpgradedRequest); action_url.SetProtocol("https"); if (action_url.Port() == 80) action_url.SetPort(443);
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp index 92e76b7a..1b32305 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -780,11 +780,11 @@ return GetFrame()->GetChromeClient().IsSVGImageChromeClient(); } -void FrameFetchContext::CountUsage(UseCounter::Feature feature) const { +void FrameFetchContext::CountUsage(WebFeature feature) const { UseCounter::Count(GetFrame(), feature); } -void FrameFetchContext::CountDeprecation(UseCounter::Feature feature) const { +void FrameFetchContext::CountDeprecation(WebFeature feature) const { Deprecation::CountDeprecation(GetFrame(), feature); }
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.h b/third_party/WebKit/Source/core/loader/FrameFetchContext.h index 493770d..3b76424b 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.h +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.h
@@ -184,8 +184,8 @@ ResourceRequestBlockedReason) const override; bool ShouldBypassMainWorldCSP() const override; bool IsSVGImageChromeClient() const override; - void CountUsage(UseCounter::Feature) const override; - void CountDeprecation(UseCounter::Feature) const override; + void CountUsage(WebFeature) const override; + void CountDeprecation(WebFeature) const override; bool ShouldBlockFetchByMixedContentCheck( const ResourceRequest&, const KURL&,
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 1d33f70..aecce715aa 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -135,7 +135,7 @@ return; } Deprecation::CountDeprecation( - document, UseCounter::kLegacyProtocolEmbeddedAsSubresource); + document, WebFeature::kLegacyProtocolEmbeddedAsSubresource); } static NavigationPolicy MaybeCheckCSP( @@ -370,7 +370,7 @@ DocumentLoader* document_loader(frame_->GetDocument()->Loader()); UseCounter::Count(*frame_->GetDocument(), - UseCounter::kReplaceDocumentViaJavaScriptURL); + WebFeature::kReplaceDocumentViaJavaScriptURL); // Prepare a DocumentInit before clearing the frame, because it may need to // inherit an aliased security context. @@ -1273,7 +1273,7 @@ if (request.Url().PotentiallyDanglingMarkup() && request.Url().ProtocolIsInHTTPFamily()) { Deprecation::CountDeprecation( - frame_, UseCounter::kCanRequestURLHTTPContainingNewline); + frame_, WebFeature::kCanRequestURLHTTPContainingNewline); if (RuntimeEnabledFeatures::RestrictCanRequestURLCharacterSetEnabled()) return kNavigationPolicyIgnore; } @@ -1625,7 +1625,7 @@ (!url.Host().IsNull() && relevant_navigation_set->Contains(url.Host().Impl()->GetHash()))) { UseCounter::Count(document, - UseCounter::kUpgradeInsecureRequestsUpgradedRequest); + WebFeature::kUpgradeInsecureRequestsUpgradedRequest); url.SetProtocol("https"); if (url.Port() == 80) url.SetPort(443);
diff --git a/third_party/WebKit/Source/core/loader/HttpEquiv.cpp b/third_party/WebKit/Source/core/loader/HttpEquiv.cpp index bb43aaf3..fbecc31d 100644 --- a/third_party/WebKit/Source/core/loader/HttpEquiv.cpp +++ b/third_party/WebKit/Source/core/loader/HttpEquiv.cpp
@@ -91,7 +91,7 @@ if (!document.GetFrame()) return; - UseCounter::Count(document, UseCounter::kClientHintsMetaAcceptCH); + UseCounter::Count(document, WebFeature::kClientHintsMetaAcceptCH); FrameClientHintsPreferencesContext hints_context(document.GetFrame()); document.GetClientHintsPreferences().UpdateFromAcceptClientHintsHeader( content, &hints_context); @@ -105,12 +105,12 @@ void HttpEquiv::ProcessHttpEquivRefresh(Document& document, const AtomicString& content, Element* element) { - UseCounter::Count(document, UseCounter::kMetaRefresh); + UseCounter::Count(document, WebFeature::kMetaRefresh); if (!document.GetContentSecurityPolicy()->AllowInlineScript( element, KURL(), "", OrdinalNumber(), "", SecurityViolationReportingPolicy::kSuppressReporting)) { UseCounter::Count(document, - UseCounter::kMetaRefreshWhenCSPBlocksInlineScript); + WebFeature::kMetaRefreshWhenCSPBlocksInlineScript); } document.MaybeHandleHttpRefresh(content, Document::kHttpRefreshFromMetaTag); @@ -124,12 +124,12 @@ if (!document.IsHTMLDocument()) return; - UseCounter::Count(document, UseCounter::kMetaSetCookie); + UseCounter::Count(document, WebFeature::kMetaSetCookie); if (!document.GetContentSecurityPolicy()->AllowInlineScript( element, KURL(), "", OrdinalNumber(), "", SecurityViolationReportingPolicy::kSuppressReporting)) { UseCounter::Count(document, - UseCounter::kMetaSetCookieWhenCSPBlocksInlineScript); + WebFeature::kMetaSetCookieWhenCSPBlocksInlineScript); } // Exception (for sandboxed documents) ignored.
diff --git a/third_party/WebKit/Source/core/loader/LinkLoader.cpp b/third_party/WebKit/Source/core/loader/LinkLoader.cpp index f76101d..8843652d 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoader.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoader.cpp
@@ -64,11 +64,11 @@ unsigned result = 0; if (rel_attribute.IsLinkPrerender()) { result |= kPrerenderRelTypePrerender; - UseCounter::Count(document, UseCounter::kLinkRelPrerender); + UseCounter::Count(document, WebFeature::kLinkRelPrerender); } if (rel_attribute.IsLinkNext()) { result |= kPrerenderRelTypeNext; - UseCounter::Count(document, UseCounter::kLinkRelNext); + UseCounter::Count(document, WebFeature::kLinkRelNext); } return result; @@ -154,9 +154,9 @@ const NetworkHintsInterface& network_hints_interface, LinkCaller caller) { if (rel_attribute.IsDNSPrefetch()) { - UseCounter::Count(frame, UseCounter::kLinkRelDnsPrefetch); + UseCounter::Count(frame, WebFeature::kLinkRelDnsPrefetch); if (caller == kLinkCalledFromHeader) - UseCounter::Count(frame, UseCounter::kLinkHeaderDnsPrefetch); + UseCounter::Count(frame, WebFeature::kLinkHeaderDnsPrefetch); Settings* settings = frame ? frame->GetSettings() : nullptr; // FIXME: The href attribute of the link element can be in "//hostname" // form, and we shouldn't attempt to complete that as URL @@ -185,9 +185,9 @@ LinkCaller caller) { if (rel_attribute.IsPreconnect() && href.IsValid() && href.ProtocolIsInHTTPFamily()) { - UseCounter::Count(frame, UseCounter::kLinkRelPreconnect); + UseCounter::Count(frame, WebFeature::kLinkRelPreconnect); if (caller == kLinkCalledFromHeader) - UseCounter::Count(frame, UseCounter::kLinkHeaderPreconnect); + UseCounter::Count(frame, WebFeature::kLinkHeaderPreconnect); Settings* settings = frame ? frame->GetSettings() : nullptr; if (settings && settings->GetLogDnsPrefetchAndPreconnect()) { SendMessageToConsoleForPossiblyNullDocument( @@ -308,7 +308,7 @@ if (!document.Loader() || !rel_attribute.IsLinkPreload()) return nullptr; - UseCounter::Count(document, UseCounter::kLinkRelPreload); + UseCounter::Count(document, WebFeature::kLinkRelPreload); if (!href.IsValid() || href.IsEmpty()) { document.AddConsoleMessage(ConsoleMessage::Create( kOtherMessageSource, kWarningMessageLevel, @@ -332,7 +332,7 @@ return nullptr; } if (caller == kLinkCalledFromHeader) - UseCounter::Count(document, UseCounter::kLinkHeaderPreload); + UseCounter::Count(document, WebFeature::kLinkHeaderPreload); Optional<Resource::Type> resource_type = LinkLoader::GetResourceTypeFromAsAttribute(as); if (resource_type == WTF::nullopt) { @@ -384,7 +384,7 @@ CrossOriginAttributeValue cross_origin, ReferrerPolicy referrer_policy) { if (rel_attribute.IsLinkPrefetch() && href.IsValid() && document.GetFrame()) { - UseCounter::Count(document, UseCounter::kLinkRelPrefetch); + UseCounter::Count(document, WebFeature::kLinkRelPrefetch); ResourceRequest resource_request(document.CompleteURL(href)); if (referrer_policy != kReferrerPolicyDefault) { @@ -457,7 +457,7 @@ kReferrerPolicyDefault); } if (rel_attribute.IsServiceWorker()) { - UseCounter::Count(&frame, UseCounter::kLinkHeaderServiceWorker); + UseCounter::Count(&frame, WebFeature::kLinkHeaderServiceWorker); } // TODO(yoav): Add more supported headers as needed. }
diff --git a/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp b/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp index 4cfa88c..00601ff 100644 --- a/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp +++ b/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp
@@ -152,13 +152,13 @@ if (origin->Protocol() != "https") { UseCounter::Count( source, - UseCounter::kMixedContentInNonHTTPSFrameThatRestrictsMixedContent); + WebFeature::kMixedContentInNonHTTPSFrameThatRestrictsMixedContent); } } else if (!SecurityOrigin::IsSecure(url) && SchemeRegistry::ShouldTreatURLSchemeAsSecure(origin->Protocol())) { UseCounter::Count( source, - UseCounter::kMixedContentInSecureFrameThatDoesNotRestrictMixedContent); + WebFeature::kMixedContentInSecureFrameThatDoesNotRestrictMixedContent); } } @@ -249,7 +249,7 @@ void MixedContentChecker::Count(Frame* frame, WebURLRequest::RequestContext request_context, const LocalFrame* source) { - UseCounter::Count(source, UseCounter::kMixedContentPresent); + UseCounter::Count(source, WebFeature::kMixedContentPresent); // Roll blockable content up into a single counter, count unblocked types // individually so we can determine when they can be safely moved to the @@ -259,35 +259,35 @@ request_context, frame->GetSettings()->GetStrictMixedContentCheckingForPlugin()); if (context_type == WebMixedContentContextType::kBlockable) { - UseCounter::Count(source, UseCounter::kMixedContentBlockable); + UseCounter::Count(source, WebFeature::kMixedContentBlockable); return; } - UseCounter::Feature feature; + WebFeature feature; switch (request_context) { case WebURLRequest::kRequestContextAudio: - feature = UseCounter::kMixedContentAudio; + feature = WebFeature::kMixedContentAudio; break; case WebURLRequest::kRequestContextDownload: - feature = UseCounter::kMixedContentDownload; + feature = WebFeature::kMixedContentDownload; break; case WebURLRequest::kRequestContextFavicon: - feature = UseCounter::kMixedContentFavicon; + feature = WebFeature::kMixedContentFavicon; break; case WebURLRequest::kRequestContextImage: - feature = UseCounter::kMixedContentImage; + feature = WebFeature::kMixedContentImage; break; case WebURLRequest::kRequestContextInternal: - feature = UseCounter::kMixedContentInternal; + feature = WebFeature::kMixedContentInternal; break; case WebURLRequest::kRequestContextPlugin: - feature = UseCounter::kMixedContentPlugin; + feature = WebFeature::kMixedContentPlugin; break; case WebURLRequest::kRequestContextPrefetch: - feature = UseCounter::kMixedContentPrefetch; + feature = WebFeature::kMixedContentPrefetch; break; case WebURLRequest::kRequestContextVideo: - feature = UseCounter::kMixedContentVideo; + feature = WebFeature::kMixedContentVideo; break; default: @@ -379,7 +379,7 @@ IsMixedContent(frame->GetSecurityContext()->GetSecurityOrigin(), url)) { UseCounter::Count(frame, - UseCounter::kBlockableMixedContentInSubframeBlocked); + WebFeature::kBlockableMixedContentInSubframeBlocked); allowed = false; break; } @@ -394,7 +394,7 @@ security_origin, url); if (allowed) { client->DidRunInsecureContent(security_origin, url); - UseCounter::Count(frame, UseCounter::kMixedContentBlockableAllowed); + UseCounter::Count(frame, WebFeature::kMixedContentBlockableAllowed); } break; } @@ -447,8 +447,8 @@ if (!mixed_frame) return false; - UseCounter::Count(frame, UseCounter::kMixedContentPresent); - UseCounter::Count(frame, UseCounter::kMixedContentWebSocket); + UseCounter::Count(frame, WebFeature::kMixedContentPresent); + UseCounter::Count(frame, WebFeature::kMixedContentWebSocket); if (ContentSecurityPolicy* policy = frame->GetSecurityContext()->GetContentSecurityPolicy()) { policy->ReportMixedContent(url, @@ -505,7 +505,7 @@ if (!mixed_frame) return false; - UseCounter::Count(frame, UseCounter::kMixedContentPresent); + UseCounter::Count(frame, WebFeature::kMixedContentPresent); // Use the current local frame's client; the embedder doesn't distinguish // mixed content signals from different frames on the same page. @@ -535,7 +535,7 @@ if (NetworkUtils::IsReservedIPAddress(resource_ip_address) && frame->GetDocument()->AddressSpace() == kWebAddressSpacePublic) { UseCounter::Count(frame->GetDocument(), - UseCounter::kMixedContentPrivateHostnameInPublicHostname); + WebFeature::kMixedContentPrivateHostnameInPublicHostname); // We can simplify the IP checks here, as we've already verified that // |resourceIPAddress| is a reserved IP address, which means it's also a // valid IP address in a normalized form. @@ -543,8 +543,8 @@ resource_ip_address == "[::1]") { UseCounter::Count(frame->GetDocument(), frame->GetDocument()->IsSecureContext() - ? UseCounter::kLoopbackEmbeddedInSecureContext - : UseCounter::kLoopbackEmbeddedInNonSecureContext); + ? WebFeature::kLoopbackEmbeddedInSecureContext + : WebFeature::kLoopbackEmbeddedInNonSecureContext); } } }
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp index 1f38c934..5b0f225 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp
@@ -56,7 +56,7 @@ return TaskRunnerHelper::Get(type, document_.Get()); } - void RecordUseCount(UseCounter::Feature feature) override { + void RecordUseCount(WebFeature feature) override { UseCounter::Count(document_.Get(), feature); } @@ -117,7 +117,7 @@ return fetch_context_->GetTaskRunner(); } - void RecordUseCount(UseCounter::Feature feature) override { + void RecordUseCount(WebFeature feature) override { UseCounter::Count(worker_global_scope_, feature); }
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h index 35549a9..8ed27e9 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h +++ b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h
@@ -43,7 +43,7 @@ virtual KURL FirstPartyForCookies() const = 0; virtual String UserAgent() const = 0; virtual RefPtr<WebTaskRunner> GetTaskRunner(TaskType) = 0; - virtual void RecordUseCount(UseCounter::Feature) = 0; + virtual void RecordUseCount(WebFeature) = 0; // TODO(kinuko): Try getting rid of dependency to Document. virtual Document* GetLoadingDocument() { return nullptr; }
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp index 76deee5..9b8a99fe 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp
@@ -134,11 +134,11 @@ return false; } -void WorkerFetchContext::CountUsage(UseCounter::Feature feature) const { +void WorkerFetchContext::CountUsage(WebFeature feature) const { UseCounter::Count(global_scope_, feature); } -void WorkerFetchContext::CountDeprecation(UseCounter::Feature feature) const { +void WorkerFetchContext::CountDeprecation(WebFeature feature) const { Deprecation::CountDeprecation(global_scope_, feature); }
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h index 54f5cb38..1c29244 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h
@@ -47,8 +47,8 @@ ResourceRequestBlockedReason) const override; bool ShouldBypassMainWorldCSP() const override; bool IsSVGImageChromeClient() const override; - void CountUsage(UseCounter::Feature) const override; - void CountDeprecation(UseCounter::Feature) const override; + void CountUsage(WebFeature) const override; + void CountDeprecation(WebFeature) const override; bool ShouldBlockFetchByMixedContentCheck( const ResourceRequest&, const KURL&,
diff --git a/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp b/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp index ada5b3d..d7252ed 100644 --- a/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp +++ b/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp
@@ -129,10 +129,10 @@ return; if (document->IsSecureContext()) { - UseCounter::Count(document, UseCounter::kApplicationCacheAPISecureOrigin); + UseCounter::Count(document, WebFeature::kApplicationCacheAPISecureOrigin); } else { Deprecation::CountDeprecation( - document, UseCounter::kApplicationCacheAPIInsecureOrigin); + document, WebFeature::kApplicationCacheAPIInsecureOrigin); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature::kApplicationCacheAPIInsecureHost);
diff --git a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp index 54aa2d7..32577c3 100644 --- a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp +++ b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp
@@ -142,14 +142,14 @@ } if (document->IsSecureContext()) { UseCounter::Count(document, - UseCounter::kApplicationCacheManifestSelectSecureOrigin); + WebFeature::kApplicationCacheManifestSelectSecureOrigin); UseCounter::CountCrossOriginIframe( - *document, UseCounter::kApplicationCacheManifestSelectSecureOrigin); + *document, WebFeature::kApplicationCacheManifestSelectSecureOrigin); } else { Deprecation::CountDeprecation( - document, UseCounter::kApplicationCacheManifestSelectInsecureOrigin); + document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin); Deprecation::CountDeprecationCrossOriginIframe( - *document, UseCounter::kApplicationCacheManifestSelectInsecureOrigin); + *document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature:: kApplicationCacheManifestSelectInsecureHost);
diff --git a/third_party/WebKit/Source/core/loader/private/FrameClientHintsPreferencesContext.cpp b/third_party/WebKit/Source/core/loader/private/FrameClientHintsPreferencesContext.cpp index cca8ec2..1dbc12ce 100644 --- a/third_party/WebKit/Source/core/loader/private/FrameClientHintsPreferencesContext.cpp +++ b/third_party/WebKit/Source/core/loader/private/FrameClientHintsPreferencesContext.cpp
@@ -13,19 +13,19 @@ : frame_(frame) {} void FrameClientHintsPreferencesContext::CountClientHintsDeviceRAM() { - UseCounter::Count(frame_, UseCounter::kClientHintsDeviceRAM); + UseCounter::Count(frame_, WebFeature::kClientHintsDeviceRAM); } void FrameClientHintsPreferencesContext::CountClientHintsDPR() { - UseCounter::Count(frame_, UseCounter::kClientHintsDPR); + UseCounter::Count(frame_, WebFeature::kClientHintsDPR); } void FrameClientHintsPreferencesContext::CountClientHintsResourceWidth() { - UseCounter::Count(frame_, UseCounter::kClientHintsResourceWidth); + UseCounter::Count(frame_, WebFeature::kClientHintsResourceWidth); } void FrameClientHintsPreferencesContext::CountClientHintsViewportWidth() { - UseCounter::Count(frame_, UseCounter::kClientHintsViewportWidth); + UseCounter::Count(frame_, WebFeature::kClientHintsViewportWidth); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/page/AutoscrollController.cpp b/third_party/WebKit/Source/core/page/AutoscrollController.cpp index b3e6cdf..b0c6af1 100644 --- a/third_party/WebKit/Source/core/page/AutoscrollController.cpp +++ b/third_party/WebKit/Source/core/page/AutoscrollController.cpp
@@ -193,7 +193,7 @@ autoscroll_layout_object_ = scrollable; drag_and_drop_autoscroll_start_time_ = event_time; UseCounter::Count(autoscroll_layout_object_->GetFrame(), - UseCounter::kDragAndDropScrollStart); + WebFeature::kDragAndDropScrollStart); StartAutoscroll(); } else if (autoscroll_layout_object_ != scrollable) { drag_and_drop_autoscroll_start_time_ = event_time; @@ -243,7 +243,7 @@ did_latch_for_middle_click_autoscroll_ = false; UseCounter::Count(autoscroll_layout_object_->GetFrame(), - UseCounter::kMiddleClickAutoscrollStart); + WebFeature::kMiddleClickAutoscrollStart); StartAutoscroll(); }
diff --git a/third_party/WebKit/Source/core/page/ChromeClient.cpp b/third_party/WebKit/Source/core/page/ChromeClient.cpp index 4b08bd7..5cdc4a9 100644 --- a/third_party/WebKit/Source/core/page/ChromeClient.cpp +++ b/third_party/WebKit/Source/core/page/ChromeClient.cpp
@@ -219,7 +219,7 @@ } if (frame->GetDocument()->IsSandboxed(kSandboxModals)) { - UseCounter::Count(frame, UseCounter::kDialogInSandboxedContext); + UseCounter::Count(frame, WebFeature::kDialogInSandboxedContext); frame->Console().AddMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Ignored call to 'print()'. The document is sandboxed, and the "
diff --git a/third_party/WebKit/Source/core/page/CreateWindow.cpp b/third_party/WebKit/Source/core/page/CreateWindow.cpp index 88aa2ad..6d027e7 100644 --- a/third_party/WebKit/Source/core/page/CreateWindow.cpp +++ b/third_party/WebKit/Source/core/page/CreateWindow.cpp
@@ -403,7 +403,7 @@ ? KURL(kParsedURLString, g_empty_string) : first_frame.GetDocument()->CompleteURL(url_string); if (!completed_url.IsEmpty() && !completed_url.IsValid()) { - UseCounter::Count(active_frame, UseCounter::kWindowOpenWithInvalidURL); + UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL); exception_state.ThrowDOMException( kSyntaxError, "Unable to open a window with invalid URL '" + completed_url.GetString() + "'.\n");
diff --git a/third_party/WebKit/Source/core/page/FrameTree.cpp b/third_party/WebKit/Source/core/page/FrameTree.cpp index da809e9b..d12d5c44 100644 --- a/third_party/WebKit/Source/core/page/FrameTree.cpp +++ b/third_party/WebKit/Source/core/page/FrameTree.cpp
@@ -57,10 +57,10 @@ : (Top().IsLocalFrame() ? ToLocalFrame(&Top()) : nullptr); if (frame) { UseCounter::Count(frame, - UseCounter::kCrossOriginMainFrameNulledNameAccessed); + WebFeature::kCrossOriginMainFrameNulledNameAccessed); if (!name_.IsEmpty()) { UseCounter::Count( - frame, UseCounter::kCrossOriginMainFrameNulledNonEmptyNameAccessed); + frame, WebFeature::kCrossOriginMainFrameNulledNonEmptyNameAccessed); } } }
diff --git a/third_party/WebKit/Source/core/page/PointerLockController.cpp b/third_party/WebKit/Source/core/page/PointerLockController.cpp index 16a10efe..a066783 100644 --- a/third_party/WebKit/Source/core/page/PointerLockController.cpp +++ b/third_party/WebKit/Source/core/page/PointerLockController.cpp
@@ -50,10 +50,10 @@ } UseCounter::CountCrossOriginIframe( - target->GetDocument(), UseCounter::kElementRequestPointerLockIframe); + target->GetDocument(), WebFeature::kElementRequestPointerLockIframe); if (target->IsInShadowTree()) { UseCounter::Count(target->GetDocument(), - UseCounter::kElementRequestPointerLockInShadow); + WebFeature::kElementRequestPointerLockInShadow); } if (target->GetDocument().IsSandboxed(kSandboxPointerLock)) {
diff --git a/third_party/WebKit/Source/core/paint/PaintInvalidationCapableScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintInvalidationCapableScrollableArea.cpp index f226cca..8eceda9 100644 --- a/third_party/WebKit/Source/core/paint/PaintInvalidationCapableScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintInvalidationCapableScrollableArea.cpp
@@ -241,7 +241,7 @@ void PaintInvalidationCapableScrollableArea::DidScrollWithScrollbar( ScrollbarPart part, ScrollbarOrientation orientation) { - UseCounter::Feature scrollbar_use_uma; + WebFeature scrollbar_use_uma; switch (part) { case kBackButtonStartPart: case kForwardButtonStartPart: @@ -249,21 +249,21 @@ case kForwardButtonEndPart: scrollbar_use_uma = (orientation == kVerticalScrollbar - ? UseCounter::kScrollbarUseVerticalScrollbarButton - : UseCounter::kScrollbarUseHorizontalScrollbarButton); + ? WebFeature::kScrollbarUseVerticalScrollbarButton + : WebFeature::kScrollbarUseHorizontalScrollbarButton); break; case kThumbPart: scrollbar_use_uma = (orientation == kVerticalScrollbar - ? UseCounter::kScrollbarUseVerticalScrollbarThumb - : UseCounter::kScrollbarUseHorizontalScrollbarThumb); + ? WebFeature::kScrollbarUseVerticalScrollbarThumb + : WebFeature::kScrollbarUseHorizontalScrollbarThumb); break; case kBackTrackPart: case kForwardTrackPart: scrollbar_use_uma = (orientation == kVerticalScrollbar - ? UseCounter::kScrollbarUseVerticalScrollbarTrack - : UseCounter::kScrollbarUseHorizontalScrollbarTrack); + ? WebFeature::kScrollbarUseVerticalScrollbarTrack + : WebFeature::kScrollbarUseHorizontalScrollbarTrack); break; default: return;
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp index 38c53c9..2d9eb0c 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp
@@ -328,10 +328,12 @@ ShouldRespectOverflowClipType respect_overflow_clip = ShouldRespectOverflowClip(paint_flags, paint_layer_.GetLayoutObject()); + bool should_create_subsequence = ShouldCreateSubsequence( + paint_layer_, context, painting_info_arg, paint_flags); + Optional<SubsequenceRecorder> subsequence_recorder; bool should_clear_empty_paint_phase_flags = false; - if (ShouldCreateSubsequence(paint_layer_, context, painting_info_arg, - paint_flags)) { + if (should_create_subsequence) { if (!ShouldRepaintSubsequence(paint_layer_, painting_info_arg, respect_overflow_clip, subpixel_accumulation, should_clear_empty_paint_phase_flags) && @@ -519,8 +521,11 @@ properties.property_tree_state = *local_border_box_properties; properties.backface_hidden = paint_layer_.GetLayoutObject().HasHiddenBackface(); - content_scoped_paint_chunk_properties.emplace(context.GetPaintController(), - paint_layer_, properties); + content_scoped_paint_chunk_properties.emplace( + context.GetPaintController(), paint_layer_, properties, + // Force a new paint chunk, since it is required for subsequence + // caching. + should_create_subsequence ? ForceNewChunk : DontForceNewChunk); } bool selection_only =
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp index 64476fb..6cb84837 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainterTest.cpp
@@ -86,7 +86,6 @@ " <div id='content2' style='position: absolute; width: 100px; height: " "100px; background-color: green'></div>" "</div>"); - GetDocument().View()->UpdateAllLifecyclePhases(); LayoutObject& container1 = *GetDocument().getElementById("container1")->GetLayoutObject(); @@ -105,6 +104,17 @@ TestDisplayItem(content1, kBackgroundType), TestDisplayItem(container2, kBackgroundType), TestDisplayItem(content2, kBackgroundType)); + + // check that new paint chunks were forced for |container1| and + // |container2|. + Vector<PaintChunk> paint_chunks = + RootPaintController().GetPaintArtifact().PaintChunks(); + EXPECT_EQ(3u, paint_chunks.size()); + EXPECT_EQ(GetLayoutView().Layer(), &paint_chunks[0].id->client); + EXPECT_EQ(ToLayoutBoxModelObject(container1).Layer(), + &paint_chunks[1].id->client); + EXPECT_EQ(ToLayoutBoxModelObject(container2).Layer(), + &paint_chunks[2].id->client); } else { EXPECT_DISPLAY_LIST( RootPaintController().GetDisplayItemList(), 5,
diff --git a/third_party/WebKit/Source/core/paint/ThemePainter.cpp b/third_party/WebKit/Source/core/paint/ThemePainter.cpp index 40ba4fc..84f8562 100644 --- a/third_party/WebKit/Source/core/paint/ThemePainter.cpp +++ b/third_party/WebKit/Source/core/paint/ThemePainter.cpp
@@ -70,19 +70,19 @@ if (part == kButtonPart && o.GetNode()) { UseCounter::Count(o.GetDocument(), - UseCounter::kCSSValueAppearanceButtonRendered); + WebFeature::kCSSValueAppearanceButtonRendered); if (isHTMLAnchorElement(o.GetNode())) { UseCounter::Count(o.GetDocument(), - UseCounter::kCSSValueAppearanceButtonForAnchor); + WebFeature::kCSSValueAppearanceButtonForAnchor); } else if (isHTMLButtonElement(o.GetNode())) { UseCounter::Count(o.GetDocument(), - UseCounter::kCSSValueAppearanceButtonForButton); + WebFeature::kCSSValueAppearanceButtonForButton); } else if (isHTMLInputElement(o.GetNode()) && toHTMLInputElement(o.GetNode())->IsTextButton()) { // Text buttons (type=button, reset, submit) has // -webkit-appearance:push-button by default. UseCounter::Count(o.GetNode()->GetDocument(), - UseCounter::kCSSValueAppearanceButtonForOtherButtons); + WebFeature::kCSSValueAppearanceButtonForOtherButtons); } } @@ -178,16 +178,16 @@ switch (o.StyleRef().Appearance()) { case kTextFieldPart: UseCounter::Count(o.GetDocument(), - UseCounter::kCSSValueAppearanceTextFieldRendered); + WebFeature::kCSSValueAppearanceTextFieldRendered); if (isHTMLInputElement(o.GetNode())) { HTMLInputElement* input = toHTMLInputElement(o.GetNode()); if (input->type() == InputTypeNames::search) { UseCounter::Count(o.GetDocument(), - UseCounter::kCSSValueAppearanceTextFieldForSearch); + WebFeature::kCSSValueAppearanceTextFieldForSearch); } else if (input->IsTextField()) { UseCounter::Count( o.GetDocument(), - UseCounter::kCSSValueAppearanceTextFieldForTextField); + WebFeature::kCSSValueAppearanceTextFieldForTextField); } } return PaintTextField(o, paint_info, r);
diff --git a/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp b/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp index 0336213..416baf6 100644 --- a/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp +++ b/third_party/WebKit/Source/core/svg/SVGAnimatedHref.cpp
@@ -45,20 +45,20 @@ String SVGAnimatedHref::baseVal() { UseCounter::Count(contextElement()->GetDocument(), - UseCounter::kSVGHrefBaseVal); + WebFeature::kSVGHrefBaseVal); return BackingString()->SVGAnimatedString::baseVal(); } void SVGAnimatedHref::setBaseVal(const String& value, ExceptionState& exception_state) { UseCounter::Count(contextElement()->GetDocument(), - UseCounter::kSVGHrefBaseVal); + WebFeature::kSVGHrefBaseVal); return BackingString()->SVGAnimatedString::setBaseVal(value, exception_state); } String SVGAnimatedHref::animVal() { UseCounter::Count(contextElement()->GetDocument(), - UseCounter::kSVGHrefAnimVal); + WebFeature::kSVGHrefAnimVal); return BackingString()->SVGAnimatedString::animVal(); }
diff --git a/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp b/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp index 972c960..88889ea 100644 --- a/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp
@@ -40,7 +40,7 @@ calc_mode_(kCalcModeLinear), animation_mode_(kNoAnimation) { DCHECK(RuntimeEnabledFeatures::SMILEnabled()); - UseCounter::Count(document, UseCounter::kSVGAnimationElement); + UseCounter::Count(document, WebFeature::kSVGAnimationElement); } bool SVGAnimationElement::ParseValues(const String& value, @@ -287,20 +287,20 @@ DEFINE_STATIC_LOCAL(const AtomicString, paced, ("paced")); DEFINE_STATIC_LOCAL(const AtomicString, spline, ("spline")); if (calc_mode == discrete) { - UseCounter::Count(GetDocument(), UseCounter::kSVGCalcModeDiscrete); + UseCounter::Count(GetDocument(), WebFeature::kSVGCalcModeDiscrete); SetCalcMode(kCalcModeDiscrete); } else if (calc_mode == linear) { if (isSVGAnimateMotionElement(*this)) - UseCounter::Count(GetDocument(), UseCounter::kSVGCalcModeLinear); + UseCounter::Count(GetDocument(), WebFeature::kSVGCalcModeLinear); // else linear is the default. SetCalcMode(kCalcModeLinear); } else if (calc_mode == paced) { if (!isSVGAnimateMotionElement(*this)) - UseCounter::Count(GetDocument(), UseCounter::kSVGCalcModePaced); + UseCounter::Count(GetDocument(), WebFeature::kSVGCalcModePaced); // else paced is the default. SetCalcMode(kCalcModePaced); } else if (calc_mode == spline) { - UseCounter::Count(GetDocument(), UseCounter::kSVGCalcModeSpline); + UseCounter::Count(GetDocument(), WebFeature::kSVGCalcModeSpline); SetCalcMode(kCalcModeSpline); } else SetCalcMode(isSVGAnimateMotionElement(*this) ? kCalcModePaced @@ -590,7 +590,7 @@ } if (animation_valid_ && (IsAdditive() || IsAccumulated())) - UseCounter::Count(&GetDocument(), UseCounter::kSVGSMILAdditiveAnimation); + UseCounter::Count(&GetDocument(), WebFeature::kSVGSMILAdditiveAnimation); } void SVGAnimationElement::UpdateAnimation(float percent,
diff --git a/third_party/WebKit/Source/core/svg/SVGElement.cpp b/third_party/WebKit/Source/core/svg/SVGElement.cpp index e39c477..9f1c5fe 100644 --- a/third_party/WebKit/Source/core/svg/SVGElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGElement.cpp
@@ -363,7 +363,7 @@ } if (TransformUsesBoxSize(*style, apply_transform_origin)) - UseCounter::Count(GetDocument(), UseCounter::kTransformUsesBoxSizeOnSVG); + UseCounter::Count(GetDocument(), WebFeature::kTransformUsesBoxSizeOnSVG); // CSS transforms operate with pre-scaled lengths. To make this work with // SVG (which applies the zoom factor globally, at the root level) we
diff --git a/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp b/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp index 67d55d0..f5d42ba 100644 --- a/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp
@@ -52,7 +52,7 @@ AddToPropertyMap(width_); AddToPropertyMap(height_); - UseCounter::Count(document, UseCounter::kSVGForeignObjectElement); + UseCounter::Count(document, WebFeature::kSVGForeignObjectElement); } DEFINE_TRACE(SVGForeignObjectElement) {
diff --git a/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp b/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp index 1f32546..35b568d 100644 --- a/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
@@ -92,7 +92,7 @@ AddToPropertyMap(width_); AddToPropertyMap(height_); - UseCounter::Count(doc, UseCounter::kSVGSVGElement); + UseCounter::Count(doc, WebFeature::kSVGSVGElement); } DEFINE_NODE_FACTORY(SVGSVGElement) @@ -523,9 +523,9 @@ Node::InsertionNotificationRequest SVGSVGElement::InsertedInto( ContainerNode* root_parent) { if (root_parent->isConnected()) { - UseCounter::Count(GetDocument(), UseCounter::kSVGSVGElementInDocument); + UseCounter::Count(GetDocument(), WebFeature::kSVGSVGElementInDocument); if (root_parent->GetDocument().IsXMLDocument()) - UseCounter::Count(GetDocument(), UseCounter::kSVGSVGElementInXMLDocument); + UseCounter::Count(GetDocument(), WebFeature::kSVGSVGElementInXMLDocument); if (RuntimeEnabledFeatures::SMILEnabled()) { GetDocument().AccessSVGExtensions().AddTimeContainer(this); @@ -708,7 +708,7 @@ SVGViewSpec* view_spec = SVGViewSpec::CreateForElement(*this); if (view_spec->ParseViewSpec(fragment_identifier)) { UseCounter::Count(GetDocument(), - UseCounter::kSVGSVGElementFragmentSVGView); + WebFeature::kSVGSVGElementFragmentSVGView); SetViewSpec(view_spec); return; } @@ -738,7 +738,7 @@ SVGViewSpec* view_spec = SVGViewSpec::CreateForElement(*svg); view_spec->InheritViewAttributesFromElement(view_element); UseCounter::Count(svg->GetDocument(), - UseCounter::kSVGSVGElementFragmentSVGViewElement); + WebFeature::kSVGSVGElementFragmentSVGViewElement); svg->SetViewSpec(view_spec); }
diff --git a/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp b/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp index 8b9dceb3..6221fc2 100644 --- a/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp
@@ -28,7 +28,7 @@ inline SVGSwitchElement::SVGSwitchElement(Document& document) : SVGGraphicsElement(SVGNames::switchTag, document) { - UseCounter::Count(document, UseCounter::kSVGSwitchElement); + UseCounter::Count(document, WebFeature::kSVGSwitchElement); } DEFINE_NODE_FACTORY(SVGSwitchElement)
diff --git a/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp b/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp index d5e3180..9a1ea04 100644 --- a/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp
@@ -249,12 +249,12 @@ DEFINE_STATIC_LOCAL(const AtomicString, preserve_string, ("preserve")); if (value == preserve_string) { - UseCounter::Count(GetDocument(), UseCounter::kWhiteSpacePreFromXMLSpace); + UseCounter::Count(GetDocument(), WebFeature::kWhiteSpacePreFromXMLSpace); AddPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre); } else { UseCounter::Count(GetDocument(), - UseCounter::kWhiteSpaceNowrapFromXMLSpace); + WebFeature::kWhiteSpaceNowrapFromXMLSpace); AddPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValueNowrap); }
diff --git a/third_party/WebKit/Source/core/svg/SVGViewElement.cpp b/third_party/WebKit/Source/core/svg/SVGViewElement.cpp index 9708903..62a027b 100644 --- a/third_party/WebKit/Source/core/svg/SVGViewElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGViewElement.cpp
@@ -27,7 +27,7 @@ inline SVGViewElement::SVGViewElement(Document& document) : SVGElement(SVGNames::viewTag, document), SVGFitToViewBox(this) { - UseCounter::Count(document, UseCounter::kSVGViewElement); + UseCounter::Count(document, WebFeature::kSVGViewElement); } DEFINE_NODE_FACTORY(SVGViewElement)
diff --git a/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp b/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp index 28d71c34..e441f728 100644 --- a/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp +++ b/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -499,7 +499,7 @@ return earliest_fire_time; } - UseCounter::Count(&GetDocument(), UseCounter::kSVGSMILAnimationAppliedEffect); + UseCounter::Count(&GetDocument(), WebFeature::kSVGSMILAnimationAppliedEffect); std::sort(animations_to_apply.begin(), animations_to_apply.end(), PriorityCompare(elapsed));
diff --git a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp index 1e6c961..150a0de 100644 --- a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp +++ b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
@@ -305,10 +305,10 @@ if (!root_parent->isConnected()) return kInsertionDone; - UseCounter::Count(GetDocument(), UseCounter::kSVGSMILElementInDocument); + UseCounter::Count(GetDocument(), WebFeature::kSVGSMILElementInDocument); if (GetDocument().IsLoadCompleted()) { UseCounter::Count(&GetDocument(), - UseCounter::kSVGSMILElementInsertedAfterLoad); + WebFeature::kSVGSMILElementInsertedAfterLoad); } SVGSVGElement* owner = ownerSVGElement(); @@ -458,13 +458,13 @@ if (base_id.IsEmpty()) return false; UseCounter::Count(&GetDocument(), - UseCounter::kSVGSMILBeginOrEndSyncbaseValue); + WebFeature::kSVGSMILBeginOrEndSyncbaseValue); type = Condition::kSyncbase; } else if (name_string.StartsWith("accesskey(")) { // FIXME: accesskey() support. type = Condition::kAccessKey; } else { - UseCounter::Count(&GetDocument(), UseCounter::kSVGSMILBeginOrEndEventValue); + UseCounter::Count(&GetDocument(), WebFeature::kSVGSMILBeginOrEndEventValue); type = Condition::kEventBase; }
diff --git a/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp b/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp index 6199c5b..26aa2caec 100644 --- a/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp +++ b/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp
@@ -640,7 +640,7 @@ if (SVGSVGElement* root_element = SvgRootElement(page_.Get())) { if (root_element->TimeContainer()->HasAnimations()) { UseCounter::Count(document, - UseCounter::kSVGSMILAnimationInImageRegardlessOfCache); + WebFeature::kSVGSMILAnimationInImageRegardlessOfCache); } } }
diff --git a/third_party/WebKit/Source/core/testing/Internals.cpp b/third_party/WebKit/Source/core/testing/Internals.cpp index 0eb0e411..f49dca0 100644 --- a/third_party/WebKit/Source/core/testing/Internals.cpp +++ b/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -3276,10 +3276,9 @@ } bool Internals::isUseCounted(Document* document, uint32_t feature) { - if (feature >= UseCounter::kNumberOfFeatures) + if (feature >= static_cast<uint32_t>(WebFeature::kNumberOfFeatures)) return false; - return UseCounter::IsCounted(*document, - static_cast<UseCounter::Feature>(feature)); + return UseCounter::IsCounted(*document, static_cast<WebFeature>(feature)); } bool Internals::isCSSPropertyUseCounted(Document* document, @@ -3297,13 +3296,12 @@ uint32_t feature) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); - if (feature >= UseCounter::kNumberOfFeatures) { + if (feature >= static_cast<uint32_t>(WebFeature::kNumberOfFeatures)) { resolver->Reject(); return promise; } - UseCounter::Feature use_counter_feature = - static_cast<UseCounter::Feature>(feature); + WebFeature use_counter_feature = static_cast<WebFeature>(feature); if (UseCounter::IsCounted(*document, use_counter_feature)) { resolver->Resolve(); return promise;
diff --git a/third_party/WebKit/Source/core/testing/Internals.h b/third_party/WebKit/Source/core/testing/Internals.h index e997305..d31c67a 100644 --- a/third_party/WebKit/Source/core/testing/Internals.h +++ b/third_party/WebKit/Source/core/testing/Internals.h
@@ -517,7 +517,7 @@ float visualViewportScrollY(); // Return true if the given use counter exists for the given document. - // |feature| must be one of the values from the UseCounter::Feature enum. + // |feature| must be one of the values from the WebFeature enum. bool isUseCounted(Document*, uint32_t feature); bool isCSSPropertyUseCounted(Document*, const String&); bool isAnimatedCSSPropertyUseCounted(Document*, const String&);
diff --git a/third_party/WebKit/Source/core/testing/WorkerInternals.cpp b/third_party/WebKit/Source/core/testing/WorkerInternals.cpp index a0cf2de9..04ca57507 100644 --- a/third_party/WebKit/Source/core/testing/WorkerInternals.cpp +++ b/third_party/WebKit/Source/core/testing/WorkerInternals.cpp
@@ -24,25 +24,25 @@ void WorkerInternals::countFeature(ScriptState* script_state, uint32_t feature, ExceptionState& exception_state) { - if (UseCounter::kNumberOfFeatures <= feature) { + if (static_cast<uint32_t>(WebFeature::kNumberOfFeatures) <= feature) { exception_state.ThrowTypeError( - "The given feature does not exist in UseCounter::Feature."); + "The given feature does not exist in WebFeature."); return; } UseCounter::Count(ExecutionContext::From(script_state), - static_cast<UseCounter::Feature>(feature)); + static_cast<WebFeature>(feature)); } void WorkerInternals::countDeprecation(ScriptState* script_state, uint32_t feature, ExceptionState& exception_state) { - if (UseCounter::kNumberOfFeatures <= feature) { + if (static_cast<uint32_t>(WebFeature::kNumberOfFeatures) <= feature) { exception_state.ThrowTypeError( - "The given feature does not exist in UseCounter::Feature."); + "The given feature does not exist in WebFeature."); return; } Deprecation::CountDeprecation(ExecutionContext::From(script_state), - static_cast<UseCounter::Feature>(feature)); + static_cast<WebFeature>(feature)); } void WorkerInternals::collectGarbage(ScriptState* script_state) {
diff --git a/third_party/WebKit/Source/core/timing/Performance.cpp b/third_party/WebKit/Source/core/timing/Performance.cpp index 97edfa909..a60c520b 100644 --- a/third_party/WebKit/Source/core/timing/Performance.cpp +++ b/third_party/WebKit/Source/core/timing/Performance.cpp
@@ -156,7 +156,7 @@ if (HasObserverFor(PerformanceEntry::kLongTask)) { UseCounter::Count(&GetFrame()->LocalFrameRoot(), - UseCounter::kLongTaskObserver); + WebFeature::kLongTaskObserver); GetFrame()->GetPerformanceMonitor()->Subscribe( PerformanceMonitor::kLongTask, kLongTaskThreshold, this); } else {
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp index 6484bdf..904e27f9 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp
@@ -269,7 +269,7 @@ return false; if (timing_allow_origin_string == "*") { - UseCounter::Count(context, UseCounter::kStarInTimingAllowOrigin); + UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin); return true; } @@ -277,9 +277,9 @@ Vector<String> timing_allow_origins; timing_allow_origin_string.GetString().Split(' ', timing_allow_origins); if (timing_allow_origins.size() > 1) - UseCounter::Count(context, UseCounter::kMultipleOriginsInTimingAllowOrigin); + UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin); else if (timing_allow_origins.size() == 1) - UseCounter::Count(context, UseCounter::kSingleOriginInTimingAllowOrigin); + UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin); for (const String& allow_origin : timing_allow_origins) { if (allow_origin == security_origin) return true;
diff --git a/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp b/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp index e7f9cb0..b06620fb 100644 --- a/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp +++ b/third_party/WebKit/Source/core/xml/DocumentXSLT.cpp
@@ -91,7 +91,7 @@ void DocumentXSLT::ApplyXSLTransform(Document& document, ProcessingInstruction* pi) { DCHECK(!pi->IsLoading()); - UseCounter::Count(document, UseCounter::kXSLProcessingInstruction); + UseCounter::Count(document, WebFeature::kXSLProcessingInstruction); XSLTProcessor* processor = XSLTProcessor::Create(document); processor->SetXSLStyleSheet(ToXSLStyleSheet(pi->sheet())); String result_mime_type;
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index d5ab79d..3de3229 100644 --- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -666,7 +666,7 @@ return &g_global_descriptor; UseCounter::Count(XMLDocumentParserScope::current_document_, - UseCounter::kXMLExternalResourceLoad); + WebFeature::kXMLExternalResourceLoad); return new SharedBufferReader(data); } @@ -783,7 +783,7 @@ parsing_fragment_(false) { // This is XML being used as a document resource. if (frame_view && document.IsXMLDocument()) - UseCounter::Count(document, UseCounter::kXMLDocument); + UseCounter::Count(document, WebFeature::kXMLDocument); } XMLDocumentParser::XMLDocumentParser(DocumentFragment* fragment,
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index c111956..1ed4058 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
@@ -648,7 +648,7 @@ if (!GetDocument()->ProcessingBeforeUnload()) { Deprecation::CountDeprecation( GetExecutionContext(), - UseCounter::kXMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload); + WebFeature::kXMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload); } } @@ -687,7 +687,7 @@ v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (isolate && v8::MicrotasksScope::IsRunningMicrotasks(isolate)) { UseCounter::Count(GetExecutionContext(), - UseCounter::kDuring_Microtask_SyncXHR); + WebFeature::kDuring_Microtask_SyncXHR); } } @@ -979,7 +979,7 @@ if (!same_origin_request_ && include_credentials) { UseCounter::Count(&execution_context, - UseCounter::kXMLHttpRequestCrossOriginWithCredentials); + WebFeature::kXMLHttpRequestCrossOriginWithCredentials); } // We also remember whether upload events should be allowed for this request @@ -1053,7 +1053,7 @@ if (async_) { UseCounter::Count(&execution_context, - UseCounter::kXMLHttpRequestAsynchronous); + WebFeature::kXMLHttpRequestAsynchronous); if (upload_) request.SetReportUploadProgress(true); @@ -1067,7 +1067,7 @@ } // Use count for XHR synchronous requests. - UseCounter::Count(&execution_context, UseCounter::kXMLHttpRequestSynchronous); + UseCounter::Count(&execution_context, WebFeature::kXMLHttpRequestSynchronous); ThreadableLoader::LoadResourceSynchronously(execution_context, request, *this, options, resource_loader_options);
diff --git a/third_party/WebKit/Source/devtools/BUILD.gn b/third_party/WebKit/Source/devtools/BUILD.gn index 25ec3a48..22f3c89 100644 --- a/third_party/WebKit/Source/devtools/BUILD.gn +++ b/third_party/WebKit/Source/devtools/BUILD.gn
@@ -171,6 +171,7 @@ "front_end/dom_extension/DOMExtension.js", "front_end/dom_extension/module.json", "front_end/elements/breadcrumbs.css", + "front_end/elements/classesPaneWidget.css", "front_end/elements/ClassesPaneWidget.js", "front_end/elements/ColorSwatchPopoverIcon.js", "front_end/elements/ComputedStyleModel.js", @@ -180,6 +181,7 @@ "front_end/elements/elementsPanel.css", "front_end/elements/ElementsPanel.js", "front_end/elements/ElementsSidebarPane.js", + "front_end/elements/elementStatePaneWidget.css", "front_end/elements/ElementStatePaneWidget.js", "front_end/elements/ElementsTreeElement.js", "front_end/elements/ElementsTreeElementHighlighter.js",
diff --git a/third_party/WebKit/Source/devtools/front_end/audits2/Audits2Panel.js b/third_party/WebKit/Source/devtools/front_end/audits2/Audits2Panel.js index b78a30a..bc5f597 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits2/Audits2Panel.js +++ b/third_party/WebKit/Source/devtools/front_end/audits2/Audits2Panel.js
@@ -169,6 +169,10 @@ this._dialog.setOutsideClickCallback(event => event.consume(true)); var root = UI.createShadowRootWithCoreStyles(this._dialog.contentElement, 'audits2/audits2Dialog.css'); var auditsViewElement = root.createChild('div', 'audits2-view'); + + var closeButton = auditsViewElement.createChild('div', 'dialog-close-button', 'dt-close-button'); + closeButton.addEventListener('click', () => this._cancelAndClose()); + var uiElement = auditsViewElement.createChild('div'); var headerElement = uiElement.createChild('header'); this._headerTitleElement = headerElement.createChild('p'); @@ -304,6 +308,11 @@ delete this._emulationOutlineEnabledBefore; } + _cancelAndClose() { + this._cancel(); + this._hideDialog(); + } + _cancel() { if (this._auditRunning) { this._updateStatus(Common.UIString('Cancelling\u2026'));
diff --git a/third_party/WebKit/Source/devtools/front_end/audits2/audits2Dialog.css b/third_party/WebKit/Source/devtools/front_end/audits2/audits2Dialog.css index ec1f492e..3d098c74 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits2/audits2Dialog.css +++ b/third_party/WebKit/Source/devtools/front_end/audits2/audits2Dialog.css
@@ -10,6 +10,12 @@ align-items: center; } +.audits2-view .dialog-close-button { + position: absolute; + top: 10px; + right: 10px; +} + header { color: #666; font-weight: bold;
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js b/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js index 69a2772b..233e9e3 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/BreakpointManager.js
@@ -152,7 +152,7 @@ breakpointItem.enabled); } } - this._provisionalBreakpoints.removeAll(url); + this._provisionalBreakpoints.deleteAll(url); this._storage.unmute(); } @@ -412,7 +412,7 @@ breakpoints.remove(breakpoint); if (removeFromStorage) this._storage._removeBreakpoint(breakpoint); - this._provisionalBreakpoints.remove(breakpoint._url, breakpoint); + this._provisionalBreakpoints.delete(breakpoint._url, breakpoint); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js index f0278e20..5ca3e042e 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js
@@ -179,9 +179,9 @@ */ _disposeLocation(location) { if (location._header) - this._locations.remove(location._header, location); + this._locations.delete(location._header, location); else - this._unboundLocations.remove(location._url, location); + this._unboundLocations.delete(location._url, location); } /** @@ -205,7 +205,7 @@ this._locations.set(header, location); location.update(); } - this._unboundLocations.removeAll(header.sourceURL); + this._unboundLocations.deleteAll(header.sourceURL); } /** @@ -218,7 +218,7 @@ this._unboundLocations.set(location._url, location); location.update(); } - this._locations.removeAll(header); + this._locations.deleteAll(header); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewport.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewport.js index 6341e4a..f61e49ac 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewport.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewport.js
@@ -466,9 +466,9 @@ continue; chars += Components.Linkifier.untruncatedNodeText(node).length; } - // If the selection offset is at the end of a link's ellipsis, use the untruncated length as offset. + // If the selected node text was truncated, treat any non-zero offset as the full length. var untruncatedContainerLength = Components.Linkifier.untruncatedNodeText(selectionNode).length; - if (offset === 1 && untruncatedContainerLength > offset) + if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length) offset = untruncatedContainerLength; return chars + offset; }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js index 747bd96..e9de728 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ClassesPaneWidget.js
@@ -6,12 +6,13 @@ */ Elements.ClassesPaneWidget = class extends UI.Widget { constructor() { - super(); - this.element.className = 'styles-element-classes-pane'; - var container = this.element.createChild('div', 'title-container'); + super(true); + this.registerRequiredCSS('elements/classesPaneWidget.css'); + this.contentElement.className = 'styles-element-classes-pane'; + var container = this.contentElement.createChild('div', 'title-container'); this._input = container.createChild('div', 'new-class-input monospace'); this.setDefaultFocusedElement(this._input); - this._classesContainer = this.element.createChild('div', 'source-code'); + this._classesContainer = this.contentElement.createChild('div', 'source-code'); this._classesContainer.classList.add('styles-element-classes-container'); this._prompt = new Elements.ClassesPaneWidget.ClassNamePrompt(); this._prompt.setAutocompletionTimeout(0);
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js index 61d3b8c..a4c3edfe 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementStatePaneWidget.js
@@ -6,9 +6,10 @@ */ Elements.ElementStatePaneWidget = class extends UI.Widget { constructor() { - super(); - this.element.className = 'styles-element-state-pane'; - this.element.createChild('div').createTextChild(Common.UIString('Force element state')); + super(true); + this.registerRequiredCSS('elements/elementStatePaneWidget.css'); + this.contentElement.className = 'styles-element-state-pane'; + this.contentElement.createChild('div').createTextChild(Common.UIString('Force element state')); var table = createElementWithClass('table', 'source-code'); var inputs = []; @@ -47,7 +48,7 @@ tr.appendChild(createCheckbox.call(null, 'focus')); tr.appendChild(createCheckbox.call(null, 'visited')); - this.element.appendChild(table); + this.contentElement.appendChild(table); UI.context.addFlavorChangeListener(SDK.DOMNode, this._update, this); }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js b/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js index 9a15951..b59b574a 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/EventListenersWidget.js
@@ -46,7 +46,8 @@ this._showFrameworkListenersSetting = Common.settings.createSetting('showFrameowkrListeners', true); this._showFrameworkListenersSetting.setTitle(Common.UIString('Framework listeners')); this._showFrameworkListenersSetting.addChangeListener(this._showFrameworkListenersChanged.bind(this)); - this._eventListenersView = new EventListeners.EventListenersView(this.element, this.update.bind(this)); + this._eventListenersView = new EventListeners.EventListenersView(this.update.bind(this)); + this._eventListenersView.show(this.element); var refreshButton = new UI.ToolbarButton(Common.UIString('Refresh'), 'largeicon-refresh'); refreshButton.addEventListener(UI.ToolbarButton.Events.Click, this.update.bind(this));
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/classesPaneWidget.css b/third_party/WebKit/Source/devtools/front_end/elements/classesPaneWidget.css new file mode 100644 index 0000000..66e35443 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/elements/classesPaneWidget.css
@@ -0,0 +1,37 @@ +/** + * 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. + */ + +.styles-element-classes-pane { + background-color: #f3f3f3; + border-bottom: 1px solid rgb(189, 189, 189); + padding: 6px 2px 2px; +} + +.styles-element-classes-container { + display: flex; + flex-wrap: wrap; + justify-content: flex-start; +} + +.styles-element-classes-pane label { + margin-right: 15px; +} + +.styles-element-classes-pane .title-container { + padding-bottom: 2px; +} + +.styles-element-classes-pane .new-class-input { + padding-left: 3px; + padding-right: 3px; + overflow: hidden; + border: 1px solid #ddd; + line-height: 15px; + margin-left: 3px; + width: calc(100% - 7px); + background-color: #fff; + cursor: text; +}
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/elementStatePaneWidget.css b/third_party/WebKit/Source/devtools/front_end/elements/elementStatePaneWidget.css new file mode 100644 index 0000000..ff0dd4c --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/elements/elementStatePaneWidget.css
@@ -0,0 +1,27 @@ +/** + * 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. + */ + +.styles-element-state-pane { + overflow: hidden; + height: 66px; + padding-left: 2px; + background-color: #f3f3f3; + border-bottom: 1px solid rgb(189, 189, 189); + margin-top: 0; +} + +.styles-element-state-pane > div { + margin: 8px 4px 6px; +} + +.styles-element-state-pane > table { + width: 100%; + border-spacing: 0; +} + +.styles-element-state-pane td { + padding: 0; +}
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/elementsPanel.css b/third_party/WebKit/Source/devtools/front_end/elements/elementsPanel.css index 76b0b62..ca322df 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/elementsPanel.css +++ b/third_party/WebKit/Source/devtools/front_end/elements/elementsPanel.css
@@ -259,13 +259,6 @@ padding-left: 0; } -.styles-element-state-pane { - overflow: hidden; - height: 66px; - padding-left: 2px; - border-bottom: 1px solid rgb(189, 189, 189); -} - @keyframes styles-element-state-pane-slidein { from { margin-top: -60px; @@ -296,57 +289,6 @@ flex-shrink: 0; } -.styles-element-state-pane { - background-color: #f3f3f3; - border-bottom: 1px solid rgb(189, 189, 189); - margin-top: 0; -} - -.styles-element-classes-pane { - background-color: #f3f3f3; - border-bottom: 1px solid rgb(189, 189, 189); - padding: 6px 2px 2px; -} - -.styles-element-classes-container { - display: flex; - flex-wrap: wrap; - justify-content: flex-start; -} - -.styles-element-classes-pane label { - margin-right: 15px; -} - -.styles-element-classes-pane .title-container { - padding-bottom: 2px; -} - -.styles-element-classes-pane .new-class-input { - padding-left: 3px; - padding-right: 3px; - overflow: hidden; - border: 1px solid #ddd; - line-height: 15px; - margin-left: 3px; - width: calc(100% - 7px); - background-color: #fff; - cursor: text; -} - -.styles-element-state-pane > div { - margin: 8px 4px 6px; -} - -.styles-element-state-pane > table { - width: 100%; - border-spacing: 0; -} - -.styles-element-state-pane td { - padding: 0; -} - .styles-animations-controls-pane > * { margin: 6px 4px; }
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/module.json b/third_party/WebKit/Source/devtools/front_end/elements/module.json index 7fe5b5a..bb50e908 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/module.json +++ b/third_party/WebKit/Source/devtools/front_end/elements/module.json
@@ -271,8 +271,10 @@ ], "resources": [ "breadcrumbs.css", + "classesPaneWidget.css", "computedStyleSidebarPane.css", "elementsPanel.css", + "elementStatePaneWidget.css", "elementsTreeOutline.css", "platformFontsWidget.css", "stylesSectionTree.css"
diff --git a/third_party/WebKit/Source/devtools/front_end/event_listeners/EventListenersView.js b/third_party/WebKit/Source/devtools/front_end/event_listeners/EventListenersView.js index 109bf64..e35dd93 100644 --- a/third_party/WebKit/Source/devtools/front_end/event_listeners/EventListenersView.js +++ b/third_party/WebKit/Source/devtools/front_end/event_listeners/EventListenersView.js
@@ -9,13 +9,12 @@ /** * @unrestricted */ -EventListeners.EventListenersView = class { +EventListeners.EventListenersView = class extends UI.VBox { /** - * @param {!Element} element * @param {function()} changeCallback */ - constructor(element, changeCallback) { - this._element = element; + constructor(changeCallback) { + super(); this._changeCallback = changeCallback; this._treeOutline = new UI.TreeOutlineInShadow(); this._treeOutline.hideOverflow(); @@ -23,7 +22,7 @@ this._treeOutline.registerRequiredCSS('event_listeners/eventListenersView.css'); this._treeOutline.setComparator(EventListeners.EventListenersTreeElement.comparator); this._treeOutline.element.classList.add('monospace'); - this._element.appendChild(this._treeOutline.element); + this.element.appendChild(this._treeOutline.element); this._emptyHolder = createElementWithClass('div', 'gray-info-message'); this._emptyHolder.textContent = Common.UIString('No event listeners'); this._linkifier = new Components.Linkifier(); @@ -191,7 +190,7 @@ allHidden = allHidden && eventType.hidden; } if (allHidden && !this._emptyHolder.parentNode) - this._element.appendChild(this._emptyHolder); + this.element.appendChild(this._emptyHolder); } reset() {
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js index 830ae477..9853ca3 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/Persistence.js
@@ -296,7 +296,7 @@ * @param {function()} listener */ unsubscribeFromBindingEvent(uiSourceCode, listener) { - this._subscribedBindingEventListeners.remove(uiSourceCode, listener); + this._subscribedBindingEventListeners.delete(uiSourceCode, listener); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/platform/utilities.js b/third_party/WebKit/Source/devtools/front_end/platform/utilities.js index 07435b1c..baffe72 100644 --- a/third_party/WebKit/Source/devtools/front_end/platform/utilities.js +++ b/third_party/WebKit/Source/devtools/front_end/platform/utilities.js
@@ -1225,7 +1225,7 @@ * @param {V} value * @return {boolean} */ - remove: function(key, value) { + delete: function(key, value) { var values = this.get(key); var result = values.delete(value); if (!values.size) @@ -1236,7 +1236,7 @@ /** * @param {K} key */ - removeAll: function(key) { + deleteAll: function(key) { this._map.delete(key); },
diff --git a/third_party/WebKit/Source/devtools/front_end/sass/ASTSourceMap.js b/third_party/WebKit/Source/devtools/front_end/sass/ASTSourceMap.js index 5a81f6a..5000d8a 100644 --- a/third_party/WebKit/Source/devtools/front_end/sass/ASTSourceMap.js +++ b/third_party/WebKit/Source/devtools/front_end/sass/ASTSourceMap.js
@@ -152,7 +152,7 @@ */ removeMapping(compiled, source) { this._compiledToSource.delete(compiled); - this._sourceToCompiled.remove(source, compiled); + this._sourceToCompiled.delete(source, compiled); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/SourceMapManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/SourceMapManager.js index c41b50d..2c884e4 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/SourceMapManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/SourceMapManager.js
@@ -171,7 +171,7 @@ function onSourceMap(sourceMapURL, sourceMap) { this._sourceMapLoadedForTest(); var clients = this._sourceMapURLToLoadingClients.get(sourceMapURL); - this._sourceMapURLToLoadingClients.removeAll(sourceMapURL); + this._sourceMapURLToLoadingClients.deleteAll(sourceMapURL); if (!clients.size) return; if (!sourceMap) { @@ -225,11 +225,11 @@ if (!sourceMapURL) return; if (!this._sourceMapURLToClients.hasValue(sourceMapURL, client)) { - if (this._sourceMapURLToLoadingClients.remove(sourceMapURL, client)) + if (this._sourceMapURLToLoadingClients.delete(sourceMapURL, client)) this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach, client); return; } - this._sourceMapURLToClients.remove(sourceMapURL, client); + this._sourceMapURLToClients.delete(sourceMapURL, client); var sourceMap = this._sourceMapByURL.get(sourceMapURL); if (!this._sourceMapURLToClients.has(sourceMapURL)) this._sourceMapByURL.delete(sourceMapURL);
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js index fc9d986..3c5dd18 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/NavigatorView.js
@@ -573,7 +573,7 @@ */ _removeUISourceCodeNode(node) { var uiSourceCode = node.uiSourceCode(); - this._uiSourceCodeNodes.remove(uiSourceCode, node); + this._uiSourceCodeNodes.delete(uiSourceCode, node); var project = uiSourceCode.project(); var target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); var frame = node.frame();
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/ObjectEventListenersSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/sources/ObjectEventListenersSidebarPane.js index 35440f1..620e252 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/ObjectEventListenersSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/ObjectEventListenersSidebarPane.js
@@ -8,13 +8,12 @@ Sources.ObjectEventListenersSidebarPane = class extends UI.VBox { constructor() { super(); - this.element.classList.add('event-listeners-sidebar-pane'); - this._refreshButton = new UI.ToolbarButton(Common.UIString('Refresh'), 'largeicon-refresh'); this._refreshButton.addEventListener(UI.ToolbarButton.Events.Click, this._refreshClick, this); this._refreshButton.setEnabled(false); - this._eventListenersView = new EventListeners.EventListenersView(this.element, this.update.bind(this)); + this._eventListenersView = new EventListeners.EventListenersView(this.update.bind(this)); + this._eventListenersView.show(this.element); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/sourcesPanel.css b/third_party/WebKit/Source/devtools/front_end/sources/sourcesPanel.css index 790456602..851ee52 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/sourcesPanel.css +++ b/third_party/WebKit/Source/devtools/front_end/sources/sourcesPanel.css
@@ -67,7 +67,3 @@ .cursor-auto { cursor: auto; } - -.event-listeners-sidebar-pane .toolbar { - border-bottom: 1px solid #eee; -}
diff --git a/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js b/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js index 2d04f08..eb243c3 100644 --- a/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js +++ b/third_party/WebKit/Source/devtools/front_end/text_editor/CodeMirrorTextEditor.js
@@ -904,7 +904,7 @@ if (decoration.element !== element) return; this._codeMirror.removeLineWidget(decoration.widget); - this._decorations.remove(lineNumber, decoration); + this._decorations.delete(lineNumber, decoration); } }
diff --git a/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js b/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js index 4d88c33..fa6690cc 100644 --- a/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js +++ b/third_party/WebKit/Source/devtools/front_end/workspace/UISourceCode.js
@@ -616,7 +616,7 @@ if (!this._decorations) return; var markers = this._decorations.get(type); - this._decorations.removeAll(type); + this._decorations.deleteAll(type); markers.forEach(marker => { this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved, marker); });
diff --git a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp index 83f42f34..229ebf7 100644 --- a/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp +++ b/third_party/WebKit/Source/modules/app_banner/BeforeInstallPromptEvent.cpp
@@ -31,7 +31,7 @@ prompt_called_(false) { DCHECK(banner_service_); DCHECK(binding_.is_bound()); - UseCounter::Count(&frame, UseCounter::kBeforeInstallPromptEvent); + UseCounter::Count(&frame, WebFeature::kBeforeInstallPromptEvent); } BeforeInstallPromptEvent::BeforeInstallPromptEvent( @@ -59,7 +59,7 @@ ScriptPromise BeforeInstallPromptEvent::userChoice(ScriptState* script_state) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kBeforeInstallPromptEventUserChoice); + WebFeature::kBeforeInstallPromptEventUserChoice); // |m_binding| must be bound to allow the AppBannerService to resolve the // userChoice promise. if (user_choice_ && binding_.is_bound()) @@ -82,7 +82,7 @@ } UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kBeforeInstallPromptEventPrompt); + WebFeature::kBeforeInstallPromptEventPrompt); prompt_called_ = true; banner_service_->DisplayAppBanner( @@ -98,7 +98,7 @@ Event::preventDefault(); if (target()) { UseCounter::Count(target()->GetExecutionContext(), - UseCounter::kBeforeInstallPromptEventPreventDefault); + WebFeature::kBeforeInstallPromptEventPreventDefault); } }
diff --git a/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp b/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp index abf1dc0..308cf0a 100644 --- a/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp +++ b/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp
@@ -122,7 +122,7 @@ Blob* blob = data.getAsBlob(); if (!FetchUtils::IsSimpleContentType(AtomicString(blob->type()))) { UseCounter::Count(context, - UseCounter::kSendBeaconWithNonSimpleContentType); + WebFeature::kSendBeaconWithNonSimpleContentType); if (RuntimeEnabledFeatures:: SendBeaconThrowForBlobWithNonSimpleTypeEnabled()) { exception_state.ThrowSecurityError( @@ -146,7 +146,7 @@ } if (!allowed) { - UseCounter::Count(context, UseCounter::kSendBeaconQuotaExceeded); + UseCounter::Count(context, WebFeature::kSendBeaconQuotaExceeded); return false; }
diff --git a/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp b/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp index d59d491..2c0f718 100644 --- a/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp +++ b/third_party/WebKit/Source/modules/bluetooth/BluetoothDevice.cpp
@@ -105,7 +105,7 @@ registered_listener); if (event_type == EventTypeNames::gattserverdisconnected) { UseCounter::Count(GetExecutionContext(), - UseCounter::kGATTServerDisconnectedEvent); + WebFeature::kGATTServerDisconnectedEvent); } }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp index 5572d7f7..04fdaf1 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp
@@ -111,7 +111,7 @@ DCHECK(credential->IsPasswordCredential() || credential->IsFederatedCredential()); UseCounter::Count(ExecutionContext::From(resolver_->GetScriptState()), - UseCounter::kCredentialManagerGetReturnedCredential); + WebFeature::kCredentialManagerGetReturnedCredential); if (credential->IsPasswordCredential()) resolver_->Resolve(PasswordCredential::Create( static_cast<WebPasswordCredential*>(credential.get()))); @@ -183,7 +183,7 @@ mediation = options.unmediated() ? "silent" : "optional"; UseCounter::Count( context, - UseCounter::kCredentialManagerCredentialRequestOptionsOnlyUnmediated); + WebFeature::kCredentialManagerCredentialRequestOptionsOnlyUnmediated); } else if (options.hasMediation()) { mediation = options.mediation(); if (options.hasUnmediated() && @@ -209,16 +209,16 @@ if (mediation == "silent") { UseCounter::Count(context, - UseCounter::kCredentialManagerGetMediationSilent); + WebFeature::kCredentialManagerGetMediationSilent); requirement = WebCredentialMediationRequirement::kSilent; } else if (mediation == "optional") { UseCounter::Count(context, - UseCounter::kCredentialManagerGetMediationOptional); + WebFeature::kCredentialManagerGetMediationOptional); requirement = WebCredentialMediationRequirement::kOptional; } else { DCHECK_EQ("required", mediation); UseCounter::Count(context, - UseCounter::kCredentialManagerGetMediationRequired); + WebFeature::kCredentialManagerGetMediationRequired); requirement = WebCredentialMediationRequirement::kRequired; }
diff --git a/third_party/WebKit/Source/modules/crypto/CryptoHistograms.cpp b/third_party/WebKit/Source/modules/crypto/CryptoHistograms.cpp index a7f40b3..63a56ed0 100644 --- a/third_party/WebKit/Source/modules/crypto/CryptoHistograms.cpp +++ b/third_party/WebKit/Source/modules/crypto/CryptoHistograms.cpp
@@ -12,50 +12,50 @@ namespace blink { -static UseCounter::Feature AlgorithmIdToFeature(WebCryptoAlgorithmId id) { +static WebFeature AlgorithmIdToFeature(WebCryptoAlgorithmId id) { switch (id) { case kWebCryptoAlgorithmIdAesCbc: - return UseCounter::kCryptoAlgorithmAesCbc; + return WebFeature::kCryptoAlgorithmAesCbc; case kWebCryptoAlgorithmIdHmac: - return UseCounter::kCryptoAlgorithmHmac; + return WebFeature::kCryptoAlgorithmHmac; case kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5: - return UseCounter::kCryptoAlgorithmRsaSsaPkcs1v1_5; + return WebFeature::kCryptoAlgorithmRsaSsaPkcs1v1_5; case kWebCryptoAlgorithmIdSha1: - return UseCounter::kCryptoAlgorithmSha1; + return WebFeature::kCryptoAlgorithmSha1; case kWebCryptoAlgorithmIdSha256: - return UseCounter::kCryptoAlgorithmSha256; + return WebFeature::kCryptoAlgorithmSha256; case kWebCryptoAlgorithmIdSha384: - return UseCounter::kCryptoAlgorithmSha384; + return WebFeature::kCryptoAlgorithmSha384; case kWebCryptoAlgorithmIdSha512: - return UseCounter::kCryptoAlgorithmSha512; + return WebFeature::kCryptoAlgorithmSha512; case kWebCryptoAlgorithmIdAesGcm: - return UseCounter::kCryptoAlgorithmAesGcm; + return WebFeature::kCryptoAlgorithmAesGcm; case kWebCryptoAlgorithmIdRsaOaep: - return UseCounter::kCryptoAlgorithmRsaOaep; + return WebFeature::kCryptoAlgorithmRsaOaep; case kWebCryptoAlgorithmIdAesCtr: - return UseCounter::kCryptoAlgorithmAesCtr; + return WebFeature::kCryptoAlgorithmAesCtr; case kWebCryptoAlgorithmIdAesKw: - return UseCounter::kCryptoAlgorithmAesKw; + return WebFeature::kCryptoAlgorithmAesKw; case kWebCryptoAlgorithmIdRsaPss: - return UseCounter::kCryptoAlgorithmRsaPss; + return WebFeature::kCryptoAlgorithmRsaPss; case kWebCryptoAlgorithmIdEcdsa: - return UseCounter::kCryptoAlgorithmEcdsa; + return WebFeature::kCryptoAlgorithmEcdsa; case kWebCryptoAlgorithmIdEcdh: - return UseCounter::kCryptoAlgorithmEcdh; + return WebFeature::kCryptoAlgorithmEcdh; case kWebCryptoAlgorithmIdHkdf: - return UseCounter::kCryptoAlgorithmHkdf; + return WebFeature::kCryptoAlgorithmHkdf; case kWebCryptoAlgorithmIdPbkdf2: - return UseCounter::kCryptoAlgorithmPbkdf2; + return WebFeature::kCryptoAlgorithmPbkdf2; } NOTREACHED(); - return static_cast<UseCounter::Feature>(0); + return static_cast<WebFeature>(0); } static void HistogramAlgorithmId(ExecutionContext* context, WebCryptoAlgorithmId algorithm_id) { - UseCounter::Feature feature = AlgorithmIdToFeature(algorithm_id); - if (feature) + WebFeature feature = AlgorithmIdToFeature(algorithm_id); + if (static_cast<bool>(feature)) UseCounter::Count(context, feature); }
diff --git a/third_party/WebKit/Source/modules/device_orientation/DeviceMotionController.cpp b/third_party/WebKit/Source/modules/device_orientation/DeviceMotionController.cpp index 8372dc87..8543af5 100644 --- a/third_party/WebKit/Source/modules/device_orientation/DeviceMotionController.cpp +++ b/third_party/WebKit/Source/modules/device_orientation/DeviceMotionController.cpp
@@ -46,10 +46,10 @@ if (GetDocument().GetFrame()) { if (GetDocument().IsSecureContext()) { UseCounter::Count(GetDocument().GetFrame(), - UseCounter::kDeviceMotionSecureOrigin); + WebFeature::kDeviceMotionSecureOrigin); } else { Deprecation::CountDeprecation(GetDocument().GetFrame(), - UseCounter::kDeviceMotionInsecureOrigin); + WebFeature::kDeviceMotionInsecureOrigin); HostsUsingFeatures::CountAnyWorld( GetDocument(), HostsUsingFeatures::Feature::kDeviceMotionInsecureHost);
diff --git a/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationAbsoluteController.cpp b/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationAbsoluteController.cpp index 46c7267..0c7e43c 100644 --- a/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationAbsoluteController.cpp +++ b/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationAbsoluteController.cpp
@@ -44,11 +44,11 @@ if (GetDocument().GetFrame()) { if (GetDocument().IsSecureContext()) { UseCounter::Count(GetDocument().GetFrame(), - UseCounter::kDeviceOrientationAbsoluteSecureOrigin); + WebFeature::kDeviceOrientationAbsoluteSecureOrigin); } else { Deprecation::CountDeprecation( GetDocument().GetFrame(), - UseCounter::kDeviceOrientationAbsoluteInsecureOrigin); + WebFeature::kDeviceOrientationAbsoluteInsecureOrigin); // TODO: add rappor logging of insecure origins as in // DeviceOrientationController. if (GetDocument()
diff --git a/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationController.cpp b/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationController.cpp index 10eac3e..3e47f8c 100644 --- a/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationController.cpp +++ b/third_party/WebKit/Source/modules/device_orientation/DeviceOrientationController.cpp
@@ -55,11 +55,11 @@ if (GetDocument().GetFrame()) { if (GetDocument().IsSecureContext()) { UseCounter::Count(GetDocument().GetFrame(), - UseCounter::kDeviceOrientationSecureOrigin); + WebFeature::kDeviceOrientationSecureOrigin); } else { Deprecation::CountDeprecation( GetDocument().GetFrame(), - UseCounter::kDeviceOrientationInsecureOrigin); + WebFeature::kDeviceOrientationInsecureOrigin); HostsUsingFeatures::CountAnyWorld( GetDocument(), HostsUsingFeatures::Feature::kDeviceOrientationInsecureHost);
diff --git a/third_party/WebKit/Source/modules/eventsource/EventSource.cpp b/third_party/WebKit/Source/modules/eventsource/EventSource.cpp index 1aa3044..e1a76073 100644 --- a/third_party/WebKit/Source/modules/eventsource/EventSource.cpp +++ b/third_party/WebKit/Source/modules/eventsource/EventSource.cpp
@@ -82,9 +82,9 @@ const EventSourceInit& event_source_init, ExceptionState& exception_state) { if (context->IsDocument()) - UseCounter::Count(ToDocument(context), UseCounter::kEventSourceDocument); + UseCounter::Count(ToDocument(context), WebFeature::kEventSourceDocument); else - UseCounter::Count(context, UseCounter::kEventSourceWorker); + UseCounter::Count(context, WebFeature::kEventSourceWorker); if (url.IsEmpty()) { exception_state.ThrowDOMException(
diff --git a/third_party/WebKit/Source/modules/fetch/GlobalFetch.cpp b/third_party/WebKit/Source/modules/fetch/GlobalFetch.cpp index 0d3f7f74..644c036 100644 --- a/third_party/WebKit/Source/modules/fetch/GlobalFetch.cpp +++ b/third_party/WebKit/Source/modules/fetch/GlobalFetch.cpp
@@ -97,7 +97,7 @@ const RequestInfo& input, const Dictionary& init, ExceptionState& exception_state) { - UseCounter::Count(window.GetExecutionContext(), UseCounter::kFetch); + UseCounter::Count(window.GetExecutionContext(), WebFeature::kFetch); if (!window.GetFrame()) { exception_state.ThrowTypeError("The global scope is shutting down."); return ScriptPromise(); @@ -111,7 +111,7 @@ const RequestInfo& input, const Dictionary& init, ExceptionState& exception_state) { - UseCounter::Count(worker.GetExecutionContext(), UseCounter::kFetch); + UseCounter::Count(worker.GetExecutionContext(), WebFeature::kFetch); return ScopedFetcher::From(worker)->Fetch(script_state, input, init, exception_state); }
diff --git a/third_party/WebKit/Source/modules/fetch/RequestInit.cpp b/third_party/WebKit/Source/modules/fetch/RequestInit.cpp index bf3c8d0..ea5cd44 100644 --- a/third_party/WebKit/Source/modules/fetch/RequestInit.cpp +++ b/third_party/WebKit/Source/modules/fetch/RequestInit.cpp
@@ -118,7 +118,7 @@ if (is_credential_set) { if (V8PasswordCredential::hasInstance(v8_credential, isolate)) { Deprecation::CountDeprecation(context, - UseCounter::kCredentialManagerCustomFetch); + WebFeature::kCredentialManagerCustomFetch); // TODO(mkwst): According to the spec, we'd serialize this once we touch // the network. We're serializing it here, ahead of time, because lifetime // issues around ResourceRequest make it pretty difficult to pass a
diff --git a/third_party/WebKit/Source/modules/fetch/Response.cpp b/third_party/WebKit/Source/modules/fetch/Response.cpp index 75c1b4d..28755f8c 100644 --- a/third_party/WebKit/Source/modules/fetch/Response.cpp +++ b/third_party/WebKit/Source/modules/fetch/Response.cpp
@@ -180,7 +180,7 @@ } else if (ReadableStreamOperations::IsReadableStream(script_state, body_value)) { UseCounter::Count(execution_context, - UseCounter::kFetchResponseConstructionWithStream); + WebFeature::kFetchResponseConstructionWithStream); body_buffer = new BodyStreamBuffer(script_state, body_value); } else { String string = ToUSVString(isolate, body, exception_state);
diff --git a/third_party/WebKit/Source/modules/filesystem/DOMWindowFileSystem.cpp b/third_party/WebKit/Source/modules/filesystem/DOMWindowFileSystem.cpp index 9fb5afa3..cedc8a71 100644 --- a/third_party/WebKit/Source/modules/filesystem/DOMWindowFileSystem.cpp +++ b/third_party/WebKit/Source/modules/filesystem/DOMWindowFileSystem.cpp
@@ -56,7 +56,7 @@ if (SchemeRegistry::SchemeShouldBypassContentSecurityPolicy( document->GetSecurityOrigin()->Protocol())) - UseCounter::Count(document, UseCounter::kRequestFileSystemNonWebbyOrigin); + UseCounter::Count(document, WebFeature::kRequestFileSystemNonWebbyOrigin); if (!document->GetSecurityOrigin()->CanAccessFileSystem()) { DOMFileSystem::ReportError(document,
diff --git a/third_party/WebKit/Source/modules/filesystem/Entry.cpp b/third_party/WebKit/Source/modules/filesystem/Entry.cpp index 6dd24e5..7cbfffad 100644 --- a/third_party/WebKit/Source/modules/filesystem/Entry.cpp +++ b/third_party/WebKit/Source/modules/filesystem/Entry.cpp
@@ -51,7 +51,7 @@ if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count( ExecutionContext::From(script_state), - UseCounter::kEntry_Filesystem_AttributeGetter_IsolatedFileSystem); + WebFeature::kEntry_Filesystem_AttributeGetter_IsolatedFileSystem); } return filesystem(); } @@ -61,7 +61,7 @@ ErrorCallback* error_callback) { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_GetMetadata_Method_IsolatedFileSystem); + WebFeature::kEntry_GetMetadata_Method_IsolatedFileSystem); } file_system_->GetMetadata(this, success_callback, ScriptErrorCallback::Wrap(error_callback)); @@ -74,7 +74,7 @@ ErrorCallback* error_callback) const { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_MoveTo_Method_IsolatedFileSystem); + WebFeature::kEntry_MoveTo_Method_IsolatedFileSystem); } file_system_->Move(this, parent, name, success_callback, ScriptErrorCallback::Wrap(error_callback)); @@ -87,7 +87,7 @@ ErrorCallback* error_callback) const { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_CopyTo_Method_IsolatedFileSystem); + WebFeature::kEntry_CopyTo_Method_IsolatedFileSystem); } file_system_->Copy(this, parent, name, success_callback, ScriptErrorCallback::Wrap(error_callback)); @@ -98,7 +98,7 @@ ErrorCallback* error_callback) const { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_Remove_Method_IsolatedFileSystem); + WebFeature::kEntry_Remove_Method_IsolatedFileSystem); } file_system_->Remove(this, success_callback, ScriptErrorCallback::Wrap(error_callback)); @@ -109,7 +109,7 @@ ErrorCallback* error_callback) const { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_GetParent_Method_IsolatedFileSystem); + WebFeature::kEntry_GetParent_Method_IsolatedFileSystem); } file_system_->GetParent(this, success_callback, ScriptErrorCallback::Wrap(error_callback)); @@ -118,7 +118,7 @@ String Entry::toURL(ScriptState* script_state) const { if (file_system_->GetType() == kFileSystemTypeIsolated) { UseCounter::Count(ExecutionContext::From(script_state), - UseCounter::kEntry_ToURL_Method_IsolatedFileSystem); + WebFeature::kEntry_ToURL_Method_IsolatedFileSystem); } return static_cast<const EntryBase*>(this)->toURL(); }
diff --git a/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp b/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp index 1a25b452..a49fea9 100644 --- a/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp +++ b/third_party/WebKit/Source/modules/geolocation/Geolocation.cpp
@@ -148,9 +148,9 @@ // developer console. String insecure_origin_msg; if (document->IsSecureContext(insecure_origin_msg)) { - UseCounter::Count(document, UseCounter::kGeolocationSecureOrigin); + UseCounter::Count(document, WebFeature::kGeolocationSecureOrigin); UseCounter::CountCrossOriginIframe( - *document, UseCounter::kGeolocationSecureOriginIframe); + *document, WebFeature::kGeolocationSecureOriginIframe); } else if (GetFrame() ->GetSettings() ->GetAllowGeolocationOnInsecureOrigins()) { @@ -159,17 +159,17 @@ // // See https://crbug.com/603574. Deprecation::CountDeprecation( - document, UseCounter::kGeolocationInsecureOriginDeprecatedNotRemoved); + document, WebFeature::kGeolocationInsecureOriginDeprecatedNotRemoved); Deprecation::CountDeprecationCrossOriginIframe( *document, - UseCounter::kGeolocationInsecureOriginIframeDeprecatedNotRemoved); + WebFeature::kGeolocationInsecureOriginIframeDeprecatedNotRemoved); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature::kGeolocationInsecureHost); } else { Deprecation::CountDeprecation(document, - UseCounter::kGeolocationInsecureOrigin); + WebFeature::kGeolocationInsecureOrigin); Deprecation::CountDeprecationCrossOriginIframe( - *document, UseCounter::kGeolocationInsecureOriginIframe); + *document, WebFeature::kGeolocationInsecureOriginIframe); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature::kGeolocationInsecureHost); }
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp index f893eb19..c9f52b30 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp
@@ -115,7 +115,7 @@ if (media_element.ControlsListInternal()->ShouldHideFullscreen()) { UseCounter::Count(media_element.GetDocument(), - UseCounter::kHTMLMediaElementControlsListNoFullscreen); + WebFeature::kHTMLMediaElementControlsListNoFullscreen); return false; } @@ -137,7 +137,7 @@ if (media_element.ControlsListInternal()->ShouldHideRemotePlayback()) { UseCounter::Count( media_element.GetDocument(), - UseCounter::kHTMLMediaElementControlsListNoRemotePlayback); + WebFeature::kHTMLMediaElementControlsListNoRemotePlayback); return false; }
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlDownloadButtonElement.cpp b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlDownloadButtonElement.cpp index b9759b9..2007c5d 100644 --- a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlDownloadButtonElement.cpp +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlDownloadButtonElement.cpp
@@ -69,7 +69,7 @@ // The attribute disables the download button. if (MediaElement().ControlsListInternal()->ShouldHideDownload()) { UseCounter::Count(MediaElement().GetDocument(), - UseCounter::kHTMLMediaElementControlsListNoDownload); + WebFeature::kHTMLMediaElementControlsListNoDownload); return false; }
diff --git a/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp b/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp index 2e1a75ed..e492df5 100644 --- a/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp +++ b/third_party/WebKit/Source/modules/mediasource/MediaSource.cpp
@@ -545,7 +545,7 @@ Deprecation::CountDeprecation( attached_element_->GetDocument(), - UseCounter::kMediaSourceDurationTruncatingBuffered); + WebFeature::kMediaSourceDurationTruncatingBuffered); // See also deprecated remove(new duration, old duration) behavior below. }
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp index fdb4fad..f3fad64 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp +++ b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp
@@ -412,7 +412,7 @@ } Deprecation::CountDeprecation(source_->MediaElement()->GetDocument(), - UseCounter::kMediaSourceAbortRemove); + WebFeature::kMediaSourceAbortRemove); CancelRemove(); }
diff --git a/third_party/WebKit/Source/modules/mediasource/URLMediaSource.cpp b/third_party/WebKit/Source/modules/mediasource/URLMediaSource.cpp index 556d454..2e28dbf 100644 --- a/third_party/WebKit/Source/modules/mediasource/URLMediaSource.cpp +++ b/third_party/WebKit/Source/modules/mediasource/URLMediaSource.cpp
@@ -47,7 +47,7 @@ DCHECK(execution_context); DCHECK(source); - UseCounter::Count(execution_context, UseCounter::kCreateObjectURLMediaSource); + UseCounter::Count(execution_context, WebFeature::kCreateObjectURLMediaSource); return DOMURL::CreatePublicURL(execution_context, source); }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp index 4ed0261..29cbdf4 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp
@@ -499,7 +499,7 @@ error_state.ThrowTypeError("Malformed constraints object."); return WebMediaConstraints(); } - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsFromDictionary); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsFromDictionary); return CreateFromNamedConstraints(context, mandatory, optional, error_state); } @@ -732,7 +732,7 @@ WebMediaConstraints standard_form = ConvertConstraintsToWeb(constraints_in); if (constraints_in.hasOptional() || constraints_in.hasMandatory()) { if (!standard_form.IsEmpty()) { - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsOldAndNew); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsOldAndNew); error_state.ThrowTypeError( "Malformed constraint: Cannot use both optional/mandatory and " "specific or advanced constraints."); @@ -744,11 +744,11 @@ error_state.ThrowTypeError("Malformed constraints object."); return WebMediaConstraints(); } - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsNameValue); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsNameValue); return CreateFromNamedConstraints(context, mandatory, optional, error_state); } - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsConformant); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsConformant); return standard_form; }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp index b232cf7..d22178f 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp
@@ -319,10 +319,10 @@ EventListener* listener, const AddEventListenerOptionsResolved& options) { if (event_type == EventTypeNames::active) { - UseCounter::Count(GetExecutionContext(), UseCounter::kMediaStreamOnActive); + UseCounter::Count(GetExecutionContext(), WebFeature::kMediaStreamOnActive); } else if (event_type == EventTypeNames::inactive) { UseCounter::Count(GetExecutionContext(), - UseCounter::kMediaStreamOnInactive); + WebFeature::kMediaStreamOnInactive); } return EventTargetWithInlineData::AddEventListenerInternal(event_type,
diff --git a/third_party/WebKit/Source/modules/mediastream/URLMediaStream.cpp b/third_party/WebKit/Source/modules/mediastream/URLMediaStream.cpp index 48a9f927b..e50ebcb9 100644 --- a/third_party/WebKit/Source/modules/mediastream/URLMediaStream.cpp +++ b/third_party/WebKit/Source/modules/mediastream/URLMediaStream.cpp
@@ -47,7 +47,7 @@ DCHECK(execution_context); DCHECK(stream); - UseCounter::Count(execution_context, UseCounter::kCreateObjectURLMediaStream); + UseCounter::Count(execution_context, WebFeature::kCreateObjectURLMediaStream); return DOMURL::CreatePublicURL(execution_context, stream); }
diff --git a/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp b/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp index 503dd846..a69f4f2 100644 --- a/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp +++ b/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp
@@ -106,7 +106,7 @@ public: FeatureCounter(ExecutionContext* context) : context_(context), is_unconstrained_(true) {} - void Count(UseCounter::Feature feature) { + void Count(WebFeature feature) { UseCounter::Count(context_, feature); is_unconstrained_ = false; } @@ -122,110 +122,110 @@ FeatureCounter counter(context); if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::sample_rate)) { - counter.Count(UseCounter::kMediaStreamConstraintsSampleRate); + counter.Count(WebFeature::kMediaStreamConstraintsSampleRate); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::sample_size)) { - counter.Count(UseCounter::kMediaStreamConstraintsSampleSize); + counter.Count(WebFeature::kMediaStreamConstraintsSampleSize); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::echo_cancellation)) { - counter.Count(UseCounter::kMediaStreamConstraintsEchoCancellation); + counter.Count(WebFeature::kMediaStreamConstraintsEchoCancellation); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::latency)) { - counter.Count(UseCounter::kMediaStreamConstraintsLatency); + counter.Count(WebFeature::kMediaStreamConstraintsLatency); } if (RequestUsesNumericConstraint( constraints, &WebMediaTrackConstraintSet::channel_count)) { - counter.Count(UseCounter::kMediaStreamConstraintsChannelCount); + counter.Count(WebFeature::kMediaStreamConstraintsChannelCount); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::device_id)) { - counter.Count(UseCounter::kMediaStreamConstraintsDeviceIdAudio); + counter.Count(WebFeature::kMediaStreamConstraintsDeviceIdAudio); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::disable_local_echo)) { - counter.Count(UseCounter::kMediaStreamConstraintsDisableLocalEcho); + counter.Count(WebFeature::kMediaStreamConstraintsDisableLocalEcho); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::group_id)) { - counter.Count(UseCounter::kMediaStreamConstraintsGroupIdAudio); + counter.Count(WebFeature::kMediaStreamConstraintsGroupIdAudio); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::media_stream_source)) { - counter.Count(UseCounter::kMediaStreamConstraintsMediaStreamSourceAudio); + counter.Count(WebFeature::kMediaStreamConstraintsMediaStreamSourceAudio); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::render_to_associated_sink)) { - counter.Count(UseCounter::kMediaStreamConstraintsRenderToAssociatedSink); + counter.Count(WebFeature::kMediaStreamConstraintsRenderToAssociatedSink); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::hotword_enabled)) { - counter.Count(UseCounter::kMediaStreamConstraintsHotwordEnabled); + counter.Count(WebFeature::kMediaStreamConstraintsHotwordEnabled); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_echo_cancellation)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogEchoCancellation); + counter.Count(WebFeature::kMediaStreamConstraintsGoogEchoCancellation); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_experimental_echo_cancellation)) { counter.Count( - UseCounter::kMediaStreamConstraintsGoogExperimentalEchoCancellation); + WebFeature::kMediaStreamConstraintsGoogExperimentalEchoCancellation); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_auto_gain_control)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogAutoGainControl); + counter.Count(WebFeature::kMediaStreamConstraintsGoogAutoGainControl); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_experimental_auto_gain_control)) { counter.Count( - UseCounter::kMediaStreamConstraintsGoogExperimentalAutoGainControl); + WebFeature::kMediaStreamConstraintsGoogExperimentalAutoGainControl); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_noise_suppression)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogNoiseSuppression); + counter.Count(WebFeature::kMediaStreamConstraintsGoogNoiseSuppression); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_highpass_filter)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogHighpassFilter); + counter.Count(WebFeature::kMediaStreamConstraintsGoogHighpassFilter); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_typing_noise_detection)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogTypingNoiseDetection); + counter.Count(WebFeature::kMediaStreamConstraintsGoogTypingNoiseDetection); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_experimental_noise_suppression)) { counter.Count( - UseCounter::kMediaStreamConstraintsGoogExperimentalNoiseSuppression); + WebFeature::kMediaStreamConstraintsGoogExperimentalNoiseSuppression); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_beamforming)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogBeamforming); + counter.Count(WebFeature::kMediaStreamConstraintsGoogBeamforming); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_array_geometry)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogArrayGeometry); + counter.Count(WebFeature::kMediaStreamConstraintsGoogArrayGeometry); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_audio_mirroring)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogAudioMirroring); + counter.Count(WebFeature::kMediaStreamConstraintsGoogAudioMirroring); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_da_echo_cancellation)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogDAEchoCancellation); + counter.Count(WebFeature::kMediaStreamConstraintsGoogDAEchoCancellation); } - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsAudio); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsAudio); if (counter.IsUnconstrained()) { UseCounter::Count(context, - UseCounter::kMediaStreamConstraintsAudioUnconstrained); + WebFeature::kMediaStreamConstraintsAudioUnconstrained); } } @@ -234,70 +234,70 @@ FeatureCounter counter(context); if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::width)) { - counter.Count(UseCounter::kMediaStreamConstraintsWidth); + counter.Count(WebFeature::kMediaStreamConstraintsWidth); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::height)) { - counter.Count(UseCounter::kMediaStreamConstraintsHeight); + counter.Count(WebFeature::kMediaStreamConstraintsHeight); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::aspect_ratio)) { - counter.Count(UseCounter::kMediaStreamConstraintsAspectRatio); + counter.Count(WebFeature::kMediaStreamConstraintsAspectRatio); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::frame_rate)) { - counter.Count(UseCounter::kMediaStreamConstraintsFrameRate); + counter.Count(WebFeature::kMediaStreamConstraintsFrameRate); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::facing_mode)) { - counter.Count(UseCounter::kMediaStreamConstraintsFacingMode); + counter.Count(WebFeature::kMediaStreamConstraintsFacingMode); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::device_id)) { - counter.Count(UseCounter::kMediaStreamConstraintsDeviceIdVideo); + counter.Count(WebFeature::kMediaStreamConstraintsDeviceIdVideo); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::group_id)) { - counter.Count(UseCounter::kMediaStreamConstraintsGroupIdVideo); + counter.Count(WebFeature::kMediaStreamConstraintsGroupIdVideo); } if (RequestUsesDiscreteConstraint(constraints, &WebMediaTrackConstraintSet::video_kind)) { - counter.Count(UseCounter::kMediaStreamConstraintsVideoKind); + counter.Count(WebFeature::kMediaStreamConstraintsVideoKind); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::depth_near)) { - counter.Count(UseCounter::kMediaStreamConstraintsDepthNear); + counter.Count(WebFeature::kMediaStreamConstraintsDepthNear); } if (RequestUsesNumericConstraint(constraints, &WebMediaTrackConstraintSet::depth_far)) { - counter.Count(UseCounter::kMediaStreamConstraintsDepthFar); + counter.Count(WebFeature::kMediaStreamConstraintsDepthFar); } if (RequestUsesNumericConstraint( constraints, &WebMediaTrackConstraintSet::focal_length_x)) { - counter.Count(UseCounter::kMediaStreamConstraintsFocalLengthX); + counter.Count(WebFeature::kMediaStreamConstraintsFocalLengthX); } if (RequestUsesNumericConstraint( constraints, &WebMediaTrackConstraintSet::focal_length_y)) { - counter.Count(UseCounter::kMediaStreamConstraintsFocalLengthY); + counter.Count(WebFeature::kMediaStreamConstraintsFocalLengthY); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::media_stream_source)) { - counter.Count(UseCounter::kMediaStreamConstraintsMediaStreamSourceVideo); + counter.Count(WebFeature::kMediaStreamConstraintsMediaStreamSourceVideo); } if (RequestUsesDiscreteConstraint( constraints, &WebMediaTrackConstraintSet::goog_noise_reduction)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogNoiseReduction); + counter.Count(WebFeature::kMediaStreamConstraintsGoogNoiseReduction); } if (RequestUsesNumericConstraint( constraints, &WebMediaTrackConstraintSet::goog_power_line_frequency)) { - counter.Count(UseCounter::kMediaStreamConstraintsGoogPowerLineFrequency); + counter.Count(WebFeature::kMediaStreamConstraintsGoogPowerLineFrequency); } - UseCounter::Count(context, UseCounter::kMediaStreamConstraintsVideo); + UseCounter::Count(context, WebFeature::kMediaStreamConstraintsVideo); if (counter.IsUnconstrained()) { UseCounter::Count(context, - UseCounter::kMediaStreamConstraintsVideoUnconstrained); + WebFeature::kMediaStreamConstraintsVideoUnconstrained); } } @@ -399,9 +399,9 @@ if (document->IsSecureContext(error_message)) { UseCounter::Count(document->GetFrame(), - UseCounter::kGetUserMediaSecureOrigin); + WebFeature::kGetUserMediaSecureOrigin); UseCounter::CountCrossOriginIframe( - *document, UseCounter::kGetUserMediaSecureOriginIframe); + *document, WebFeature::kGetUserMediaSecureOriginIframe); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature::kGetUserMediaSecureHost); return true; @@ -410,9 +410,9 @@ // While getUserMedia is blocked on insecure origins, we still want to // count attempts to use it. Deprecation::CountDeprecation(document->GetFrame(), - UseCounter::kGetUserMediaInsecureOrigin); + WebFeature::kGetUserMediaInsecureOrigin); Deprecation::CountDeprecationCrossOriginIframe( - *document, UseCounter::kGetUserMediaInsecureOriginIframe); + *document, WebFeature::kGetUserMediaInsecureOriginIframe); HostsUsingFeatures::CountAnyWorld( *document, HostsUsingFeatures::Feature::kGetUserMediaInsecureHost); return false;
diff --git a/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp b/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp index 384e7fbe..9c184c33 100644 --- a/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp +++ b/third_party/WebKit/Source/modules/navigatorcontentutils/NavigatorContentUtils.cpp
@@ -158,8 +158,8 @@ // Count usage; perhaps we can lock this to secure contexts. UseCounter::Count(*document, document->IsSecureContext() - ? UseCounter::kRegisterProtocolHandlerSecureOrigin - : UseCounter::kRegisterProtocolHandlerInsecureOrigin); + ? WebFeature::kRegisterProtocolHandlerSecureOrigin + : WebFeature::kRegisterProtocolHandlerInsecureOrigin); NavigatorContentUtils::From(navigator)->Client()->RegisterProtocolHandler( scheme, document->CompleteURL(url), title);
diff --git a/third_party/WebKit/Source/modules/notifications/Notification.cpp b/third_party/WebKit/Source/modules/notifications/Notification.cpp index a6bc3b4..85455f68 100644 --- a/third_party/WebKit/Source/modules/notifications/Notification.cpp +++ b/third_party/WebKit/Source/modules/notifications/Notification.cpp
@@ -95,18 +95,18 @@ } if (context->IsSecureContext()) { - UseCounter::Count(context, UseCounter::kNotificationSecureOrigin); + UseCounter::Count(context, WebFeature::kNotificationSecureOrigin); if (context->IsDocument()) { UseCounter::CountCrossOriginIframe( - *ToDocument(context), UseCounter::kNotificationAPISecureOriginIframe); + *ToDocument(context), WebFeature::kNotificationAPISecureOriginIframe); } } else { Deprecation::CountDeprecation(context, - UseCounter::kNotificationInsecureOrigin); + WebFeature::kNotificationInsecureOrigin); if (context->IsDocument()) { Deprecation::CountDeprecationCrossOriginIframe( *ToDocument(context), - UseCounter::kNotificationAPIInsecureOriginIframe); + WebFeature::kNotificationAPIInsecureOriginIframe); } } @@ -367,14 +367,14 @@ ExecutionContext* context = ExecutionContext::From(script_state); if (!context->IsSecureContext()) { Deprecation::CountDeprecation( - context, UseCounter::kNotificationPermissionRequestedInsecureOrigin); + context, WebFeature::kNotificationPermissionRequestedInsecureOrigin); } if (context->IsDocument()) { LocalFrame* frame = ToDocument(context)->GetFrame(); if (frame && !frame->IsMainFrame()) { Deprecation::CountDeprecation( - context, UseCounter::kNotificationPermissionRequestedIframe); + context, WebFeature::kNotificationPermissionRequestedIframe); } }
diff --git a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp index 2d6f0e2..6cfb6ec06 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.cpp
@@ -47,7 +47,7 @@ ScriptPromise OffscreenCanvasRenderingContext2D::commit( ScriptState* script_state, ExceptionState& exception_state) { - UseCounter::Feature feature = UseCounter::kOffscreenCanvasCommit2D; + WebFeature feature = WebFeature::kOffscreenCanvasCommit2D; UseCounter::Count(ExecutionContext::From(script_state), feature); bool is_web_gl_software_rendering = false; SkIRect damage_rect(dirty_rect_for_commit_); @@ -116,8 +116,7 @@ ImageBitmap* OffscreenCanvasRenderingContext2D::TransferToImageBitmap( ScriptState* script_state) { - UseCounter::Feature feature = - UseCounter::kOffscreenCanvasTransferToImageBitmap2D; + WebFeature feature = WebFeature::kOffscreenCanvasTransferToImageBitmap2D; UseCounter::Count(ExecutionContext::From(script_state), feature); RefPtr<StaticBitmapImage> image = TransferToStaticBitmapImage(); if (!image)
diff --git a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp index 6eb14f07..e1fd159 100644 --- a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp +++ b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
@@ -534,7 +534,7 @@ if (supported_methods.Contains(kBasicCardNetworks[i].name)) { Deprecation::CountDeprecation( &execution_context, - UseCounter::kPaymentRequestNetworkNameInSupportedMethods); + WebFeature::kPaymentRequestNetworkNameInSupportedMethods); break; } }
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCIceCandidate.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCIceCandidate.cpp index caa1526..86c6c11 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCIceCandidate.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCIceCandidate.cpp
@@ -62,7 +62,7 @@ sdp_m_line_index = candidate_init.sdpMLineIndex(); } else { UseCounter::Count(context, - UseCounter::kRTCIceCandidateDefaultSdpMLineIndex); + WebFeature::kRTCIceCandidateDefaultSdpMLineIndex); } return new RTCIceCandidate(WebRTCICECandidate(candidate_init.candidate(),
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp index 32f99046..97b35c5 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
@@ -192,7 +192,7 @@ sdp_m_line_index = ice_candidate_init.sdpMLineIndex(); } else { UseCounter::Count(context, - UseCounter::kRTCIceCandidateDefaultSdpMLineIndex); + WebFeature::kRTCIceCandidateDefaultSdpMLineIndex); } return WebRTCICECandidate(ice_candidate_init.candidate(), ice_candidate_init.sdpMid(), sdp_m_line_index); @@ -240,11 +240,11 @@ WebRTCIceTransportPolicy ice_transport_policy = WebRTCIceTransportPolicy::kAll; if (configuration.hasIceTransportPolicy()) { - UseCounter::Count(context, UseCounter::kRTCConfigurationIceTransportPolicy); + UseCounter::Count(context, WebFeature::kRTCConfigurationIceTransportPolicy); ice_transport_policy = IceTransportPolicyFromString(configuration.iceTransportPolicy()); } else if (configuration.hasIceTransports()) { - UseCounter::Count(context, UseCounter::kRTCConfigurationIceTransports); + UseCounter::Count(context, WebFeature::kRTCConfigurationIceTransports); ice_transport_policy = IceTransportPolicyFromString(configuration.iceTransports()); } @@ -263,7 +263,7 @@ String rtcp_mux_policy_string = configuration.rtcpMuxPolicy(); if (rtcp_mux_policy_string == "negotiate") { rtcp_mux_policy = WebRTCRtcpMuxPolicy::kNegotiate; - Deprecation::CountDeprecation(context, UseCounter::kRtcpMuxPolicyNegotiate); + Deprecation::CountDeprecation(context, WebFeature::kRtcpMuxPolicyNegotiate); } else { DCHECK_EQ(rtcp_mux_policy_string, "require"); } @@ -277,7 +277,7 @@ for (const RTCIceServer& ice_server : configuration.iceServers()) { Vector<String> url_strings; if (ice_server.hasURLs()) { - UseCounter::Count(context, UseCounter::kRTCIceServerURLs); + UseCounter::Count(context, WebFeature::kRTCIceServerURLs); const StringOrStringSequence& urls = ice_server.urls(); if (urls.isString()) { url_strings.push_back(urls.getAsString()); @@ -286,7 +286,7 @@ url_strings = urls.getAsStringSequence(); } } else if (ice_server.hasURL()) { - UseCounter::Count(context, UseCounter::kRTCIceServerURL); + UseCounter::Count(context, WebFeature::kRTCIceServerURL); url_strings.push_back(ice_server.url()); } else { exception_state.ThrowTypeError("Malformed RTCIceServer"); @@ -435,10 +435,10 @@ ExceptionState& exception_state) { if (media_constraints.IsObject()) { UseCounter::Count(context, - UseCounter::kRTCPeerConnectionConstructorConstraints); + WebFeature::kRTCPeerConnectionConstructorConstraints); } else { UseCounter::Count(context, - UseCounter::kRTCPeerConnectionConstructorCompliant); + WebFeature::kRTCPeerConnectionConstructorCompliant); } WebRTCConfiguration configuration = @@ -561,7 +561,7 @@ ExecutionContext* context = ExecutionContext::From(script_state); UseCounter::Count( context, - UseCounter::kRTCPeerConnectionCreateOfferOptionsOfferToReceive); + WebFeature::kRTCPeerConnectionCreateOfferOptionsOfferToReceive); } peer_handler_->CreateOffer(request, ConvertToWebRTCOfferOptions(options)); return promise; @@ -577,7 +577,7 @@ DCHECK(error_callback); ExecutionContext* context = ExecutionContext::From(script_state); UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateOfferLegacyFailureCallback); + context, WebFeature::kRTCPeerConnectionCreateOfferLegacyFailureCallback); if (CallErrorCallbackIfSignalingStateClosed(signaling_state_, error_callback)) return ScriptPromise::CastUndefined(script_state); @@ -593,10 +593,10 @@ if (offer_options->OfferToReceiveAudio() != -1 || offer_options->OfferToReceiveVideo() != -1) { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateOfferLegacyOfferOptions); + context, WebFeature::kRTCPeerConnectionCreateOfferLegacyOfferOptions); } else { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateOfferLegacyCompliant); + context, WebFeature::kRTCPeerConnectionCreateOfferLegacyCompliant); } peer_handler_->CreateOffer(request, WebRTCOfferOptions(offer_options)); @@ -616,10 +616,10 @@ if (!constraints.IsEmpty()) { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateOfferLegacyConstraints); + context, WebFeature::kRTCPeerConnectionCreateOfferLegacyConstraints); } else { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateOfferLegacyCompliant); + context, WebFeature::kRTCPeerConnectionCreateOfferLegacyCompliant); } peer_handler_->CreateOffer(request, constraints); @@ -652,13 +652,13 @@ DCHECK(error_callback); ExecutionContext* context = ExecutionContext::From(script_state); UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateAnswerLegacyFailureCallback); + context, WebFeature::kRTCPeerConnectionCreateAnswerLegacyFailureCallback); if (media_constraints.IsObject()) { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateAnswerLegacyConstraints); + context, WebFeature::kRTCPeerConnectionCreateAnswerLegacyConstraints); } else { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateAnswerLegacyCompliant); + context, WebFeature::kRTCPeerConnectionCreateAnswerLegacyCompliant); } if (CallErrorCallbackIfSignalingStateClosed(signaling_state_, error_callback)) @@ -710,17 +710,17 @@ if (success_callback && error_callback) { UseCounter::Count( context, - UseCounter::kRTCPeerConnectionSetLocalDescriptionLegacyCompliant); + WebFeature::kRTCPeerConnectionSetLocalDescriptionLegacyCompliant); } else { if (!success_callback) UseCounter::Count( context, - UseCounter:: + WebFeature:: kRTCPeerConnectionSetLocalDescriptionLegacyNoSuccessCallback); if (!error_callback) UseCounter::Count( context, - UseCounter:: + WebFeature:: kRTCPeerConnectionSetLocalDescriptionLegacyNoFailureCallback); } @@ -770,17 +770,17 @@ if (success_callback && error_callback) { UseCounter::Count( context, - UseCounter::kRTCPeerConnectionSetRemoteDescriptionLegacyCompliant); + WebFeature::kRTCPeerConnectionSetRemoteDescriptionLegacyCompliant); } else { if (!success_callback) UseCounter::Count( context, - UseCounter:: + WebFeature:: kRTCPeerConnectionSetRemoteDescriptionLegacyNoSuccessCallback); if (!error_callback) UseCounter::Count( context, - UseCounter:: + WebFeature:: kRTCPeerConnectionSetRemoteDescriptionLegacyNoFailureCallback); } @@ -1166,7 +1166,7 @@ ScriptPromise promise = resolver->Promise(); UseCounter::Count(context, - UseCounter::kRTCPeerConnectionGetStatsLegacyNonCompliant); + WebFeature::kRTCPeerConnectionGetStatsLegacyNonCompliant); RTCStatsRequest* stats_request = RTCStatsRequestImpl::Create( GetExecutionContext(), this, success_callback, selector); // FIXME: Add passing selector as part of the statsRequest. @@ -1178,7 +1178,7 @@ ScriptPromise RTCPeerConnection::getStats(ScriptState* script_state) { ExecutionContext* context = ExecutionContext::From(script_state); - UseCounter::Count(context, UseCounter::kRTCPeerConnectionGetStats); + UseCounter::Count(context, WebFeature::kRTCPeerConnectionGetStats); ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); @@ -1251,12 +1251,12 @@ if (data_channel_dict.hasMaxRetransmitTime()) { UseCounter::Count( context, - UseCounter::kRTCPeerConnectionCreateDataChannelMaxRetransmitTime); + WebFeature::kRTCPeerConnectionCreateDataChannelMaxRetransmitTime); init.max_retransmit_time = data_channel_dict.maxRetransmitTime(); } if (data_channel_dict.hasMaxRetransmits()) { UseCounter::Count( - context, UseCounter::kRTCPeerConnectionCreateDataChannelMaxRetransmits); + context, WebFeature::kRTCPeerConnectionCreateDataChannelMaxRetransmits); init.max_retransmits = data_channel_dict.maxRetransmits(); } init.protocol = data_channel_dict.protocol();
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCSessionDescription.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCSessionDescription.cpp index 9986c68..b9e3d05f 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCSessionDescription.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCSessionDescription.cpp
@@ -45,13 +45,13 @@ if (description_init_dict.hasType()) type = description_init_dict.type(); else - UseCounter::Count(context, UseCounter::kRTCSessionDescriptionInitNoType); + UseCounter::Count(context, WebFeature::kRTCSessionDescriptionInitNoType); String sdp; if (description_init_dict.hasSdp()) sdp = description_init_dict.sdp(); else - UseCounter::Count(context, UseCounter::kRTCSessionDescriptionInitNoSdp); + UseCounter::Count(context, WebFeature::kRTCSessionDescriptionInitNoSdp); return new RTCSessionDescription(WebRTCSessionDescription(type, sdp)); }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp b/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp index ec418b1c..81e0c28 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationAvailability.cpp
@@ -63,7 +63,7 @@ registered_listener); if (event_type == EventTypeNames::change) { UseCounter::Count(GetExecutionContext(), - UseCounter::kPresentationAvailabilityChangeEventListener); + WebFeature::kPresentationAvailabilityChangeEventListener); } }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp index 66fd5d2..6a8a8aa 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp
@@ -227,17 +227,17 @@ registered_listener); if (event_type == EventTypeNames::connect) { UseCounter::Count(GetExecutionContext(), - UseCounter::kPresentationConnectionConnectEventListener); + WebFeature::kPresentationConnectionConnectEventListener); } else if (event_type == EventTypeNames::close) { UseCounter::Count(GetExecutionContext(), - UseCounter::kPresentationConnectionCloseEventListener); + WebFeature::kPresentationConnectionCloseEventListener); } else if (event_type == EventTypeNames::terminate) { UseCounter::Count( GetExecutionContext(), - UseCounter::kPresentationConnectionTerminateEventListener); + WebFeature::kPresentationConnectionTerminateEventListener); } else if (event_type == EventTypeNames::message) { UseCounter::Count(GetExecutionContext(), - UseCounter::kPresentationConnectionMessageEventListener); + WebFeature::kPresentationConnectionMessageEventListener); } }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnectionList.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnectionList.cpp index ff37b724..99666817 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnectionList.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnectionList.cpp
@@ -32,7 +32,7 @@ if (event_type == EventTypeNames::connectionavailable) { UseCounter::Count( GetExecutionContext(), - UseCounter::kPresentationRequestConnectionAvailableEventListener); + WebFeature::kPresentationRequestConnectionAvailableEventListener); } }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp index 487cffe..766753b 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp
@@ -116,10 +116,10 @@ void PresentationReceiver::RecordOriginTypeAccess(Document* document) const { DCHECK(document); if (document->IsSecureContext()) { - UseCounter::Count(document, UseCounter::kPresentationReceiverSecureOrigin); + UseCounter::Count(document, WebFeature::kPresentationReceiverSecureOrigin); } else { UseCounter::Count(document, - UseCounter::kPresentationReceiverInsecureOrigin); + WebFeature::kPresentationReceiverInsecureOrigin); } }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp b/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp index 06ae6626..aa5cbbd8 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp
@@ -103,7 +103,7 @@ if (event_type == EventTypeNames::connectionavailable) { UseCounter::Count( GetExecutionContext(), - UseCounter::kPresentationRequestConnectionAvailableEventListener); + WebFeature::kPresentationRequestConnectionAvailableEventListener); } } @@ -224,10 +224,10 @@ DCHECK(execution_context); if (execution_context->IsSecureContext()) { UseCounter::Count(execution_context, - UseCounter::kPresentationRequestSecureOrigin); + WebFeature::kPresentationRequestSecureOrigin); } else { UseCounter::Count(execution_context, - UseCounter::kPresentationRequestInsecureOrigin); + WebFeature::kPresentationRequestInsecureOrigin); } }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp index c1565e7..fd07fda 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerContainer.cpp
@@ -438,7 +438,7 @@ WTF::WrapUnique(handle.release())); if (controller_) { UseCounter::Count(GetExecutionContext(), - UseCounter::kServiceWorkerControlledPage); + WebFeature::kServiceWorkerControlledPage); } if (should_notify_controller_change) DispatchEvent(Event::Create(EventTypeNames::controllerchange)); @@ -464,8 +464,7 @@ void ServiceWorkerContainer::CountFeature(uint32_t feature) { if (!GetExecutionContext()) return; - UseCounter::Feature use_counter_feature = - static_cast<UseCounter::Feature>(feature); + WebFeature use_counter_feature = static_cast<WebFeature>(feature); if (Deprecation::DeprecationMessage(use_counter_feature).IsEmpty()) UseCounter::Count(GetExecutionContext(), use_counter_feature); else
diff --git a/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp b/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp index 51bb711..ac81883 100644 --- a/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp +++ b/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp
@@ -107,7 +107,7 @@ } else { // Just shows the deprecation message in M59. level = kWarningMessageLevel; Deprecation::CountDeprecation(frame, - UseCounter::kVibrateWithoutUserGesture); + WebFeature::kVibrateWithoutUserGesture); } if (level == kErrorMessageLevel) { @@ -125,9 +125,9 @@ void NavigatorVibration::CollectHistogramMetrics(const LocalFrame& frame) { NavigatorVibrationType type; bool user_gesture = frame.HasReceivedUserGesture(); - UseCounter::Count(&frame, UseCounter::kNavigatorVibrate); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrate); if (!frame.IsMainFrame()) { - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateSubFrame); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateSubFrame); if (frame.IsCrossOriginSubframe()) { if (user_gesture) type = NavigatorVibrationType::kCrossOriginSubFrameWithUserGesture; @@ -151,22 +151,22 @@ switch (frame.GetDocument()->GetEngagementLevel()) { case mojom::blink::EngagementLevel::NONE: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementNone); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementNone); break; case mojom::blink::EngagementLevel::MINIMAL: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementMinimal); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementMinimal); break; case mojom::blink::EngagementLevel::LOW: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementLow); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementLow); break; case mojom::blink::EngagementLevel::MEDIUM: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementMedium); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementMedium); break; case mojom::blink::EngagementLevel::HIGH: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementHigh); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementHigh); break; case mojom::blink::EngagementLevel::MAX: - UseCounter::Count(&frame, UseCounter::kNavigatorVibrateEngagementMax); + UseCounter::Count(&frame, WebFeature::kNavigatorVibrateEngagementMax); break; } }
diff --git a/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp b/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp index 6de2c23..f6baae6e 100644 --- a/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp +++ b/third_party/WebKit/Source/modules/vr/NavigatorVR.cpp
@@ -73,10 +73,10 @@ return promise; } - UseCounter::Count(*GetDocument(), UseCounter::kVRGetDisplays); + UseCounter::Count(*GetDocument(), WebFeature::kVRGetDisplays); ExecutionContext* execution_context = ExecutionContext::From(script_state); if (!execution_context->IsSecureContext()) - UseCounter::Count(*GetDocument(), UseCounter::kVRGetDisplaysInsecureOrigin); + UseCounter::Count(*GetDocument(), WebFeature::kVRGetDisplaysInsecureOrigin); Platform::Current()->RecordRapporURL("VR.WebVR.GetDisplays", GetDocument()->Url());
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp index 88c0b5c..1a53ff5 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp
@@ -226,10 +226,10 @@ const HeapVector<VRLayer>& layers) { DVLOG(1) << __FUNCTION__; ExecutionContext* execution_context = ExecutionContext::From(script_state); - UseCounter::Count(execution_context, UseCounter::kVRRequestPresent); + UseCounter::Count(execution_context, WebFeature::kVRRequestPresent); if (!execution_context->IsSecureContext()) { UseCounter::Count(execution_context, - UseCounter::kVRRequestPresentInsecureOrigin); + WebFeature::kVRRequestPresentInsecureOrigin); } ReportPresentationResult(PresentationResult::kRequested);
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioContext.cpp b/third_party/WebKit/Source/modules/webaudio/AudioContext.cpp index f0a5e2f0..a30318d0 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioContext.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioContext.cpp
@@ -38,7 +38,7 @@ DCHECK(IsMainThread()); UseCounter::CountCrossOriginIframe( - document, UseCounter::kAudioContextCrossOriginIframe); + document, WebFeature::kAudioContextCrossOriginIframe); if (g_hardware_context_count >= kMaxHardwareContexts) { exception_state.ThrowDOMException(
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp b/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp index b96cc3a..768273d 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp
@@ -61,9 +61,9 @@ if (time >= 0) return true; - exception_state.ThrowDOMException( - kInvalidAccessError, message + " must be a finite non-negative number: " + - String::Number(time)); + exception_state.ThrowRangeError( + message + + " must be a finite non-negative number: " + String::Number(time)); return false; } @@ -73,8 +73,7 @@ if (time > 0) return true; - exception_state.ThrowDOMException( - kInvalidAccessError, + exception_state.ThrowRangeError( message + " must be a finite positive number: " + String::Number(time)); return false; } @@ -444,12 +443,11 @@ return; if (!value) { - exception_state.ThrowDOMException( - kInvalidAccessError, + exception_state.ThrowRangeError( "The float target value provided (" + String::Number(value) + - ") should not be in the range (" + - String::Number(-std::numeric_limits<float>::denorm_min()) + ", " + - String::Number(std::numeric_limits<float>::denorm_min()) + ")."); + ") should not be in the range (" + + String::Number(-std::numeric_limits<float>::denorm_min()) + ", " + + String::Number(std::numeric_limits<float>::denorm_min()) + ")."); return; }
diff --git a/third_party/WebKit/Source/modules/webdatabase/DatabaseAuthorizer.cpp b/third_party/WebKit/Source/modules/webdatabase/DatabaseAuthorizer.cpp index 4ca0605..f9e5d18c 100644 --- a/third_party/WebKit/Source/modules/webdatabase/DatabaseAuthorizer.cpp +++ b/third_party/WebKit/Source/modules/webdatabase/DatabaseAuthorizer.cpp
@@ -253,7 +253,7 @@ return kSQLAuthDeny; UseCounter::Count(database_context_->GetExecutionContext(), - UseCounter::kWebDatabaseCreateDropFTS3Table); + WebFeature::kWebDatabaseCreateDropFTS3Table); last_action_changed_database_ = true; return DenyBasedOnTableName(table_name); } @@ -268,7 +268,7 @@ return kSQLAuthDeny; UseCounter::Count(database_context_->GetExecutionContext(), - UseCounter::kWebDatabaseCreateDropFTS3Table); + WebFeature::kWebDatabaseCreateDropFTS3Table); return UpdateDeletesBasedOnTableName(table_name); }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index 22e819b..3d05dca2 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -703,8 +703,7 @@ ImageBitmap* WebGLRenderingContextBase::TransferToImageBitmapBase( ScriptState* script_state) { - UseCounter::Feature feature = - UseCounter::kOffscreenCanvasTransferToImageBitmapWebGL; + WebFeature feature = WebFeature::kOffscreenCanvasTransferToImageBitmapWebGL; UseCounter::Count(ExecutionContext::From(script_state), feature); if (!GetDrawingBuffer()) return nullptr; @@ -714,7 +713,7 @@ ScriptPromise WebGLRenderingContextBase::commit( ScriptState* script_state, ExceptionState& exception_state) { - UseCounter::Feature feature = UseCounter::kOffscreenCanvasCommitWebGL; + WebFeature feature = WebFeature::kOffscreenCanvasCommitWebGL; UseCounter::Count(ExecutionContext::From(script_state), feature); int width = GetDrawingBuffer()->Size().Width(); int height = GetDrawingBuffer()->Size().Height(); @@ -4826,7 +4825,7 @@ RefPtr<Image> image_for_render = image->CachedImage()->GetImage(); if (image_for_render && image_for_render->IsSVGImage()) { if (canvas()) { - UseCounter::Count(canvas()->GetDocument(), UseCounter::kSVGInWebGL); + UseCounter::Count(canvas()->GetDocument(), WebFeature::kSVGInWebGL); } image_for_render = DrawImageIntoBuffer(std::move(image_for_render), image->width(),
diff --git a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp index e67f2e3..83ccd58 100644 --- a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp +++ b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp
@@ -81,12 +81,12 @@ Document& document = *ToDocument(ExecutionContext::From(script_state)); if (options.hasSysex() && options.sysex()) { - UseCounter::Count(document, UseCounter::kRequestMIDIAccessWithSysExOption); + UseCounter::Count(document, WebFeature::kRequestMIDIAccessWithSysExOption); UseCounter::CountCrossOriginIframe( - document, UseCounter::kRequestMIDIAccessIframeWithSysExOption); + document, WebFeature::kRequestMIDIAccessIframeWithSysExOption); } UseCounter::CountCrossOriginIframe(document, - UseCounter::kRequestMIDIAccessIframe); + WebFeature::kRequestMIDIAccessIframe); return MIDIAccessInitializer::Start(script_state, options); }
diff --git a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp index 192aeb2..aacd15a 100644 --- a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp +++ b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp
@@ -288,7 +288,7 @@ void DOMWebSocket::Connect(const String& url, const Vector<String>& protocols, ExceptionState& exception_state) { - UseCounter::Count(GetExecutionContext(), UseCounter::kWebSocket); + UseCounter::Count(GetExecutionContext(), WebFeature::kWebSocket); NETWORK_DVLOG(1) << "WebSocket " << this << " connect() url=" << url; url_ = KURL(KURL(), url); @@ -297,7 +297,7 @@ kUpgradeInsecureRequests && url_.Protocol() == "ws") { UseCounter::Count(GetExecutionContext(), - UseCounter::kUpgradeInsecureRequestsUpgradedRequest); + WebFeature::kUpgradeInsecureRequestsUpgradedRequest); url_.SetProtocol("wss"); if (url_.Port() == 80) url_.SetPort(443);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp index ac0f7c45..e083dc9 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp
@@ -8,19 +8,21 @@ namespace blink { -PaintChunker::PaintChunker() {} +PaintChunker::PaintChunker() : force_new_chunk_(DontForceNewChunk) {} PaintChunker::~PaintChunker() {} void PaintChunker::UpdateCurrentPaintChunkProperties( const PaintChunk::Id* chunk_id, - const PaintChunkProperties& properties) { + const PaintChunkProperties& properties, + NewChunkForceState force_new_chunk) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); current_chunk_id_ = WTF::nullopt; if (chunk_id) current_chunk_id_.emplace(*chunk_id); current_properties_ = properties; + force_new_chunk_ = force_new_chunk; } bool PaintChunker::IncrementDisplayItemIndex(const DisplayItem& item) { @@ -60,18 +62,22 @@ current_properties_); chunks_.push_back(new_chunk); chunk_behavior_.push_back(behavior); + force_new_chunk_ = DontForceNewChunk; return true; } auto& last_chunk = chunks_.back(); bool can_continue_chunk = current_properties_ == last_chunk.properties && behavior != kRequiresSeparateChunk && - chunk_behavior_.back() != kRequiresSeparateChunk; + chunk_behavior_.back() != kRequiresSeparateChunk && + force_new_chunk_ == DontForceNewChunk; if (can_continue_chunk) { last_chunk.end_index++; return false; } + force_new_chunk_ = DontForceNewChunk; + PaintChunk new_chunk(last_chunk.end_index, last_chunk.end_index + 1, new_chunk_id ? &*new_chunk_id : nullptr, current_properties_);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h index 75093f6..fab3b415 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.h
@@ -15,6 +15,8 @@ namespace blink { +enum NewChunkForceState { DontForceNewChunk, ForceNewChunk }; + // Accepts information about changes to |PaintChunkProperties| as drawings are // accumulated, and produces a series of paint chunks: contiguous ranges of the // display list with identical |PaintChunkProperties|. @@ -33,8 +35,10 @@ const PaintChunkProperties& CurrentPaintChunkProperties() const { return current_properties_; } - void UpdateCurrentPaintChunkProperties(const PaintChunk::Id*, - const PaintChunkProperties&); + void UpdateCurrentPaintChunkProperties( + const PaintChunk::Id*, + const PaintChunkProperties&, + NewChunkForceState force_new_chunk = DontForceNewChunk); // Returns true if a new chunk is created. bool IncrementDisplayItemIndex(const DisplayItem&); @@ -72,6 +76,7 @@ Vector<ItemBehavior> chunk_behavior_; Optional<PaintChunk::Id> current_chunk_id_; PaintChunkProperties current_properties_; + NewChunkForceState force_new_chunk_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp index 4c7a4b6..0cabe7bf 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp
@@ -327,8 +327,10 @@ void PaintController::UpdateCurrentPaintChunkProperties( const PaintChunk::Id* id, - const PaintChunkProperties& new_properties) { - new_paint_chunks_.UpdateCurrentPaintChunkProperties(id, new_properties); + const PaintChunkProperties& new_properties, + NewChunkForceState force_new_chunk) { + new_paint_chunks_.UpdateCurrentPaintChunkProperties(id, new_properties, + force_new_chunk); } const PaintChunkProperties& PaintController::CurrentPaintChunkProperties() @@ -493,9 +495,10 @@ cached_chunk = current_paint_artifact_.FindChunkByDisplayItemIndex(begin_index); DCHECK(cached_chunk != current_paint_artifact_.PaintChunks().end()); + UpdateCurrentPaintChunkProperties( cached_chunk->id ? &*cached_chunk->id : nullptr, - cached_chunk->properties); + cached_chunk->properties, ForceNewChunk); } else { // Avoid uninitialized variable error on Windows. cached_chunk = current_paint_artifact_.PaintChunks().begin(); @@ -519,7 +522,7 @@ DCHECK(cached_chunk != current_paint_artifact_.PaintChunks().end()); UpdateCurrentPaintChunkProperties( cached_chunk->id ? &*cached_chunk->id : nullptr, - cached_chunk->properties); + cached_chunk->properties, ForceNewChunk); } #if DCHECK_IS_ON()
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.h b/third_party/WebKit/Source/platform/graphics/paint/PaintController.h index 842acb6d..1a644ad 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.h
@@ -72,12 +72,14 @@ void InvalidateAll(); - // These methods are called during painting. + // These methods are called during painting.u // Provide a new set of paint chunk properties to apply to recorded display // items, for Slimming Paint v2. - void UpdateCurrentPaintChunkProperties(const PaintChunk::Id*, - const PaintChunkProperties&); + void UpdateCurrentPaintChunkProperties( + const PaintChunk::Id*, + const PaintChunkProperties&, + NewChunkForceState force_new_chunk = DontForceNewChunk); // Retrieve the current paint properties. const PaintChunkProperties& CurrentPaintChunkProperties() const;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp index 04e74ca..c06c0cc 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
@@ -1078,6 +1078,58 @@ } } +TEST_P(PaintControllerTest, CachedSubsequenceForcePaintChunk) { + if (!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) + return; + + GraphicsContext context(GetPaintController()); + + FakeDisplayItemClient root("root"); + auto root_properties = DefaultPaintChunkProperties(); + PaintChunk::Id root_id(root, DisplayItem::kCaret); + // Record a first chunk with backface_hidden == false + GetPaintController().UpdateCurrentPaintChunkProperties(&root_id, + root_properties); + DrawRect(context, root, kBackgroundDrawingType, + FloatRect(100, 100, 100, 100)); + + FakeDisplayItemClient container("container"); + { + // Record a second chunk with backface_hidden == true + auto container_properties = DefaultPaintChunkProperties(); + container_properties.backface_hidden = true; + PaintChunk::Id container_id(container, DisplayItem::kCaret); + + SubsequenceRecorder r(context, container); + GetPaintController().UpdateCurrentPaintChunkProperties( + &container_id, container_properties); + DrawRect(context, container, kBackgroundDrawingType, + FloatRect(100, 100, 100, 100)); + DrawRect(context, container, kForegroundDrawingType, + FloatRect(100, 100, 100, 100)); + } + GetPaintController().CommitNewDisplayItems(); + + root_properties.backface_hidden = true; + // This time, record the fist chunk with backface_hidden == true + GetPaintController().UpdateCurrentPaintChunkProperties(&root_id, + root_properties); + DrawRect(context, root, kBackgroundDrawingType, + FloatRect(100, 100, 100, 100)); + EXPECT_TRUE(GetPaintController().UseCachedSubsequenceIfPossible(container)); + GetPaintController().CommitNewDisplayItems(); + + // Even though the paint properties match, |container| should receive its + // own PaintChunk because it is a cached subsequence. + EXPECT_EQ(2u, GetPaintController().GetPaintArtifact().PaintChunks().size()); + EXPECT_EQ( + root, + GetPaintController().GetPaintArtifact().PaintChunks()[0].id->client); + EXPECT_EQ( + container, + GetPaintController().GetPaintArtifact().PaintChunks()[1].id->client); +} + TEST_P(PaintControllerTest, CachedSubsequenceSwapOrder) { FakeDisplayItemClient container1("container1", LayoutRect(100, 100, 100, 100));
diff --git a/third_party/WebKit/Source/platform/graphics/paint/ScopedPaintChunkProperties.h b/third_party/WebKit/Source/platform/graphics/paint/ScopedPaintChunkProperties.h index 0995faf1c..ec0884c 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/ScopedPaintChunkProperties.h +++ b/third_party/WebKit/Source/platform/graphics/paint/ScopedPaintChunkProperties.h
@@ -19,25 +19,31 @@ WTF_MAKE_NONCOPYABLE(ScopedPaintChunkProperties); public: - ScopedPaintChunkProperties(PaintController& paint_controller, - const DisplayItemClient& client, - DisplayItem::Type type, - const PaintChunkProperties& properties) + ScopedPaintChunkProperties( + PaintController& paint_controller, + const DisplayItemClient& client, + DisplayItem::Type type, + const PaintChunkProperties& properties, + NewChunkForceState force_new_chunk = DontForceNewChunk) : paint_controller_(paint_controller), previous_properties_(paint_controller.CurrentPaintChunkProperties()) { PaintChunk::Id id(client, type); - paint_controller_.UpdateCurrentPaintChunkProperties(&id, properties); + paint_controller_.UpdateCurrentPaintChunkProperties(&id, properties, + force_new_chunk); } // Omits the type parameter, in case that the client creates only one // PaintChunkProperties node during each painting. - ScopedPaintChunkProperties(PaintController& paint_controller, - const DisplayItemClient& client, - const PaintChunkProperties& properties) + ScopedPaintChunkProperties( + PaintController& paint_controller, + const DisplayItemClient& client, + const PaintChunkProperties& properties, + NewChunkForceState force_new_chunk = DontForceNewChunk) : ScopedPaintChunkProperties(paint_controller, client, DisplayItem::kUninitializedType, - properties) {} + properties, + force_new_chunk) {} ~ScopedPaintChunkProperties() { // We should not return to the previous id, because that may cause a new
diff --git a/third_party/WebKit/Source/web/WebRemoteFrameImpl.cpp b/third_party/WebKit/Source/web/WebRemoteFrameImpl.cpp index 81e3d64..c2c3be357 100644 --- a/third_party/WebKit/Source/web/WebRemoteFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebRemoteFrameImpl.cpp
@@ -87,11 +87,6 @@ NOTREACHED(); } -WebVector<WebIconURL> WebRemoteFrameImpl::IconURLs(int icon_types_mask) const { - NOTREACHED(); - return WebVector<WebIconURL>(); -} - WebSize WebRemoteFrameImpl::GetScrollOffset() const { NOTREACHED(); return WebSize();
diff --git a/third_party/WebKit/Source/web/WebRemoteFrameImpl.h b/third_party/WebKit/Source/web/WebRemoteFrameImpl.h index 7836d34..e11c0ce 100644 --- a/third_party/WebKit/Source/web/WebRemoteFrameImpl.h +++ b/third_party/WebKit/Source/web/WebRemoteFrameImpl.h
@@ -34,7 +34,6 @@ void Close() override; WebString AssignedName() const override; void SetName(const WebString&) override; - WebVector<WebIconURL> IconURLs(int icon_types_mask) const override; WebSize GetScrollOffset() const override; void SetScrollOffset(const WebSize&) override; WebSize ContentsSize() const override;
diff --git a/third_party/WebKit/public/platform/UseCounterFeature.def b/third_party/WebKit/public/platform/UseCounterFeature.def index f7a68db..ba1c7f6 100644 --- a/third_party/WebKit/public/platform/UseCounterFeature.def +++ b/third_party/WebKit/public/platform/UseCounterFeature.def
@@ -1,8 +1,6 @@ // ============ Definition for WebFeature used for UseCounter =============== // A WebFeature conceptually represents some particular web-exposed API // or code path which can be used/triggered by a web page. -// TODO(lunalu): Replace occurance of UseCounter::Feature by WebFeature in -// Blink. // TODO(rbyers): Add CSS and animated CSS feature types by making this a // more sophisticated class. //
diff --git a/third_party/WebKit/public/platform/WebFeature.h b/third_party/WebKit/public/platform/WebFeature.h index 0acc877..348447f 100644 --- a/third_party/WebKit/public/platform/WebFeature.h +++ b/third_party/WebKit/public/platform/WebFeature.h
@@ -5,8 +5,6 @@ // A WebFeature conceptually represents some particular web-exposed API // or code path which can be used/triggered by a web page. -// TODO(lunalu): Replace occurance of UseCounter::Feature by WebFeature in -// Blink. // TODO(rbyers): Add CSS and animated CSS feature types by making this a // more sophisticated class. enum class WebFeature : uint32_t {
diff --git a/third_party/WebKit/public/web/WebFrame.h b/third_party/WebKit/public/web/WebFrame.h index dcf4dd1..85e63de 100644 --- a/third_party/WebKit/public/web/WebFrame.h +++ b/third_party/WebKit/public/web/WebFrame.h
@@ -126,12 +126,6 @@ // frame name unique within the hierarchy. virtual void SetName(const WebString&) = 0; - // The urls of the given combination types of favicon (if any) specified by - // the document loaded in this frame. The iconTypesMask is a bit-mask of - // WebIconURL::Type values, used to select from the available set of icon - // URLs - virtual WebVector<WebIconURL> IconURLs(int icon_types_mask) const = 0; - // The security origin of this frame. BLINK_EXPORT WebSecurityOrigin GetSecurityOrigin() const;
diff --git a/third_party/WebKit/public/web/WebLocalFrame.h b/third_party/WebKit/public/web/WebLocalFrame.h index 7581208..15a4e3a 100644 --- a/third_party/WebKit/public/web/WebLocalFrame.h +++ b/third_party/WebKit/public/web/WebLocalFrame.h
@@ -116,6 +116,14 @@ virtual void SetSharedWorkerRepositoryClient( WebSharedWorkerRepositoryClient*) = 0; + // Basic properties --------------------------------------------------- + + // The urls of the given combination types of favicon (if any) specified by + // the document loaded in this frame. The iconTypesMask is a bit-mask of + // WebIconURL::Type values, used to select from the available set of icon + // URLs + virtual WebVector<WebIconURL> IconURLs(int icon_types_mask) const = 0; + // Hierarchy ---------------------------------------------------------- // Get the highest-level LocalFrame in this frame's in-process subtree. @@ -228,7 +236,7 @@ // one of its descendants having processed a user gesture. virtual void SetHasReceivedUserGesture() = 0; - // Reports a list of unique blink::UseCounter::Feature values representing + // Reports a list of unique blink::WebFeature values representing // Blink features used, performed or encountered by the browser during the // current page load happening on the frame. virtual void BlinkFeatureUsageReport(const std::set<int>& features) = 0;
diff --git a/third_party/libvpx/README.chromium b/third_party/libvpx/README.chromium index 50fa43b..4dcaf0d 100644 --- a/third_party/libvpx/README.chromium +++ b/third_party/libvpx/README.chromium
@@ -5,9 +5,9 @@ License File: source/libvpx/LICENSE Security Critical: yes -Date: Tuesday May 30 2017 +Date: Tuesday June 06 2017 Branch: master -Commit: b9649d240768cdcfc233960056aafb9ed1a3db14 +Commit: ff42e04f9cb60e63ca3fe12ac497f27c68555e1f Description: Contains the sources used to compile libvpx binaries used by Google Chrome and
diff --git a/third_party/libvpx/libvpx_srcs.gni b/third_party/libvpx/libvpx_srcs.gni index e0cbe6b4..66eb5267 100644 --- a/third_party/libvpx/libvpx_srcs.gni +++ b/third_party/libvpx/libvpx_srcs.gni
@@ -1559,6 +1559,7 @@ "//third_party/libvpx/source/libvpx/vpx/vpx_integer.h", "//third_party/libvpx/source/libvpx/vpx_dsp/add_noise.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_neon.c", + "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_pred_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/deblock_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fdct_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fwd_txfm_neon.c", @@ -2036,6 +2037,7 @@ "//third_party/libvpx/source/libvpx/vp9/encoder/arm/neon/vp9_error_neon.c", "//third_party/libvpx/source/libvpx/vp9/encoder/arm/neon/vp9_quantize_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_neon.c", + "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_pred_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/deblock_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fdct_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fwd_txfm_neon.c", @@ -2361,6 +2363,7 @@ "//third_party/libvpx/source/libvpx/vpx/vpx_integer.h", "//third_party/libvpx/source/libvpx/vpx_dsp/add_noise.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_neon.c", + "//third_party/libvpx/source/libvpx/vpx_dsp/arm/avg_pred_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/deblock_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fdct_neon.c", "//third_party/libvpx/source/libvpx/vpx_dsp/arm/fwd_txfm_neon.c",
diff --git a/third_party/libvpx/source/config/ios/arm-neon/vpx_dsp_rtcd.h b/third_party/libvpx/source/config/ios/arm-neon/vpx_dsp_rtcd.h index 4b3c5be..2a63d18 100644 --- a/third_party/libvpx/source/config/ios/arm-neon/vpx_dsp_rtcd.h +++ b/third_party/libvpx/source/config/ios/arm-neon/vpx_dsp_rtcd.h
@@ -28,7 +28,8 @@ #define vpx_avg_8x8 vpx_avg_8x8_neon void vpx_comp_avg_pred_c(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); -#define vpx_comp_avg_pred vpx_comp_avg_pred_c +void vpx_comp_avg_pred_neon(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); +#define vpx_comp_avg_pred vpx_comp_avg_pred_neon void vpx_convolve8_c(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); void vpx_convolve8_neon(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h);
diff --git a/third_party/libvpx/source/config/ios/arm64/vpx_dsp_rtcd.h b/third_party/libvpx/source/config/ios/arm64/vpx_dsp_rtcd.h index 4b3c5be..2a63d18 100644 --- a/third_party/libvpx/source/config/ios/arm64/vpx_dsp_rtcd.h +++ b/third_party/libvpx/source/config/ios/arm64/vpx_dsp_rtcd.h
@@ -28,7 +28,8 @@ #define vpx_avg_8x8 vpx_avg_8x8_neon void vpx_comp_avg_pred_c(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); -#define vpx_comp_avg_pred vpx_comp_avg_pred_c +void vpx_comp_avg_pred_neon(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); +#define vpx_comp_avg_pred vpx_comp_avg_pred_neon void vpx_convolve8_c(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); void vpx_convolve8_neon(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h);
diff --git a/third_party/libvpx/source/config/linux/arm-neon-cpu-detect/vpx_dsp_rtcd.h b/third_party/libvpx/source/config/linux/arm-neon-cpu-detect/vpx_dsp_rtcd.h index cfcf57d..7727e12 100644 --- a/third_party/libvpx/source/config/linux/arm-neon-cpu-detect/vpx_dsp_rtcd.h +++ b/third_party/libvpx/source/config/linux/arm-neon-cpu-detect/vpx_dsp_rtcd.h
@@ -28,7 +28,8 @@ RTCD_EXTERN unsigned int (*vpx_avg_8x8)(const uint8_t *, int p); void vpx_comp_avg_pred_c(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); -#define vpx_comp_avg_pred vpx_comp_avg_pred_c +void vpx_comp_avg_pred_neon(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); +RTCD_EXTERN void (*vpx_comp_avg_pred)(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); void vpx_convolve8_c(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); void vpx_convolve8_neon(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); @@ -851,6 +852,8 @@ if (flags & HAS_NEON) vpx_avg_4x4 = vpx_avg_4x4_neon; vpx_avg_8x8 = vpx_avg_8x8_c; if (flags & HAS_NEON) vpx_avg_8x8 = vpx_avg_8x8_neon; + vpx_comp_avg_pred = vpx_comp_avg_pred_c; + if (flags & HAS_NEON) vpx_comp_avg_pred = vpx_comp_avg_pred_neon; vpx_convolve8 = vpx_convolve8_c; if (flags & HAS_NEON) vpx_convolve8 = vpx_convolve8_neon; vpx_convolve8_avg = vpx_convolve8_avg_c;
diff --git a/third_party/libvpx/source/config/linux/arm-neon/vpx_dsp_rtcd.h b/third_party/libvpx/source/config/linux/arm-neon/vpx_dsp_rtcd.h index 4b3c5be..2a63d18 100644 --- a/third_party/libvpx/source/config/linux/arm-neon/vpx_dsp_rtcd.h +++ b/third_party/libvpx/source/config/linux/arm-neon/vpx_dsp_rtcd.h
@@ -28,7 +28,8 @@ #define vpx_avg_8x8 vpx_avg_8x8_neon void vpx_comp_avg_pred_c(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); -#define vpx_comp_avg_pred vpx_comp_avg_pred_c +void vpx_comp_avg_pred_neon(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); +#define vpx_comp_avg_pred vpx_comp_avg_pred_neon void vpx_convolve8_c(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); void vpx_convolve8_neon(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h);
diff --git a/third_party/libvpx/source/config/linux/arm64/vpx_dsp_rtcd.h b/third_party/libvpx/source/config/linux/arm64/vpx_dsp_rtcd.h index 4b3c5be..2a63d18 100644 --- a/third_party/libvpx/source/config/linux/arm64/vpx_dsp_rtcd.h +++ b/third_party/libvpx/source/config/linux/arm64/vpx_dsp_rtcd.h
@@ -28,7 +28,8 @@ #define vpx_avg_8x8 vpx_avg_8x8_neon void vpx_comp_avg_pred_c(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); -#define vpx_comp_avg_pred vpx_comp_avg_pred_c +void vpx_comp_avg_pred_neon(uint8_t *comp_pred, const uint8_t *pred, int width, int height, const uint8_t *ref, int ref_stride); +#define vpx_comp_avg_pred vpx_comp_avg_pred_neon void vpx_convolve8_c(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); void vpx_convolve8_neon(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h);
diff --git a/third_party/libvpx/source/config/vpx_version.h b/third_party/libvpx/source/config/vpx_version.h index 1204fe1..d93f041 100644 --- a/third_party/libvpx/source/config/vpx_version.h +++ b/third_party/libvpx/source/config/vpx_version.h
@@ -1,7 +1,7 @@ #define VERSION_MAJOR 1 #define VERSION_MINOR 6 #define VERSION_PATCH 1 -#define VERSION_EXTRA "691-gb9649d240" +#define VERSION_EXTRA "716-gff42e04f9" #define VERSION_PACKED ((VERSION_MAJOR<<16)|(VERSION_MINOR<<8)|(VERSION_PATCH)) -#define VERSION_STRING_NOSP "v1.6.1-691-gb9649d240" -#define VERSION_STRING " v1.6.1-691-gb9649d240" +#define VERSION_STRING_NOSP "v1.6.1-716-gff42e04f9" +#define VERSION_STRING " v1.6.1-716-gff42e04f9"
diff --git a/third_party/polymer/v1_0/reproduce.sh b/third_party/polymer/v1_0/reproduce.sh index 247d1e87..821a645 100755 --- a/third_party/polymer/v1_0/reproduce.sh +++ b/third_party/polymer/v1_0/reproduce.sh
@@ -21,8 +21,6 @@ check_dep "which npm" "npm" "visiting https://nodejs.org/en/" check_dep "which bower" "bower" "npm install -g bower" check_dep "which crisper" "crisper" "npm install -g crisper" -check_dep "which polymer-css-build" "polymer-css-build" \ - "npm install -g polymer-css-build" check_dep "which rsync" "rsync" "apt-get install rsync" check_dep "python -c 'import bs4'" "bs4" "apt-get install python-bs4" check_dep "sed --version | grep GNU" \
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 8bc9e03..cbf76fc1 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -305,12 +305,12 @@ <metric name="AudioVideo.Background.Battery"/> <metric name="AudioVideo.Background.EME"/> <metric name="AudioVideo.Background.MSE"/> - <metric name="AudioVideo.Background.NativeControlsOff"/> - <metric name="AudioVideo.Background.NativeControlsOn"/> <metric name="AudioVideo.Background.SRC"/> <metric name="AudioVideo.Battery"/> <metric name="AudioVideo.EME"/> <metric name="AudioVideo.MSE"/> + <metric name="AudioVideo.NativeControlsOff"/> + <metric name="AudioVideo.NativeControlsOn"/> <metric name="AudioVideo.SRC"/> </event>
diff --git a/tools/perf/benchmarks/blink_perf.py b/tools/perf/benchmarks/blink_perf.py index 9c2332d3..ec8f7c42 100644 --- a/tools/perf/benchmarks/blink_perf.py +++ b/tools/perf/benchmarks/blink_perf.py
@@ -67,11 +67,17 @@ else: _AddPage(path) ps = story.StorySet(base_dir=os.getcwd() + os.sep, - serving_dirs=serving_dirs) + serving_dirs=serving_dirs, + verify_names=True) + + all_urls = [p.rstrip('/') for p in page_urls] + common_prefix = os.path.dirname(os.path.commonprefix(all_urls)) for url in page_urls: + name = url[len(common_prefix):].strip('/') ps.AddStory(page_module.Page( url, ps, ps.base_dir, - shared_page_state_class=shared_page_state_class)) + shared_page_state_class=shared_page_state_class, + name=name)) return ps
diff --git a/tools/perf/benchmarks/tab_switching.py b/tools/perf/benchmarks/tab_switching.py index b1cf856..975a24f 100644 --- a/tools/perf/benchmarks/tab_switching.py +++ b/tools/perf/benchmarks/tab_switching.py
@@ -36,7 +36,8 @@ story_set = story.StorySet( archive_data_file='../page_sets/data/system_health_desktop.json', base_dir=os.path.dirname(os.path.abspath(__file__)), - cloud_storage_bucket=story.PARTNER_BUCKET) + cloud_storage_bucket=story.PARTNER_BUCKET, + verify_names=True) story_set.AddStory(multi_tab_stories.MultiTabTypical24Story( story_set, False, options.tabset_repeat)) return story_set
diff --git a/tools/perf/page_sets/key_hit_test_cases.py b/tools/perf/page_sets/key_hit_test_cases.py index d9dd86c..eedf710 100644 --- a/tools/perf/page_sets/key_hit_test_cases.py +++ b/tools/perf/page_sets/key_hit_test_cases.py
@@ -40,6 +40,6 @@ class KeyHitTestCasesPageSet(story.StorySet): def __init__(self): - super(KeyHitTestCasesPageSet, self).__init__() + super(KeyHitTestCasesPageSet, self).__init__(verify_names=True) self.AddStory(PaperCalculatorHitTest(self))
diff --git a/tools/perf/page_sets/key_idle_power_cases.py b/tools/perf/page_sets/key_idle_power_cases.py index 4e5ca5ee..43ca9fc 100644 --- a/tools/perf/page_sets/key_idle_power_cases.py +++ b/tools/perf/page_sets/key_idle_power_cases.py
@@ -16,7 +16,8 @@ url=url, page_set=page_set, shared_page_state_class=(android_screen_restoration_shared_state - .AndroidScreenRestorationSharedState)) + .AndroidScreenRestorationSharedState), + name=url.split('/')[-1]) self._turn_screen_off = turn_screen_off self._duration_seconds = duration_seconds @@ -57,7 +58,7 @@ """ Key idle power cases """ def __init__(self): - super(KeyIdlePowerCasesPageSet, self).__init__() + super(KeyIdlePowerCasesPageSet, self).__init__(verify_names=True) foreground_urls_list = [ # Why: Ensure minimal activity for static, empty pages in the foreground.
diff --git a/tools/perf/page_sets/key_noop_cases.py b/tools/perf/page_sets/key_noop_cases.py index 7175eca..a4639e4 100644 --- a/tools/perf/page_sets/key_noop_cases.py +++ b/tools/perf/page_sets/key_noop_cases.py
@@ -12,7 +12,8 @@ super(NoOpPage, self).__init__( url=url, page_set=page_set, - shared_page_state_class=shared_page_state.SharedMobilePageState) + shared_page_state_class=shared_page_state.SharedMobilePageState, + name=url.split('/')[-1]) def RunNavigateSteps(self, action_runner): super(NoOpPage, self).RunNavigateSteps(action_runner) @@ -41,7 +42,7 @@ """ Key no-op cases """ def __init__(self): - super(KeyNoOpCasesPageSet, self).__init__() + super(KeyNoOpCasesPageSet, self).__init__(verify_names=True) # Why: An infinite rAF loop which does not modify the page should incur # minimal activity.
diff --git a/tools/perf/page_sets/simple_mobile_sites.py b/tools/perf/page_sets/simple_mobile_sites.py index 7957288..f3cb9a6 100644 --- a/tools/perf/page_sets/simple_mobile_sites.py +++ b/tools/perf/page_sets/simple_mobile_sites.py
@@ -13,7 +13,8 @@ url=url, page_set=page_set, shared_page_state_class=shared_page_state.Shared10InchTabletPageState, - credentials_path='data/credentials.json') + credentials_path='data/credentials.json', + name=url) def RunNavigateSteps(self, action_runner): super(SimplePage, self).RunNavigateSteps(action_runner) @@ -37,7 +38,8 @@ def __init__(self): super(SimpleMobileSitesPageSet, self).__init__( archive_data_file='data/simple_mobile_sites.json', - cloud_storage_bucket=story.PUBLIC_BUCKET) + cloud_storage_bucket=story.PUBLIC_BUCKET, + verify_names=True) scroll_page_list = [ # Why: Scrolls moderately complex pages (up to 60 layers)
diff --git a/tools/perf/page_sets/top_10.py b/tools/perf/page_sets/top_10.py index 7c9045f..d5004a9 100644 --- a/tools/perf/page_sets/top_10.py +++ b/tools/perf/page_sets/top_10.py
@@ -8,6 +8,8 @@ class SimplePage(page_module.Page): def __init__(self, url, page_set, credentials='', name=''): + if name == '': + name = url super(SimplePage, self).__init__( url, page_set=page_set, name=name, credentials_path='data/credentials.json', @@ -92,7 +94,8 @@ def __init__(self): super(Top10PageSet, self).__init__( archive_data_file='data/top_10.json', - cloud_storage_bucket=story.PARTNER_BUCKET) + cloud_storage_bucket=story.PARTNER_BUCKET, + verify_names=True) # top google property; a google tab is often open self.AddStory(Google(self))
diff --git a/tools/perf/page_sets/tough_compositor_cases.py b/tools/perf/page_sets/tough_compositor_cases.py index bdaaf756..82ee6f2f 100644 --- a/tools/perf/page_sets/tough_compositor_cases.py +++ b/tools/perf/page_sets/tough_compositor_cases.py
@@ -11,7 +11,8 @@ def __init__(self, url, page_set): super(ToughCompositorPage, self).__init__( url=url, page_set=page_set, credentials_path = 'data/credentials.json', - shared_page_state_class=shared_page_state.SharedMobilePageState) + shared_page_state_class=shared_page_state.SharedMobilePageState, + name=url) self.archive_data_file = 'data/tough_compositor_cases.json' def RunNavigateSteps(self, action_runner): @@ -47,7 +48,8 @@ def __init__(self): super(ToughCompositorCasesPageSet, self).__init__( archive_data_file='data/tough_compositor_cases.json', - cloud_storage_bucket=story.PUBLIC_BUCKET) + cloud_storage_bucket=story.PUBLIC_BUCKET, + verify_names=True) scroll_urls_list = [ # Why: Baseline CC scrolling page. A long page with only text. """
diff --git a/tools/perf/page_sets/tough_scrolling_cases.py b/tools/perf/page_sets/tough_scrolling_cases.py index 0f5e91d..dce65ce9 100644 --- a/tools/perf/page_sets/tough_scrolling_cases.py +++ b/tools/perf/page_sets/tough_scrolling_cases.py
@@ -31,7 +31,7 @@ """ def __init__(self): - super(ToughScrollingCasesPageSet, self).__init__() + super(ToughScrollingCasesPageSet, self).__init__(verify_names=True) fast_scrolling_page_name_list = [ 'text',
diff --git a/ui/app_list/search/mixer.cc b/ui/app_list/search/mixer.cc index 537c834..fac92b3 100644 --- a/ui/app_list/search/mixer.cc +++ b/ui/app_list/search/mixer.cc
@@ -200,7 +200,8 @@ for (const SortData& sort_data : new_results) { const SearchResult& new_result = *sort_data.result; auto ui_result_it = ui_results_map.find(new_result.id()); - if (ui_result_it != ui_results_map.end()) { + if (ui_result_it != ui_results_map.end() && + new_result.view() == ui_result_it->second->view()) { // Update and use the old result if it exists. std::unique_ptr<SearchResult> ui_result = std::move(ui_result_it->second); UpdateResult(new_result, ui_result.get());
diff --git a/ui/app_list/views/search_result_answer_card_view.cc b/ui/app_list/views/search_result_answer_card_view.cc index fe597df..ee32bc1 100644 --- a/ui/app_list/views/search_result_answer_card_view.cc +++ b/ui/app_list/views/search_result_answer_card_view.cc
@@ -54,8 +54,10 @@ if (search_result_) search_result_->RemoveObserver(this); search_result_ = search_result ? search_result->Duplicate() : nullptr; - if (search_result_) + if (search_result_) { search_result_->AddObserver(this); + SetAccessibleName(search_result_->title()); + } SetVisible(new_result_view != nullptr); } @@ -161,4 +163,9 @@ return SearchResultContainerView::OnKeyPressed(event); } +void SearchResultAnswerCardView::GetAccessibleNodeData( + ui::AXNodeData* node_data) { + search_answer_container_view_->GetAccessibleNodeData(node_data); +} + } // namespace app_list
diff --git a/ui/app_list/views/search_result_answer_card_view.h b/ui/app_list/views/search_result_answer_card_view.h index 80ad1c8..2c40cd1f 100644 --- a/ui/app_list/views/search_result_answer_card_view.h +++ b/ui/app_list/views/search_result_answer_card_view.h
@@ -32,6 +32,7 @@ int DoUpdate() override; void UpdateSelectedIndex(int old_selected, int new_selected) override; bool OnKeyPressed(const ui::KeyEvent& event) override; + void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // Pointer to the container of the search answer; owned by the view hierarchy. // It's visible iff we have a search answer result.
diff --git a/ui/aura/test/ui_controls_factory_aurax11.cc b/ui/aura/test/ui_controls_factory_aurax11.cc index ce23851..1342645 100644 --- a/ui/aura/test/ui_controls_factory_aurax11.cc +++ b/ui/aura/test/ui_controls_factory_aurax11.cc
@@ -38,7 +38,7 @@ // Returns atom that indidates that the XEvent is marker event. Atom MarkerEventAtom() { - return XInternAtom(gfx::GetXDisplay(), "marker_event", False); + return ui::GetAtom("marker_event"); } // Returns true when the event is a marker event.
diff --git a/ui/aura/window_tree_host_x11.cc b/ui/aura/window_tree_host_x11.cc index af162588..f59d99e 100644 --- a/ui/aura/window_tree_host_x11.cc +++ b/ui/aura/window_tree_host_x11.cc
@@ -59,13 +59,6 @@ namespace { -const char* kAtomsToCache[] = { - "WM_DELETE_WINDOW", - "_NET_WM_PING", - "_NET_WM_PID", - NULL -}; - constexpr uint32_t kInputEventMask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask; @@ -122,8 +115,7 @@ x_root_window_(DefaultRootWindow(xdisplay_)), current_cursor_(ui::CursorType::kNull), window_mapped_(false), - bounds_(bounds), - atom_cache_(xdisplay_, kAtomsToCache) { + bounds_(bounds) { XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.background_pixmap = None; @@ -153,8 +145,8 @@ // should listen for activation events and anything else that GTK+ listens // for, and do something useful. ::Atom protocols[2]; - protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); - protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); + protocols[0] = ui::GetAtom("WM_DELETE_WINDOW"); + protocols[1] = ui::GetAtom("_NET_WM_PING"); XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with @@ -168,16 +160,9 @@ static_assert(sizeof(long) >= sizeof(pid_t), "pid_t should not be larger than long"); long pid = getpid(); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_PID"), - XA_CARDINAL, - 32, - PropModeReplace, - reinterpret_cast<unsigned char*>(&pid), 1); - - // Allow subclasses to create and cache additional atoms. - atom_cache_.allow_uncached_atoms(); + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_PID"), XA_CARDINAL, + 32, PropModeReplace, reinterpret_cast<unsigned char*>(&pid), + 1); XRRSelectInput(xdisplay_, x_root_window_, RRScreenChangeNotifyMask | RROutputChangeNotifyMask); @@ -322,10 +307,10 @@ break; case ClientMessage: { Atom message_type = static_cast<Atom>(xev->xclient.data.l[0]); - if (message_type == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { + if (message_type == ui::GetAtom("WM_DELETE_WINDOW")) { // We have received a close message from the window manager. OnHostCloseRequested(); - } else if (message_type == atom_cache_.GetAtom("_NET_WM_PING")) { + } else if (message_type == ui::GetAtom("_NET_WM_PING")) { XEvent reply_event = *xev; reply_event.xclient.window = x_root_window_;
diff --git a/ui/aura/window_tree_host_x11.h b/ui/aura/window_tree_host_x11.h index e3ede0c9..f9e1765 100644 --- a/ui/aura/window_tree_host_x11.h +++ b/ui/aura/window_tree_host_x11.h
@@ -15,7 +15,6 @@ #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/x/x11_atom_cache.h" // X forward decls to avoid including Xlib.h in a header file. typedef struct _XDisplay XDisplay; @@ -67,7 +66,6 @@ ::Window x_root_window() { return x_root_window_; } XDisplay* xdisplay() { return xdisplay_; } const gfx::Rect& bounds() const { return bounds_; } - ui::X11AtomCache* atom_cache() { return &atom_cache_; } private: // Dispatches XI2 events. Note that some events targetted for the X root @@ -98,8 +96,6 @@ // The bounds of |xwindow_|. gfx::Rect bounds_; - ui::X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostX11); };
diff --git a/ui/base/clipboard/clipboard_aurax11.cc b/ui/base/clipboard/clipboard_aurax11.cc index 39e86473..3def226 100644 --- a/ui/base/clipboard/clipboard_aurax11.cc +++ b/ui/base/clipboard/clipboard_aurax11.cc
@@ -34,7 +34,6 @@ #include "ui/events/platform/platform_event_source.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/geometry/size.h" -#include "ui/gfx/x/x11_atom_cache.h" namespace ui { @@ -46,19 +45,6 @@ const char kSaveTargets[] = "SAVE_TARGETS"; const char kTargets[] = "TARGETS"; -const char* kAtomsToCache[] = {kClipboard, - kClipboardManager, - Clipboard::kMimeTypePNG, - kMimeTypeFilename, - Clipboard::kMimeTypeMozillaURL, - Clipboard::kMimeTypeWebkitSmartPaste, - kSaveTargets, - kString, - kTargets, - kText, - kUtf8String, - nullptr}; - /////////////////////////////////////////////////////////////////////////////// // Uses the XFixes API to provide sequence numbers for GetSequenceNumber(). @@ -96,7 +82,7 @@ primary_sequence_number_(0) { int ignored; if (XFixesQueryExtension(gfx::GetXDisplay(), &event_base_, &ignored)) { - clipboard_atom_ = XInternAtom(gfx::GetXDisplay(), kClipboard, false); + clipboard_atom_ = GetAtom(kClipboard); XFixesSelectSelectionInput(gfx::GetXDisplay(), GetX11RootWindow(), clipboard_atom_, XFixesSetSelectionOwnerNotifyMask | @@ -145,7 +131,7 @@ public: typedef std::vector< ::Atom> AtomVector; - TargetList(const AtomVector& target_list, X11AtomCache* atom_cache); + explicit TargetList(const AtomVector& target_list); const AtomVector& target_list() { return target_list_; } @@ -155,17 +141,13 @@ private: AtomVector target_list_; - X11AtomCache* atom_cache_; }; -TargetList::TargetList(const AtomVector& target_list, - X11AtomCache* atom_cache) - : target_list_(target_list), - atom_cache_(atom_cache) { -} +TargetList::TargetList(const AtomVector& target_list) + : target_list_(target_list) {} bool TargetList::ContainsText() const { - std::vector< ::Atom> atoms = GetTextAtomsFrom(atom_cache_); + std::vector<::Atom> atoms = GetTextAtomsFrom(); for (std::vector< ::Atom>::const_iterator it = atoms.begin(); it != atoms.end(); ++it) { if (ContainsAtom(*it)) @@ -177,7 +159,7 @@ bool TargetList::ContainsFormat( const Clipboard::FormatType& format_type) const { - ::Atom atom = atom_cache_->GetAtom(format_type.ToString().c_str()); + ::Atom atom = GetAtom(format_type.ToString().c_str()); return ContainsAtom(atom); } @@ -233,8 +215,6 @@ AuraX11Details(); ~AuraX11Details() override; - X11AtomCache* atom_cache() { return &atom_cache_; } - // Returns the X11 type that we pass to various XSelection functions for the // given type. ::Atom LookupSelectionForClipboardType(ClipboardType type) const; @@ -305,8 +285,6 @@ // Events selected on |x_window_|. std::unique_ptr<XScopedEventSelector> x_window_events_; - X11AtomCache atom_cache_; - // Object which requests and receives selection data. SelectionRequestor selection_requestor_; @@ -335,13 +313,9 @@ CopyFromParent, // visual 0, NULL)), - atom_cache_(x_display_, kAtomsToCache), selection_requestor_(x_display_, x_window_, this), - clipboard_owner_(x_display_, x_window_, atom_cache_.GetAtom(kClipboard)), + clipboard_owner_(x_display_, x_window_, GetAtom(kClipboard)), primary_owner_(x_display_, x_window_, XA_PRIMARY) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); - XStoreName(x_display_, x_window_, "Chromium clipboard"); x_window_events_.reset( new XScopedEventSelector(x_window_, PropertyChangeMask)); @@ -366,7 +340,7 @@ } ::Atom ClipboardAuraX11::AuraX11Details::GetCopyPasteSelection() const { - return atom_cache_.GetAtom(kClipboard); + return GetAtom(kClipboard); } const SelectionFormatMap& @@ -385,7 +359,7 @@ void ClipboardAuraX11::AuraX11Details::InsertMapping( const std::string& key, const scoped_refptr<base::RefCountedMemory>& memory) { - ::Atom atom_key = atom_cache_.GetAtom(key.c_str()); + ::Atom atom_key = GetAtom(key.c_str()); clipboard_data_.Insert(atom_key, memory); } @@ -443,13 +417,10 @@ ::Atom out_type = None; if (selection_requestor_.PerformBlockingConvertSelection( - selection_name, - atom_cache_.GetAtom(kTargets), - &data, - &out_data_items, + selection_name, GetAtom(kTargets), &data, &out_data_items, &out_type)) { // Some apps return an |out_type| of "TARGETS". (crbug.com/377893) - if (out_type == XA_ATOM || out_type == atom_cache_.GetAtom(kTargets)) { + if (out_type == XA_ATOM || out_type == GetAtom(kTargets)) { const ::Atom* atom_array = reinterpret_cast<const ::Atom*>(data->front()); for (size_t i = 0; i < out_data_items; ++i) @@ -478,17 +449,17 @@ } } - return TargetList(out, &atom_cache_); + return TargetList(out); } std::vector<::Atom> ClipboardAuraX11::AuraX11Details::GetTextAtoms() const { - return GetTextAtomsFrom(&atom_cache_); + return GetTextAtomsFrom(); } std::vector<::Atom> ClipboardAuraX11::AuraX11Details::GetAtomsForFormat( const Clipboard::FormatType& format) { std::vector< ::Atom> atoms; - atoms.push_back(atom_cache_.GetAtom(format.ToString().c_str())); + atoms.push_back(GetAtom(format.ToString().c_str())); return atoms; } @@ -504,7 +475,7 @@ if (XGetSelectionOwner(x_display_, selection) != x_window_) return; - ::Atom clipboard_manager_atom = atom_cache_.GetAtom(kClipboardManager); + ::Atom clipboard_manager_atom = GetAtom(kClipboardManager); if (XGetSelectionOwner(x_display_, clipboard_manager_atom) == None) return; @@ -515,9 +486,7 @@ base::TimeTicks start = base::TimeTicks::Now(); selection_requestor_.PerformBlockingConvertSelectionWithParameter( - atom_cache_.GetAtom(kClipboardManager), - atom_cache_.GetAtom(kSaveTargets), - targets); + GetAtom(kClipboardManager), GetAtom(kSaveTargets), targets); UMA_HISTOGRAM_TIMES("Clipboard.X11StoreCopyPasteDuration", base::TimeTicks::Now() - start); }
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc b/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc index 2e4b975e..8123d38 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc +++ b/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc
@@ -33,17 +33,6 @@ const char kNetscapeURL[] = "_NETSCAPE_URL"; -const char* kAtomsToCache[] = {kString, - kText, - kUtf8String, - kDndSelection, - Clipboard::kMimeTypeURIList, - Clipboard::kMimeTypeMozillaURL, - kNetscapeURL, - Clipboard::kMimeTypeText, - kRendererTaint, - nullptr}; - } // namespace OSExchangeDataProviderAuraX11::OSExchangeDataProviderAuraX11( @@ -53,35 +42,27 @@ x_root_window_(DefaultRootWindow(x_display_)), own_window_(false), x_window_(x_window), - atom_cache_(x_display_, kAtomsToCache), format_map_(selection), - selection_owner_(x_display_, x_window_, - atom_cache_.GetAtom(kDndSelection)) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); -} + selection_owner_(x_display_, x_window_, GetAtom(kDndSelection)) {} OSExchangeDataProviderAuraX11::OSExchangeDataProviderAuraX11() : x_display_(gfx::GetXDisplay()), x_root_window_(DefaultRootWindow(x_display_)), own_window_(true), - x_window_(XCreateWindow( - x_display_, - x_root_window_, - -100, -100, 10, 10, // x, y, width, height - 0, // border width - CopyFromParent, // depth - InputOnly, - CopyFromParent, // visual - 0, - NULL)), - atom_cache_(x_display_, kAtomsToCache), + x_window_(XCreateWindow(x_display_, + x_root_window_, + -100, + -100, + 10, + 10, // x, y, width, height + 0, // border width + CopyFromParent, // depth + InputOnly, + CopyFromParent, // visual + 0, + NULL)), format_map_(), - selection_owner_(x_display_, x_window_, - atom_cache_.GetAtom(kDndSelection)) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); - + selection_owner_(x_display_, x_window_, GetAtom(kDndSelection)) { XStoreName(x_display_, x_window_, "Chromium Drag & Drop Window"); PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); @@ -119,14 +100,13 @@ void OSExchangeDataProviderAuraX11::MarkOriginatedFromRenderer() { std::string empty; - format_map_.Insert(atom_cache_.GetAtom(kRendererTaint), + format_map_.Insert(GetAtom(kRendererTaint), scoped_refptr<base::RefCountedMemory>( base::RefCountedString::TakeString(&empty))); } bool OSExchangeDataProviderAuraX11::DidOriginateFromRenderer() const { - return format_map_.find(atom_cache_.GetAtom(kRendererTaint)) != - format_map_.end(); + return format_map_.find(GetAtom(kRendererTaint)) != format_map_.end(); } void OSExchangeDataProviderAuraX11::SetString(const base::string16& text_data) { @@ -137,10 +117,10 @@ scoped_refptr<base::RefCountedMemory> mem( base::RefCountedString::TakeString(&utf8)); - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeText), mem); - format_map_.Insert(atom_cache_.GetAtom(kText), mem); - format_map_.Insert(atom_cache_.GetAtom(kString), mem); - format_map_.Insert(atom_cache_.GetAtom(kUtf8String), mem); + format_map_.Insert(GetAtom(Clipboard::kMimeTypeText), mem); + format_map_.Insert(GetAtom(kText), mem); + format_map_.Insert(GetAtom(kString), mem); + format_map_.Insert(GetAtom(kUtf8String), mem); } void OSExchangeDataProviderAuraX11::SetURL(const GURL& url, @@ -158,8 +138,7 @@ scoped_refptr<base::RefCountedMemory> mem( base::RefCountedBytes::TakeVector(&data)); - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeMozillaURL), - mem); + format_map_.Insert(GetAtom(Clipboard::kMimeTypeMozillaURL), mem); // Set a string fallback as well. SetString(spec); @@ -179,7 +158,7 @@ std::string netscape_url = url.spec(); netscape_url += "\n"; netscape_url += base::UTF16ToUTF8(title); - format_map_.Insert(atom_cache_.GetAtom(kNetscapeURL), + format_map_.Insert(GetAtom(kNetscapeURL), scoped_refptr<base::RefCountedMemory>( base::RefCountedString::TakeString(&netscape_url))); } @@ -205,7 +184,7 @@ std::string joined_data = base::JoinString(paths, "\n"); scoped_refptr<base::RefCountedMemory> mem( base::RefCountedString::TakeString(&joined_data)); - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeURIList), mem); + format_map_.Insert(GetAtom(Clipboard::kMimeTypeURIList), mem); } void OSExchangeDataProviderAuraX11::SetPickledData( @@ -219,7 +198,7 @@ scoped_refptr<base::RefCountedMemory> mem( base::RefCountedBytes::TakeVector(&bytes)); - format_map_.Insert(atom_cache_.GetAtom(format.ToString().c_str()), mem); + format_map_.Insert(GetAtom(format.ToString().c_str()), mem); } bool OSExchangeDataProviderAuraX11::GetString(base::string16* result) const { @@ -230,7 +209,7 @@ return false; } - std::vector< ::Atom> text_atoms = ui::GetTextAtomsFrom(&atom_cache_); + std::vector<::Atom> text_atoms = ui::GetTextAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(text_atoms, GetTargets(), &requested_types); @@ -248,7 +227,7 @@ OSExchangeData::FilenameToURLPolicy policy, GURL* url, base::string16* title) const { - std::vector< ::Atom> url_atoms = ui::GetURLAtomsFrom(&atom_cache_); + std::vector<::Atom> url_atoms = ui::GetURLAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -258,7 +237,7 @@ // but that doesn't match the assumptions of the rest of the system which // expect single types. - if (data.GetType() == atom_cache_.GetAtom(Clipboard::kMimeTypeMozillaURL)) { + if (data.GetType() == GetAtom(Clipboard::kMimeTypeMozillaURL)) { // Mozilla URLs are (UTF16: URL, newline, title). base::string16 unparsed; data.AssignTo(&unparsed); @@ -275,8 +254,7 @@ *url = GURL(tokens[0]); return true; } - } else if (data.GetType() == atom_cache_.GetAtom( - Clipboard::kMimeTypeURIList)) { + } else if (data.GetType() == GetAtom(Clipboard::kMimeTypeURIList)) { std::vector<std::string> tokens = ui::ParseURIList(data); for (std::vector<std::string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { @@ -306,7 +284,7 @@ bool OSExchangeDataProviderAuraX11::GetFilenames( std::vector<FileInfo>* filenames) const { - std::vector< ::Atom> url_atoms = ui::GetURIListAtomsFrom(&atom_cache_); + std::vector<::Atom> url_atoms = ui::GetURIListAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -331,7 +309,7 @@ const Clipboard::FormatType& format, base::Pickle* pickle) const { std::vector< ::Atom> requested_types; - requested_types.push_back(atom_cache_.GetAtom(format.ToString().c_str())); + requested_types.push_back(GetAtom(format.ToString().c_str())); ui::SelectionData data(format_map_.GetFirstOf(requested_types)); if (data.IsValid()) { @@ -346,7 +324,7 @@ } bool OSExchangeDataProviderAuraX11::HasString() const { - std::vector< ::Atom> text_atoms = ui::GetTextAtomsFrom(&atom_cache_); + std::vector<::Atom> text_atoms = ui::GetTextAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(text_atoms, GetTargets(), &requested_types); return !requested_types.empty() && !HasFile(); @@ -354,7 +332,7 @@ bool OSExchangeDataProviderAuraX11::HasURL( OSExchangeData::FilenameToURLPolicy policy) const { - std::vector< ::Atom> url_atoms = ui::GetURLAtomsFrom(&atom_cache_); + std::vector<::Atom> url_atoms = ui::GetURLAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -365,11 +343,10 @@ // Windows does and stuffs all the data into one mime type. ui::SelectionData data(format_map_.GetFirstOf(requested_types)); if (data.IsValid()) { - if (data.GetType() == atom_cache_.GetAtom(Clipboard::kMimeTypeMozillaURL)) { + if (data.GetType() == GetAtom(Clipboard::kMimeTypeMozillaURL)) { // File managers shouldn't be using this type, so this is a URL. return true; - } else if (data.GetType() == atom_cache_.GetAtom( - ui::Clipboard::kMimeTypeURIList)) { + } else if (data.GetType() == GetAtom(ui::Clipboard::kMimeTypeURIList)) { std::vector<std::string> tokens = ui::ParseURIList(data); for (std::vector<std::string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { @@ -386,7 +363,7 @@ } bool OSExchangeDataProviderAuraX11::HasFile() const { - std::vector< ::Atom> url_atoms = ui::GetURIListAtomsFrom(&atom_cache_); + std::vector<::Atom> url_atoms = ui::GetURIListAtomsFrom(); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -414,7 +391,7 @@ bool OSExchangeDataProviderAuraX11::HasCustomFormat( const Clipboard::FormatType& format) const { std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(format.ToString().c_str())); + url_atoms.push_back(GetAtom(format.ToString().c_str())); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -426,7 +403,7 @@ const std::string& file_contents) { DCHECK(!filename.empty()); DCHECK(format_map_.end() == - format_map_.find(atom_cache_.GetAtom(Clipboard::kMimeTypeMozillaURL))); + format_map_.find(GetAtom(Clipboard::kMimeTypeMozillaURL))); file_contents_name_ = filename; @@ -446,13 +423,12 @@ // things simpler for Chrome, we always 'fail' and let the destination do // the work. std::string failure("F"); - format_map_.Insert( - atom_cache_.GetAtom("XdndDirectSave0"), - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&failure))); + format_map_.Insert(GetAtom("XdndDirectSave0"), + scoped_refptr<base::RefCountedMemory>( + base::RefCountedString::TakeString(&failure))); std::string file_contents_copy = file_contents; format_map_.Insert( - atom_cache_.GetAtom("application/octet-stream"), + GetAtom("application/octet-stream"), scoped_refptr<base::RefCountedMemory>( base::RefCountedString::TakeString(&file_contents_copy))); } @@ -468,13 +444,13 @@ scoped_refptr<base::RefCountedMemory> mem( base::RefCountedBytes::TakeVector(&bytes)); - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML), mem); + format_map_.Insert(GetAtom(Clipboard::kMimeTypeHTML), mem); } bool OSExchangeDataProviderAuraX11::GetHtml(base::string16* html, GURL* base_url) const { std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)); + url_atoms.push_back(GetAtom(Clipboard::kMimeTypeHTML)); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); @@ -490,7 +466,7 @@ bool OSExchangeDataProviderAuraX11::HasHtml() const { std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)); + url_atoms.push_back(GetAtom(Clipboard::kMimeTypeHTML)); std::vector< ::Atom> requested_types; ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types);
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11.h b/ui/base/dragdrop/os_exchange_data_provider_aurax11.h index fbf19bc..9ffe068 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11.h +++ b/ui/base/dragdrop/os_exchange_data_provider_aurax11.h
@@ -23,7 +23,6 @@ #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/image/image_skia.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "url/gurl.h" namespace ui { @@ -129,8 +128,6 @@ ::Window x_window_; - X11AtomCache atom_cache_; - // A representation of data. This is either passed to us from the other // process, or built up through a sequence of Set*() calls. It can be passed // to |selection_owner_| when we take the selection.
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc b/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc index 90fa7c20..c96661c4 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc +++ b/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc
@@ -13,6 +13,7 @@ #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/dragdrop/file_info.h" +#include "ui/base/x/x11_util.h" #include "ui/events/platform/x11/x11_event_source_glib.h" #include "url/gurl.h" @@ -32,9 +33,7 @@ scoped_refptr<base::RefCountedMemory> mem( base::RefCountedString::TakeString(&contents_copy)); - provider.format_map_.Insert( - provider.atom_cache_.GetAtom(ui::Clipboard::kMimeTypeURIList), - mem); + provider.format_map_.Insert(GetAtom(ui::Clipboard::kMimeTypeURIList), mem); } protected:
diff --git a/ui/base/x/selection_owner.cc b/ui/base/x/selection_owner.cc index 83e6f38..fa8c321 100644 --- a/ui/base/x/selection_owner.cc +++ b/ui/base/x/selection_owner.cc
@@ -26,9 +26,6 @@ const char kTargets[] = "TARGETS"; const char kTimestamp[] = "TIMESTAMP"; -const char* kAtomsToCache[] = {kAtomPair, kIncr, kMultiple, kSaveTargets, - kTargets, kTimestamp, NULL}; - // The period of |incremental_transfer_abort_timer_|. Arbitrary but must be <= // than kIncrementalTransferTimeoutMs. const int kTimerPeriodMs = 1000; @@ -98,9 +95,7 @@ : x_display_(x_display), x_window_(x_window), selection_name_(selection_name), - max_request_size_(GetMaxRequestSize(x_display)), - atom_cache_(x_display_, kAtomsToCache) { -} + max_request_size_(GetMaxRequestSize(x_display)) {} SelectionOwner::~SelectionOwner() { // If we are the selection owner, we need to release the selection so we @@ -149,7 +144,7 @@ reply.xselection.property = None; // Indicates failure reply.xselection.time = event.xselectionrequest.time; - if (requested_target == atom_cache_.GetAtom(kMultiple)) { + if (requested_target == GetAtom(kMultiple)) { // The contents of |requested_property| should be a list of // <target,property> pairs. std::vector<std::pair<XAtom,XAtom> > conversions; @@ -169,11 +164,7 @@ // Set the property to indicate which conversions succeeded. This matches // what GTK does. XChangeProperty( - x_display_, - requestor, - requested_property, - atom_cache_.GetAtom(kAtomPair), - 32, + x_display_, requestor, requested_property, GetAtom(kAtomPair), 32, PropModeReplace, reinterpret_cast<const unsigned char*>(&conversion_results.front()), conversion_results.size()); @@ -215,10 +206,10 @@ bool SelectionOwner::ProcessTarget(XAtom target, XID requestor, XAtom property) { - XAtom multiple_atom = atom_cache_.GetAtom(kMultiple); - XAtom save_targets_atom = atom_cache_.GetAtom(kSaveTargets); - XAtom targets_atom = atom_cache_.GetAtom(kTargets); - XAtom timestamp_atom = atom_cache_.GetAtom(kTimestamp); + XAtom multiple_atom = GetAtom(kMultiple); + XAtom save_targets_atom = GetAtom(kSaveTargets); + XAtom targets_atom = GetAtom(kTargets); + XAtom timestamp_atom = GetAtom(kTimestamp); if (target == multiple_atom || target == save_targets_atom) return false; @@ -255,14 +246,9 @@ // the size of X requests. Notify the selection requestor that the data // will be sent incrementally by returning data of type "INCR". long length = it->second->size(); - XChangeProperty(x_display_, - requestor, - property, - atom_cache_.GetAtom(kIncr), - 32, + XChangeProperty(x_display_, requestor, property, GetAtom(kIncr), 32, PropModeReplace, - reinterpret_cast<unsigned char*>(&length), - 1); + reinterpret_cast<unsigned char*>(&length), 1); // Wait for the selection requestor to indicate that it has processed // the selection result before sending the first chunk of data. The
diff --git a/ui/base/x/selection_owner.h b/ui/base/x/selection_owner.h index 52657e3..d995dc4 100644 --- a/ui/base/x/selection_owner.h +++ b/ui/base/x/selection_owner.h
@@ -16,7 +16,6 @@ #include "base/timer/timer.h" #include "ui/base/ui_base_export.h" #include "ui/base/x/selection_utils.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" namespace ui { @@ -140,8 +139,6 @@ // Used to abort stale incremental data transfers. base::RepeatingTimer incremental_transfer_abort_timer_; - X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(SelectionOwner); };
diff --git a/ui/base/x/selection_requestor.cc b/ui/base/x/selection_requestor.cc index 324d642..a6e402c 100644 --- a/ui/base/x/selection_requestor.cc +++ b/ui/base/x/selection_requestor.cc
@@ -22,12 +22,6 @@ const char kChromeSelection[] = "CHROME_SELECTION"; const char kIncr[] = "INCR"; -const char* kAtomsToCache[] = { - kChromeSelection, - kIncr, - NULL -}; - // The period of |abort_timer_|. Arbitrary but must be <= than // kRequestTimeoutMs. const int kTimerPeriodMs = 100; @@ -67,9 +61,8 @@ x_window_(x_window), x_property_(None), dispatcher_(dispatcher), - current_request_index_(0u), - atom_cache_(x_display_, kAtomsToCache) { - x_property_ = atom_cache_.GetAtom(kChromeSelection); + current_request_index_(0u) { + x_property_ = GetAtom(kChromeSelection); } SelectionRequestor::~SelectionRequestor() {} @@ -169,7 +162,7 @@ if (event_property != None) XDeleteProperty(x_display_, x_window_, event_property); - if (request->out_type == atom_cache_.GetAtom(kIncr)) { + if (request->out_type == GetAtom(kIncr)) { request->data_sent_incrementally = true; request->out_data.clear(); request->out_data_items = 0u;
diff --git a/ui/base/x/selection_requestor.h b/ui/base/x/selection_requestor.h index e698010b..65d944a 100644 --- a/ui/base/x/selection_requestor.h +++ b/ui/base/x/selection_requestor.h
@@ -16,7 +16,6 @@ #include "base/time/time.h" #include "base/timer/timer.h" #include "ui/base/ui_base_export.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" namespace ui { @@ -150,8 +149,6 @@ // Used to abort requests if the selection owner takes too long to respond. base::RepeatingTimer abort_timer_; - X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(SelectionRequestor); };
diff --git a/ui/base/x/selection_requestor_unittest.cc b/ui/base/x/selection_requestor_unittest.cc index 43e14d5..5a94412 100644 --- a/ui/base/x/selection_requestor_unittest.cc +++ b/ui/base/x/selection_requestor_unittest.cc
@@ -15,30 +15,15 @@ #include "ui/base/x/selection_utils.h" #include "ui/base/x/x11_util.h" #include "ui/events/platform/platform_event_source.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include <X11/Xlib.h> namespace ui { -namespace { - -const char* kAtomsToCache[] = { - "STRING", - NULL -}; - -} // namespace - class SelectionRequestorTest : public testing::Test { public: - SelectionRequestorTest() - : x_display_(gfx::GetXDisplay()), - x_window_(None), - atom_cache_(gfx::GetXDisplay(), kAtomsToCache) { - atom_cache_.allow_uncached_atoms(); - } + SelectionRequestorTest() : x_display_(gfx::GetXDisplay()), x_window_(None) {} ~SelectionRequestorTest() override {} @@ -49,9 +34,7 @@ void SendSelectionNotify(XAtom selection, XAtom target, const std::string& value) { - ui::SetStringProperty(x_window_, - requestor_->x_property_, - atom_cache_.GetAtom("STRING"), + ui::SetStringProperty(x_window_, requestor_->x_property_, GetAtom("STRING"), value); XEvent xev; @@ -104,7 +87,6 @@ std::unique_ptr<SelectionRequestor> requestor_; base::MessageLoopForUI message_loop_; - X11AtomCache atom_cache_; private: DISALLOW_COPY_AND_ASSIGN(SelectionRequestorTest); @@ -114,7 +96,6 @@ // Converts |selection| to |target| and checks the returned values. void PerformBlockingConvertSelection(SelectionRequestor* requestor, - X11AtomCache* atom_cache, XAtom selection, XAtom target, const std::string& expected_data) { @@ -125,7 +106,7 @@ selection, target, &out_data, &out_data_items, &out_type)); EXPECT_EQ(expected_data, ui::RefCountedMemoryToString(out_data)); EXPECT_EQ(expected_data.size(), out_data_items); - EXPECT_EQ(atom_cache->GetAtom("STRING"), out_type); + EXPECT_EQ(GetAtom("STRING"), out_type); } } // namespace @@ -136,17 +117,16 @@ // Assume that |selection| will have no owner. If there is an owner, the owner // will set the property passed into the XConvertSelection() request which is // undesirable. - XAtom selection = atom_cache_.GetAtom("FAKE_SELECTION"); + XAtom selection = GetAtom("FAKE_SELECTION"); - XAtom target1 = atom_cache_.GetAtom("TARGET1"); - XAtom target2 = atom_cache_.GetAtom("TARGET2"); + XAtom target1 = GetAtom("TARGET1"); + XAtom target2 = GetAtom("TARGET2"); base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); loop->task_runner()->PostTask( - FROM_HERE, - base::Bind(&PerformBlockingConvertSelection, - base::Unretained(requestor_.get()), - base::Unretained(&atom_cache_), selection, target2, "Data2")); + FROM_HERE, base::Bind(&PerformBlockingConvertSelection, + base::Unretained(requestor_.get()), selection, + target2, "Data2")); loop->task_runner()->PostTask( FROM_HERE, base::Bind(&SelectionRequestorTest::SendSelectionNotify, @@ -155,8 +135,8 @@ FROM_HERE, base::Bind(&SelectionRequestorTest::SendSelectionNotify, base::Unretained(this), selection, target2, "Data2")); - PerformBlockingConvertSelection( - requestor_.get(), &atom_cache_, selection, target1, "Data1"); + PerformBlockingConvertSelection(requestor_.get(), selection, target1, + "Data1"); } } // namespace ui
diff --git a/ui/base/x/selection_utils.cc b/ui/base/x/selection_utils.cc index 2d57e49..48eff62 100644 --- a/ui/base/x/selection_utils.cc +++ b/ui/base/x/selection_utils.cc
@@ -16,7 +16,6 @@ #include "base/strings/utf_string_conversions.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/x/x11_util.h" -#include "ui/gfx/x/x11_atom_cache.h" namespace ui { @@ -26,36 +25,26 @@ const char kTextPlainUtf8[] = "text/plain;charset=utf-8"; const char kUtf8String[] = "UTF8_STRING"; -const char* kSelectionDataAtoms[] = { - Clipboard::kMimeTypeHTML, - kString, - kText, - kTextPlain, - kTextPlainUtf8, - kUtf8String, - NULL -}; - -std::vector< ::Atom> GetTextAtomsFrom(const X11AtomCache* atom_cache) { +std::vector<::Atom> GetTextAtomsFrom() { std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(kUtf8String)); - atoms.push_back(atom_cache->GetAtom(kString)); - atoms.push_back(atom_cache->GetAtom(kText)); - atoms.push_back(atom_cache->GetAtom(kTextPlain)); - atoms.push_back(atom_cache->GetAtom(kTextPlainUtf8)); + atoms.push_back(GetAtom(kUtf8String)); + atoms.push_back(GetAtom(kString)); + atoms.push_back(GetAtom(kText)); + atoms.push_back(GetAtom(kTextPlain)); + atoms.push_back(GetAtom(kTextPlainUtf8)); return atoms; } -std::vector< ::Atom> GetURLAtomsFrom(const X11AtomCache* atom_cache) { +std::vector<::Atom> GetURLAtomsFrom() { std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(Clipboard::kMimeTypeURIList)); - atoms.push_back(atom_cache->GetAtom(Clipboard::kMimeTypeMozillaURL)); + atoms.push_back(GetAtom(Clipboard::kMimeTypeURIList)); + atoms.push_back(GetAtom(Clipboard::kMimeTypeMozillaURL)); return atoms; } -std::vector< ::Atom> GetURIListAtomsFrom(const X11AtomCache* atom_cache) { +std::vector<::Atom> GetURIListAtomsFrom() { std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(Clipboard::kMimeTypeURIList)); + atoms.push_back(GetAtom(Clipboard::kMimeTypeURIList)); return atoms; } @@ -155,24 +144,15 @@ /////////////////////////////////////////////////////////////////////////////// -SelectionData::SelectionData() - : type_(None), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} +SelectionData::SelectionData() : type_(None) {} SelectionData::SelectionData( ::Atom type, const scoped_refptr<base::RefCountedMemory>& memory) - : type_(type), - memory_(memory), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} + : type_(type), memory_(memory) {} SelectionData::SelectionData(const SelectionData& rhs) - : type_(rhs.type_), - memory_(rhs.memory_), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} + : type_(rhs.type_), memory_(rhs.memory_) {} SelectionData::~SelectionData() {} @@ -201,12 +181,10 @@ } std::string SelectionData::GetText() const { - if (type_ == atom_cache_.GetAtom(kUtf8String) || - type_ == atom_cache_.GetAtom(kText) || - type_ == atom_cache_.GetAtom(kTextPlainUtf8)) { + if (type_ == GetAtom(kUtf8String) || type_ == GetAtom(kText) || + type_ == GetAtom(kTextPlainUtf8)) { return RefCountedMemoryToString(memory_); - } else if (type_ == atom_cache_.GetAtom(kString) || - type_ == atom_cache_.GetAtom(kTextPlain)) { + } else if (type_ == GetAtom(kString) || type_ == GetAtom(kTextPlain)) { std::string result; base::ConvertToUtf8AndNormalize(RefCountedMemoryToString(memory_), base::kCodepageLatin1, @@ -223,7 +201,7 @@ base::string16 SelectionData::GetHtml() const { base::string16 markup; - if (type_ == atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)) { + if (type_ == GetAtom(Clipboard::kMimeTypeHTML)) { const unsigned char* data = GetData(); size_t size = GetSize();
diff --git a/ui/base/x/selection_utils.h b/ui/base/x/selection_utils.h index 1f911a3..f7d1e18 100644 --- a/ui/base/x/selection_utils.h +++ b/ui/base/x/selection_utils.h
@@ -16,25 +16,20 @@ #include "base/memory/ref_counted_memory.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/ui_base_export.h" -#include "ui/gfx/x/x11_atom_cache.h" namespace ui { class SelectionData; -class X11AtomCache; extern const char kString[]; extern const char kText[]; extern const char kUtf8String[]; // Returns a list of all text atoms that we handle. -UI_BASE_EXPORT std::vector< ::Atom> GetTextAtomsFrom( - const X11AtomCache* atom_cache); +UI_BASE_EXPORT std::vector<::Atom> GetTextAtomsFrom(); -UI_BASE_EXPORT std::vector< ::Atom> GetURLAtomsFrom( - const X11AtomCache* atom_cache); +UI_BASE_EXPORT std::vector<::Atom> GetURLAtomsFrom(); -UI_BASE_EXPORT std::vector< ::Atom> GetURIListAtomsFrom( - const X11AtomCache* atom_cache); +UI_BASE_EXPORT std::vector<::Atom> GetURIListAtomsFrom(); // Places the intersection of |desired| and |offered| into |output|. UI_BASE_EXPORT void GetAtomIntersection(const std::vector< ::Atom>& desired, @@ -122,8 +117,6 @@ private: ::Atom type_; scoped_refptr<base::RefCountedMemory> memory_; - - X11AtomCache atom_cache_; }; } // namespace ui
diff --git a/ui/base/x/x11_util.cc b/ui/base/x/x11_util.cc index 834eff63..bf3231c 100644 --- a/ui/base/x/x11_util.cc +++ b/ui/base/x/x11_util.cc
@@ -57,6 +57,7 @@ #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/skia_util.h" +#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_error_tracker.h" #if defined(OS_FREEBSD) @@ -894,8 +895,7 @@ } XAtom GetAtom(const char* name) { - // TODO(derat): Cache atoms to avoid round-trips to the server. - return XInternAtom(gfx::GetXDisplay(), name, false); + return X11AtomCache::GetInstance()->GetAtom(name); } void SetWindowClassHint(XDisplay* display, @@ -1391,7 +1391,7 @@ for (int i = 0; i < visuals_len; ++i) visuals_[visual_list[i].visualid].reset(new XVisualData(visual_list[i])); - XAtom NET_WM_CM_S0 = XInternAtom(display_, "_NET_WM_CM_S0", False); + XAtom NET_WM_CM_S0 = GetAtom("_NET_WM_CM_S0"); using_compositing_wm_ = XGetSelectionOwner(display_, NET_WM_CM_S0) != None; // Choose the opaque visual.
diff --git a/ui/display/manager/chromeos/x11/native_display_delegate_x11.cc b/ui/display/manager/chromeos/x11/native_display_delegate_x11.cc index 56f7180..d94e618a 100644 --- a/ui/display/manager/chromeos/x11/native_display_delegate_x11.cc +++ b/ui/display/manager/chromeos/x11/native_display_delegate_x11.cc
@@ -16,6 +16,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "ui/base/x/x11_util.h" #include "ui/display/manager/chromeos/x11/display_mode_x11.h" #include "ui/display/manager/chromeos/x11/display_snapshot_x11.h" #include "ui/display/manager/chromeos/x11/display_util_x11.h" @@ -402,8 +403,7 @@ Atom actual_type = None; int success = 0; RROutput output_id = static_cast<const DisplaySnapshotX11&>(output).output(); - // TODO(kcwu): Use X11AtomCache to save round trip time of XInternAtom. - Atom prop = XInternAtom(display_, kContentProtectionAtomName, False); + Atom prop = ui::GetAtom(kContentProtectionAtomName); // TODO(kcwu): Move this to x11_util (similar method calls in this file and // output_util.cc) @@ -430,13 +430,11 @@ if (success == Success && actual_type == XA_ATOM && actual_format == 32 && nitems == 1) { Atom value = reinterpret_cast<Atom*>(values)[0]; - if (value == XInternAtom(display_, kProtectionUndesiredAtomName, False)) { + if (value == ui::GetAtom(kProtectionUndesiredAtomName)) { *state = HDCP_STATE_UNDESIRED; - } else if (value == - XInternAtom(display_, kProtectionDesiredAtomName, False)) { + } else if (value == ui::GetAtom(kProtectionDesiredAtomName)) { *state = HDCP_STATE_DESIRED; - } else if (value == - XInternAtom(display_, kProtectionEnabledAtomName, False)) { + } else if (value == ui::GetAtom(kProtectionEnabledAtomName)) { *state = HDCP_STATE_ENABLED; } else { LOG(ERROR) << "Unknown " << kContentProtectionAtomName @@ -461,14 +459,14 @@ bool NativeDisplayDelegateX11::SetHDCPState(const DisplaySnapshot& output, HDCPState state) { - Atom name = XInternAtom(display_, kContentProtectionAtomName, False); + Atom name = ui::GetAtom(kContentProtectionAtomName); Atom value = None; switch (state) { case HDCP_STATE_UNDESIRED: - value = XInternAtom(display_, kProtectionUndesiredAtomName, False); + value = ui::GetAtom(kProtectionUndesiredAtomName); break; case HDCP_STATE_DESIRED: - value = XInternAtom(display_, kProtectionDesiredAtomName, False); + value = ui::GetAtom(kProtectionDesiredAtomName); break; default: NOTREACHED() << "Invalid HDCP state: " << state; @@ -545,8 +543,8 @@ } bool NativeDisplayDelegateX11::IsOutputAspectPreservingScaling(RROutput id) { - Atom scaling_prop = XInternAtom(display_, "scaling mode", False); - Atom full_aspect_atom = XInternAtom(display_, "Full aspect", False); + Atom scaling_prop = ui::GetAtom("scaling mode"); + Atom full_aspect_atom = ui::GetAtom("Full aspect"); if (scaling_prop == None || full_aspect_atom == None) return false;
diff --git a/ui/display/util/x11/edid_parser_x11.cc b/ui/display/util/x11/edid_parser_x11.cc index c7d8e59..a394708 100644 --- a/ui/display/util/x11/edid_parser_x11.cc +++ b/ui/display/util/x11/edid_parser_x11.cc
@@ -10,6 +10,7 @@ #include "base/strings/string_util.h" #include "ui/display/util/edid_parser.h" +#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" namespace display { @@ -33,9 +34,8 @@ Display* display = gfx::GetXDisplay(); - static Atom edid_property = XInternAtom( - gfx::GetXDisplay(), - RR_PROPERTY_RANDR_EDID, false); + static Atom edid_property = + ui::X11AtomCache::GetInstance()->GetAtom(RR_PROPERTY_RANDR_EDID); bool has_edid_property = false; int num_properties = 0;
diff --git a/ui/events/devices/x11/device_data_manager_x11.cc b/ui/events/devices/x11/device_data_manager_x11.cc index 370aa04..abc70fc 100644 --- a/ui/events/devices/x11/device_data_manager_x11.cc +++ b/ui/events/devices/x11/device_data_manager_x11.cc
@@ -26,6 +26,7 @@ #include "ui/events/event_switches.h" #include "ui/events/keycodes/keyboard_code_conversion_x.h" #include "ui/gfx/geometry/point3_f.h" +#include "ui/gfx/x/x11_atom_cache.h" // XIScrollClass was introduced in XI 2.1 so we need to define it here // for backward-compatibility with older versions of XInput. @@ -165,7 +166,6 @@ DeviceDataManagerX11::DeviceDataManagerX11() : xi_opcode_(-1), high_precision_scrolling_disabled_(IsHighPrecisionScrollingDisabled()), - atom_cache_(gfx::GetXDisplay(), kCachedAtoms), button_map_count_(0) { CHECK(gfx::GetXDisplay()); InitializeXInputInternal(); @@ -243,7 +243,7 @@ // Find all the touchpad devices. const XDeviceList& dev_list = ui::DeviceListCacheX11::GetInstance()->GetXDeviceList(display); - Atom xi_touchpad = XInternAtom(display, XI_TOUCHPAD, false); + Atom xi_touchpad = ui::X11AtomCache::GetInstance()->GetAtom(XI_TOUCHPAD); for (int i = 0; i < dev_list.count; ++i) if (dev_list[i].type == xi_touchpad) touchpads_[dev_list[i].id] = true; @@ -256,7 +256,8 @@ ui::DeviceListCacheX11::GetInstance()->GetXI2DeviceList(display); Atom atoms[DT_LAST_ENTRY]; for (int data_type = 0; data_type < DT_LAST_ENTRY; ++data_type) - atoms[data_type] = atom_cache_.GetAtom(kCachedAtoms[data_type]); + atoms[data_type] = + ui::X11AtomCache::GetInstance()->GetAtom(kCachedAtoms[data_type]); for (int i = 0; i < info_list.count; ++i) { const XIDeviceInfo& info = info_list[i];
diff --git a/ui/events/devices/x11/device_data_manager_x11.h b/ui/events/devices/x11/device_data_manager_x11.h index 587e600..752404e 100644 --- a/ui/events/devices/x11/device_data_manager_x11.h +++ b/ui/events/devices/x11/device_data_manager_x11.h
@@ -28,7 +28,6 @@ #include "ui/events/event_constants.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" namespace ui { @@ -397,9 +396,6 @@ // devices when they are re-enabled. std::map<int, ui::InputDevice> blocked_keyboard_devices_; - // X11 atoms cache. - X11AtomCache atom_cache_; - unsigned char button_map_[256]; int button_map_count_;
diff --git a/ui/events/platform/x11/x11_event_source.cc b/ui/events/platform/x11/x11_event_source.cc index f8bbaeb..6f2d835 100644 --- a/ui/events/platform/x11/x11_event_source.cc +++ b/ui/events/platform/x11/x11_event_source.cc
@@ -16,6 +16,7 @@ #include "ui/events/event_utils.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/x11/x11_hotplug_event_handler.h" +#include "ui/gfx/x/x11_atom_cache.h" namespace ui { @@ -156,7 +157,7 @@ // Create a new Window and Atom that will be used for the property change. dummy_window_ = XCreateSimpleWindow(display_, DefaultRootWindow(display_), 0, 0, 1, 1, 0, 0, 0); - dummy_atom_ = XInternAtom(display_, "CHROMIUM_TIMESTAMP", False); + dummy_atom_ = X11AtomCache::GetInstance()->GetAtom("CHROMIUM_TIMESTAMP"); dummy_window_events_.reset( new XScopedEventSelector(dummy_window_, PropertyChangeMask)); dummy_initialized_ = true;
diff --git a/ui/events/platform/x11/x11_hotplug_event_handler.cc b/ui/events/platform/x11/x11_hotplug_event_handler.cc index be7bb09..f6f6b15 100644 --- a/ui/events/platform/x11/x11_hotplug_event_handler.cc +++ b/ui/events/platform/x11/x11_hotplug_event_handler.cc
@@ -25,11 +25,13 @@ #include "base/sys_info.h" #include "base/threading/thread_task_runner_handle.h" #include "base/threading/worker_pool.h" +#include "ui/base/x/x11_util.h" #include "ui/events/devices/device_data_manager.h" #include "ui/events/devices/device_hotplug_event_observer.h" #include "ui/events/devices/device_util_linux.h" #include "ui/events/devices/input_device.h" #include "ui/events/devices/touchscreen_device.h" +#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #ifndef XI_PROP_PRODUCT_ID @@ -50,17 +52,6 @@ "gpio-keys.12", "ROCKCHIP-I2S Headset Jack"}; -const char* kCachedAtomList[] = { - "Abs MT Position X", - "Abs MT Position Y", - XI_KEYBOARD, - XI_MOUSE, - XI_TOUCHPAD, - XI_TOUCHSCREEN, - XI_PROP_PRODUCT_ID, - NULL, -}; - enum DeviceType { DEVICE_TYPE_KEYBOARD, DEVICE_TYPE_MOUSE, @@ -206,7 +197,7 @@ // Input device has a property "Device Node" pointing to its dev input node, // e.g. Device Node (250): "/dev/input/event8" - Atom device_node = XInternAtom(dpy, "Device Node", False); + Atom device_node = ui::X11AtomCache::GetInstance()->GetAtom("Device Node"); if (device_node == None) return base::FilePath(); @@ -409,9 +400,7 @@ } // namespace -X11HotplugEventHandler::X11HotplugEventHandler() - : atom_cache_(gfx::GetXDisplay(), kCachedAtomList) { -} +X11HotplugEventHandler::X11HotplugEventHandler() {} X11HotplugEventHandler::~X11HotplugEventHandler() { } @@ -434,13 +423,13 @@ continue; Atom type = device_list_xi[i].type; - if (type == atom_cache_.GetAtom(XI_KEYBOARD)) + if (type == GetAtom(XI_KEYBOARD)) device_types[id] = DEVICE_TYPE_KEYBOARD; - else if (type == atom_cache_.GetAtom(XI_MOUSE)) + else if (type == GetAtom(XI_MOUSE)) device_types[id] = DEVICE_TYPE_MOUSE; - else if (type == atom_cache_.GetAtom(XI_TOUCHPAD)) + else if (type == GetAtom(XI_TOUCHPAD)) device_types[id] = DEVICE_TYPE_TOUCHPAD; - else if (type == atom_cache_.GetAtom(XI_TOUCHSCREEN)) + else if (type == GetAtom(XI_TOUCHSCREEN)) device_types[id] = DEVICE_TYPE_TOUCHSCREEN; } @@ -465,9 +454,8 @@ uint16_t vendor = 0; uint16_t product = 0; if (XIGetProperty(gfx::GetXDisplay(), device.deviceid, - atom_cache_.GetAtom(XI_PROP_PRODUCT_ID), 0, 2, 0, - XA_INTEGER, &type, &format_return, &num_items_return, - &bytes_after_return, + GetAtom(XI_PROP_PRODUCT_ID), 0, 2, 0, XA_INTEGER, &type, + &format_return, &num_items_return, &bytes_after_return, reinterpret_cast<unsigned char**>(&product_info)) == 0 && product_info) { if (num_items_return == 2) { @@ -483,8 +471,8 @@ // X11 is not thread safe, so first get all the required state. DisplayState display_state; - display_state.mt_position_x = atom_cache_.GetAtom("Abs MT Position X"); - display_state.mt_position_y = atom_cache_.GetAtom("Abs MT Position Y"); + display_state.mt_position_x = GetAtom("Abs MT Position X"); + display_state.mt_position_y = GetAtom("Abs MT Position Y"); UiCallbacks callbacks; callbacks.keyboard_callback = base::Bind(&OnKeyboardDevices);
diff --git a/ui/events/platform/x11/x11_hotplug_event_handler.h b/ui/events/platform/x11/x11_hotplug_event_handler.h index cfe2508..e920cd4 100644 --- a/ui/events/platform/x11/x11_hotplug_event_handler.h +++ b/ui/events/platform/x11/x11_hotplug_event_handler.h
@@ -7,7 +7,6 @@ #include "base/macros.h" #include "ui/events/devices/x11/device_list_cache_x11.h" -#include "ui/gfx/x/x11_atom_cache.h" namespace ui { @@ -22,8 +21,6 @@ void OnHotplugEvent(); private: - X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(X11HotplugEventHandler); };
diff --git a/ui/gfx/icc_profile_x11.cc b/ui/gfx/icc_profile_x11.cc index e37e23a..b2d7ca1 100644 --- a/ui/gfx/icc_profile_x11.cc +++ b/ui/gfx/icc_profile_x11.cc
@@ -12,6 +12,7 @@ #include "base/command_line.h" #include "ui/gfx/icc_profile.h" #include "ui/gfx/switches.h" +#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" namespace gfx { @@ -24,7 +25,7 @@ ICCProfile icc_profile; if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kHeadless)) return icc_profile; - Atom property = XInternAtom(GetXDisplay(), "_ICC_PROFILE", true); + Atom property = ui::X11AtomCache::GetInstance()->GetAtom("_ICC_PROFILE"); if (property != None) { Atom prop_type = None; int prop_format = 0;
diff --git a/ui/gfx/x/x11_atom_cache.cc b/ui/gfx/x/x11_atom_cache.cc index 0d17934..a5ce809 100644 --- a/ui/gfx/x/x11_atom_cache.cc +++ b/ui/gfx/x/x11_atom_cache.cc
@@ -10,25 +10,171 @@ #include <memory> #include "base/logging.h" +#include "base/memory/singleton.h" + +namespace { + +const char* kAtomsToCache[] = {"Abs Dbl End Timestamp", + "Abs Dbl Fling X Velocity", + "Abs Dbl Fling Y Velocity", + "Abs Dbl Metrics Data 1", + "Abs Dbl Metrics Data 2", + "Abs Dbl Ordinal X", + "Abs Dbl Ordinal Y", + "Abs Dbl Start Timestamp", + "Abs Finger Count", + "Abs Fling State", + "Abs Metrics Type", + "Abs MT Orientation", + "Abs MT Position X", + "Abs MT Position Y", + "Abs MT Pressure", + "Abs MT Touch Major", + "Abs MT Touch Minor", + "Abs MT Tracking ID", + "application/octet-stream", + "application/vnd.chromium.test", + "ATOM", + "ATOM_PAIR", + "CARDINAL", + "CHECK", + "_CHROME_DISPLAY_INTERNAL", + "_CHROME_DISPLAY_ROTATION", + "_CHROME_DISPLAY_SCALE_FACTOR", + "CHOME_SELECTION", + "CHROME_SELECTION", + "_CHROMIUM_DRAG_RECEIVER", + "chromium/filename", + "CHROMIUM_TIMESTAMP", + "chromium/x-bookmark-entries", + "chromium/x-browser-actions", + "chromium/x-file-system-files", + "chromium/x-pepper-custom-data", + "chromium/x-renderer-taint", + "chromium/x-web-custom-data", + "chromium/x-webkit-paste", + "CLIPBOARD", + "CLIPBOARD_MANAGER", + "Content Protection", + "Desired", + "Device Node", + "Device Product ID", + "EDID", + "Enabled", + "FAKE_SELECTION", + "Full aspect", + "_GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED", + "_ICC_PROFILE", + "image/png", + "INCR", + "KEYBOARD", + "LOCK", + "marker_event", + "_MOTIF_WM_HINTS", + "MOUSE", + "MULTIPLE", + "_NET_ACTIVE_WINDOW", + "_NET_CLIENT_LIST_STACKING", + "_NET_CURRENT_DESKTOP", + "_NET_FRAME_EXTENTS", + "_NETSCAPE_URL", + "_NET_SUPPORTED", + "_NET_SUPPORTING_WM_CHECK", + "_NET_WM_CM_S0", + "_NET_WM_DESKTOP", + "_NET_WM_ICON", + "_NET_WM_MOVERESIZE", + "_NET_WM_NAME", + "_NET_WM_PID", + "_NET_WM_PING", + "_NET_WM_STATE", + "_NET_WM_STATE_ABOVE", + "_NET_WM_STATE_FOCUSED", + "_NET_WM_STATE_FULLSCREEN", + "_NET_WM_STATE_HIDDEN", + "_NET_WM_STATE_MAXIMIZED_HORZ", + "_NET_WM_STATE_MAXIMIZED_VERT", + "_NET_WM_STATE_SKIP_TASKBAR", + "_NET_WM_STATE_STICKY", + "_NET_WM_USER_TIME", + "_NET_WM_WINDOW_OPACITY", + "_NET_WM_WINDOW_TYPE", + "_NET_WM_WINDOW_TYPE_DND", + "_NET_WM_WINDOW_TYPE_MENU", + "_NET_WM_WINDOW_TYPE_NORMAL", + "_NET_WM_WINDOW_TYPE_NOTIFICATION", + "_NET_WM_WINDOW_TYPE_TOOLTIP", + "_NET_WORKAREA", + "Rel Horiz Wheel", + "Rel Vert Wheel", + "SAVE_TARGETS", + "_SCREENSAVER_STATUS", + "_SCREENSAVER_VERSION", + "scaling mode", + "SELECTION_STRING", + "STRING", + "Tap Paused", + "TARGETS", + "TARGET1", + "TARGET2", + "TEXT", + "text/html", + "text/plain", + "text/plain;charset=utf-8", + "text/uri-list", + "text/rtf", + "text/x-moz-url", + "TIMESTAMP", + "TOUCHPAD", + "TOUCHSCREEN", + "Touch Timestamp", + "Undesired", + "UTF8_STRING", + "WM_CLASS", + "WM_DELETE_WINDOW", + "WM_PROTOCOLS", + "WM_WINDOW_ROLE", + "XdndActionAsk", + "XdndActionCopy", + "XdndActionDirectSave", + "XdndActionLink", + "XdndActionList", + "XdndActionMove", + "XdndActionPrivate", + "XdndAware", + "XdndDirectSave0", + "XdndDrop", + "XdndEnter", + "XdndFinished", + "XdndLeave", + "XdndPosition", + "XdndProxy", + "XdndSelection", + "XdndStatus", + "XdndTypeList", + nullptr}; + +} // namespace namespace ui { -X11AtomCache::X11AtomCache(XDisplay* xdisplay, const char* const* to_cache) - : xdisplay_(xdisplay), - uncached_atoms_allowed_(false) { +X11AtomCache* X11AtomCache::GetInstance() { + return base::Singleton<X11AtomCache>::get(); +} + +X11AtomCache::X11AtomCache() : xdisplay_(gfx::GetXDisplay()) { int cache_count = 0; - for (const char* const* i = to_cache; *i; ++i) + for (const char* const* i = kAtomsToCache; *i; ++i) ++cache_count; std::unique_ptr<XAtom[]> cached_atoms(new XAtom[cache_count]); // Grab all the atoms we need now to minimize roundtrips to the X11 server. - XInternAtoms(xdisplay_, - const_cast<char**>(to_cache), cache_count, False, + XInternAtoms(xdisplay_, const_cast<char**>(kAtomsToCache), cache_count, False, cached_atoms.get()); for (int i = 0; i < cache_count; ++i) - cached_atoms_.insert(std::make_pair(to_cache[i], cached_atoms[i])); + cached_atoms_.insert(std::make_pair(kAtomsToCache[i], cached_atoms[i])); } X11AtomCache::~X11AtomCache() {} @@ -36,13 +182,12 @@ XAtom X11AtomCache::GetAtom(const char* name) const { std::map<std::string, Atom>::const_iterator it = cached_atoms_.find(name); - if (uncached_atoms_allowed_ && it == cached_atoms_.end()) { + if (it == cached_atoms_.end()) { XAtom atom = XInternAtom(xdisplay_, name, false); cached_atoms_.insert(std::make_pair(name, atom)); return atom; } - CHECK(it != cached_atoms_.end()) << " Atom " << name << " not found"; return it->second; }
diff --git a/ui/gfx/x/x11_atom_cache.h b/ui/gfx/x/x11_atom_cache.h index fd0b637..91e68786 100644 --- a/ui/gfx/x/x11_atom_cache.h +++ b/ui/gfx/x/x11_atom_cache.h
@@ -12,6 +12,11 @@ #include "ui/gfx/gfx_export.h" #include "ui/gfx/x/x11_types.h" +namespace base { +template <typename T> +struct DefaultSingletonTraits; +} + namespace ui { // Pre-caches all Atoms on first use to minimize roundtrips to the X11 @@ -20,21 +25,18 @@ // with allow_uncached_atoms(). class GFX_EXPORT X11AtomCache { public: - // Preinterns the NULL terminated list of string |to_cache| on |xdisplay|. - X11AtomCache(XDisplay* xdisplay, const char* const* to_cache); - ~X11AtomCache(); + static X11AtomCache* GetInstance(); // Returns the pre-interned Atom without having to go to the x server. XAtom GetAtom(const char*) const; - // When an Atom isn't in the list of items we've cached, we should look it - // up, cache it locally, and then return the result. - void allow_uncached_atoms() { uncached_atoms_allowed_ = true; } - private: - XDisplay* xdisplay_; + friend struct base::DefaultSingletonTraits<X11AtomCache>; - bool uncached_atoms_allowed_; + X11AtomCache(); + ~X11AtomCache(); + + XDisplay* xdisplay_; mutable std::map<std::string, XAtom> cached_atoms_;
diff --git a/ui/platform_window/stub/stub_window.cc b/ui/platform_window/stub/stub_window.cc index 7e28c11..e646ca4 100644 --- a/ui/platform_window/stub/stub_window.cc +++ b/ui/platform_window/stub/stub_window.cc
@@ -34,8 +34,9 @@ void StubWindow::PrepareForShutdown() {} void StubWindow::SetBounds(const gfx::Rect& bounds) { - if (bounds_ == bounds) - return; + // Even if the pixel bounds didn't change this call to the delegate should + // still happen. The device scale factor may have changed which effectively + // changes the bounds. bounds_ = bounds; delegate_->OnBoundsChanged(bounds); }
diff --git a/ui/platform_window/x11/x11_window_base.cc b/ui/platform_window/x11/x11_window_base.cc index f6415e8e..61d555d 100644 --- a/ui/platform_window/x11/x11_window_base.cc +++ b/ui/platform_window/x11/x11_window_base.cc
@@ -13,6 +13,7 @@ #include "base/strings/utf_string_conversions.h" #include "ui/base/platform_window_defaults.h" +#include "ui/base/x/x11_util.h" #include "ui/base/x/x11_window_event_manager.h" #include "ui/events/devices/x11/touch_factory_x11.h" #include "ui/events/event.h" @@ -27,10 +28,6 @@ namespace { -const char* kAtomsToCache[] = {"UTF8_STRING", "WM_DELETE_WINDOW", - "_NET_WM_NAME", "_NET_WM_PID", - "_NET_WM_PING", NULL}; - XID FindXEventTarget(const XEvent& xev) { XID target = xev.xany.window; if (xev.type == GenericEvent) @@ -46,7 +43,6 @@ xdisplay_(gfx::GetXDisplay()), xwindow_(None), xroot_window_(DefaultRootWindow(xdisplay_)), - atom_cache_(xdisplay_, kAtomsToCache), bounds_(bounds) { DCHECK(delegate_); TouchFactory::SetTouchDeviceListFromCommandLine(); @@ -117,8 +113,8 @@ XFlush(xdisplay_); ::Atom protocols[2]; - protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); - protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); + protocols[0] = GetAtom("WM_DELETE_WINDOW"); + protocols[1] = GetAtom("_NET_WM_PING"); XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with @@ -131,9 +127,8 @@ static_assert(sizeof(long) >= sizeof(pid_t), "pid_t should not be larger than long"); long pid = getpid(); - XChangeProperty(xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_PID"), - XA_CARDINAL, 32, PropModeReplace, - reinterpret_cast<unsigned char*>(&pid), 1); + XChangeProperty(xdisplay_, xwindow_, GetAtom("_NET_WM_PID"), XA_CARDINAL, 32, + PropModeReplace, reinterpret_cast<unsigned char*>(&pid), 1); // Before we map the window, set size hints. Otherwise, some window managers // will ignore toplevel XMoveWindow commands. XSizeHints size_hints; @@ -219,8 +214,8 @@ return; window_title_ = title; std::string utf8str = base::UTF16ToUTF8(title); - XChangeProperty(xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_NAME"), - atom_cache_.GetAtom("UTF8_STRING"), 8, PropModeReplace, + XChangeProperty(xdisplay_, xwindow_, GetAtom("_NET_WM_NAME"), + GetAtom("UTF8_STRING"), 8, PropModeReplace, reinterpret_cast<const unsigned char*>(utf8str.c_str()), utf8str.size()); XTextProperty xtp; @@ -298,9 +293,9 @@ case ClientMessage: { Atom message = static_cast<Atom>(xev->xclient.data.l[0]); - if (message == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { + if (message == GetAtom("WM_DELETE_WINDOW")) { delegate_->OnCloseRequest(); - } else if (message == atom_cache_.GetAtom("_NET_WM_PING")) { + } else if (message == GetAtom("_NET_WM_PING")) { XEvent reply_event = *xev; reply_event.xclient.window = xroot_window_;
diff --git a/ui/platform_window/x11/x11_window_base.h b/ui/platform_window/x11/x11_window_base.h index b944d29..6f37c05fb 100644 --- a/ui/platform_window/x11/x11_window_base.h +++ b/ui/platform_window/x11/x11_window_base.h
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/macros.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/platform_window/platform_window.h" #include "ui/platform_window/platform_window_delegate.h" @@ -66,7 +65,6 @@ XDisplay* xdisplay_; XID xwindow_; XID xroot_window_; - X11AtomCache atom_cache_; std::unique_ptr<ui::XScopedEventSelector> xwindow_events_; base::string16 window_title_;
diff --git a/ui/views/test/ui_controls_factory_desktop_aurax11.cc b/ui/views/test/ui_controls_factory_desktop_aurax11.cc index 117a268..c43e67b5 100644 --- a/ui/views/test/ui_controls_factory_desktop_aurax11.cc +++ b/ui/views/test/ui_controls_factory_desktop_aurax11.cc
@@ -45,7 +45,7 @@ // Returns atom that indidates that the XEvent is marker event. Atom MarkerEventAtom() { - return XInternAtom(gfx::GetXDisplay(), "marker_event", False); + return ui::GetAtom("marker_event"); } // Returns true when the event is a marker event.
diff --git a/ui/views/test/x11_property_change_waiter.cc b/ui/views/test/x11_property_change_waiter.cc index c3adc55..b9937b3 100644 --- a/ui/views/test/x11_property_change_waiter.cc +++ b/ui/views/test/x11_property_change_waiter.cc
@@ -7,27 +7,22 @@ #include <X11/Xlib.h> #include "base/run_loop.h" +#include "ui/base/x/x11_util.h" #include "ui/base/x/x11_window_event_manager.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/gfx/x/x11_atom_cache.h" namespace views { X11PropertyChangeWaiter::X11PropertyChangeWaiter(XID window, const char* property) : x_window_(window), property_(property), wait_(true) { - Display* display = gfx::GetXDisplay(); - // Ensure that we are listening to PropertyNotify events for |window|. This // is not the case for windows which were not created by // DesktopWindowTreeHostX11. x_window_events_.reset( new ui::XScopedEventSelector(x_window_, PropertyChangeMask)); - const char* kAtomsToCache[] = { property, NULL }; - atom_cache_.reset(new ui::X11AtomCache(display, kAtomsToCache)); - // Override the dispatcher so that we get events before // DesktopWindowTreeHostX11 does. We must do this because // DesktopWindowTreeHostX11 stops propagation. @@ -61,10 +56,9 @@ uint32_t X11PropertyChangeWaiter::DispatchEvent( const ui::PlatformEvent& event) { - if (!wait_ || - event->type != PropertyNotify || + if (!wait_ || event->type != PropertyNotify || event->xproperty.window != x_window_ || - event->xproperty.atom != atom_cache_->GetAtom(property_) || + event->xproperty.atom != ui::GetAtom(property_) || ShouldKeepOnWaiting(event)) { return ui::POST_DISPATCH_PERFORM_DEFAULT; }
diff --git a/ui/views/test/x11_property_change_waiter.h b/ui/views/test/x11_property_change_waiter.h index c70ab603..e0bbee5 100644 --- a/ui/views/test/x11_property_change_waiter.h +++ b/ui/views/test/x11_property_change_waiter.h
@@ -17,7 +17,6 @@ namespace ui { class ScopedEventDispatcher; -class X11AtomCache; class XScopedEventSelector; } @@ -58,8 +57,6 @@ std::unique_ptr<ui::ScopedEventDispatcher> dispatcher_; - std::unique_ptr<ui::X11AtomCache> atom_cache_; - DISALLOW_COPY_AND_ASSIGN(X11PropertyChangeWaiter); };
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc index 3b288de..175ae23 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc
@@ -75,14 +75,6 @@ const char kXdndActionMove[] = "XdndActionMove"; const char kXdndActionLink[] = "XdndActionLink"; -// "The target will do something that the source would not understand." The -// source only needs to provide a copy of the dragged data. -const char kXdndActionPrivate[] = "XdndActionPrivate"; - -// The target should ask the user what action it wants to perform. Intended to -// match Windows' right-click drag and drop, which shows a dropdown. -const char kXdndActionAsk[] = "XdndActionAsk"; - // Triggers the XDS protocol. const char kXdndActionDirectSave[] = "XdndActionDirectSave"; @@ -155,30 +147,6 @@ // action will be taken if the drop is accepted. const char kXdndStatus[] = "XdndStatus"; -const char* kAtomsToCache[] = { - kChromiumDragReciever, - kXdndActionAsk, - kXdndActionCopy, - kXdndActionDirectSave, - kXdndActionLink, - kXdndActionList, - kXdndActionMove, - kXdndActionPrivate, - kXdndAware, - kXdndDirectSave0, - kXdndDrop, - kXdndEnter, - kXdndFinished, - kXdndLeave, - kXdndPosition, - kXdndProxy, - kXdndSelection, - kXdndStatus, - kXdndTypeList, - ui::Clipboard::kMimeTypeText, - NULL -}; - int XGetModifiers() { XDisplay* display = gfx::GetXDisplay(); @@ -242,9 +210,7 @@ class DesktopDragDropClientAuraX11::X11DragContext : public ui::PlatformEventDispatcher { public: - X11DragContext(ui::X11AtomCache* atom_cache, - ::Window local_window, - const XClientMessageEvent& event); + X11DragContext(::Window local_window, const XClientMessageEvent& event); ~X11DragContext() override; // When we receive an XdndPosition message, we need to have all the data @@ -287,9 +253,6 @@ bool CanDispatchEvent(const ui::PlatformEvent& event) override; uint32_t DispatchEvent(const ui::PlatformEvent& event) override; - // The atom cache owned by our parent. - ui::X11AtomCache* atom_cache_; - // The XID of our chrome local aura window handling our events. ::Window local_window_; @@ -336,11 +299,9 @@ }; DesktopDragDropClientAuraX11::X11DragContext::X11DragContext( - ui::X11AtomCache* atom_cache, ::Window local_window, const XClientMessageEvent& event) - : atom_cache_(atom_cache), - local_window_(local_window), + : local_window_(local_window), source_window_(event.data.l[0]), source_client_( DesktopDragDropClientAuraX11::GetForWindow(source_window_)), @@ -430,11 +391,8 @@ ::Atom target = unfetched_targets_.back(); unfetched_targets_.pop_back(); - XConvertSelection(gfx::GetXDisplay(), - atom_cache_->GetAtom(kXdndSelection), - target, - atom_cache_->GetAtom(kChromiumDragReciever), - local_window_, + XConvertSelection(gfx::GetXDisplay(), ui::GetAtom(kXdndSelection), target, + ui::GetAtom(kChromiumDragReciever), local_window_, position_time_stamp_); } @@ -450,7 +408,7 @@ DVLOG(1) << "SelectionNotify, format " << event.target; if (event.property != None) { - DCHECK_EQ(event.property, atom_cache_->GetAtom(kChromiumDragReciever)); + DCHECK_EQ(event.property, ui::GetAtom(kChromiumDragReciever)); scoped_refptr<base::RefCountedMemory> data; ::Atom type = None; @@ -508,11 +466,11 @@ void DesktopDragDropClientAuraX11::X11DragContext::MaskOperation( ::Atom xdnd_operation, int* drag_operation) const { - if (xdnd_operation == atom_cache_->GetAtom(kXdndActionCopy)) + if (xdnd_operation == ui::GetAtom(kXdndActionCopy)) *drag_operation |= ui::DragDropTypes::DRAG_COPY; - else if (xdnd_operation == atom_cache_->GetAtom(kXdndActionMove)) + else if (xdnd_operation == ui::GetAtom(kXdndActionMove)) *drag_operation |= ui::DragDropTypes::DRAG_MOVE; - else if (xdnd_operation == atom_cache_->GetAtom(kXdndActionLink)) + else if (xdnd_operation == ui::GetAtom(kXdndActionLink)) *drag_operation |= ui::DragDropTypes::DRAG_LINK; } @@ -524,7 +482,7 @@ uint32_t DesktopDragDropClientAuraX11::X11DragContext::DispatchEvent( const ui::PlatformEvent& event) { if (event->type == PropertyNotify && - event->xproperty.atom == atom_cache_->GetAtom(kXdndActionList)) { + event->xproperty.atom == ui::GetAtom(kXdndActionList)) { ReadActions(); return ui::POST_DISPATCH_STOP_PROPAGATION; } @@ -542,7 +500,6 @@ cursor_manager_(cursor_manager), xdisplay_(xdisplay), xwindow_(xwindow), - atom_cache_(xdisplay_, kAtomsToCache), current_modifier_state_(ui::EF_NONE), target_window_(NULL), waiting_on_status_(false), @@ -559,8 +516,8 @@ // Mark that we are aware of drag and drop concepts. unsigned long xdnd_version = kMaxXdndVersion; - XChangeProperty(xdisplay_, xwindow_, atom_cache_.GetAtom(kXdndAware), - XA_ATOM, 32, PropModeReplace, + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom(kXdndAware), XA_ATOM, 32, + PropModeReplace, reinterpret_cast<unsigned char*>(&xdnd_version), 1); } @@ -609,8 +566,7 @@ // Make sure that we've run ~X11DragContext() before creating another one. target_current_context_.reset(); - target_current_context_.reset( - new X11DragContext(&atom_cache_, xwindow_, event)); + target_current_context_.reset(new X11DragContext(xwindow_, event)); // In the Windows implementation, we immediately call DesktopDropTargetWin:: // Translate(). The XDND specification demands that we wait until we receive @@ -770,7 +726,7 @@ XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndFinished); + xev.xclient.message_type = ui::GetAtom(kXdndFinished); xev.xclient.format = 32; xev.xclient.window = source_window; xev.xclient.data.l[0] = xwindow_; @@ -819,11 +775,10 @@ std::vector<::Atom> actions = GetOfferedDragOperations(); if (!source_provider_->file_contents_name().empty()) { - actions.push_back(atom_cache_.GetAtom(kXdndActionDirectSave)); + actions.push_back(ui::GetAtom(kXdndActionDirectSave)); ui::SetStringProperty( - xwindow_, - atom_cache_.GetAtom(kXdndDirectSave0), - atom_cache_.GetAtom(ui::Clipboard::kMimeTypeText), + xwindow_, ui::GetAtom(kXdndDirectSave0), + ui::GetAtom(ui::Clipboard::kMimeTypeText), source_provider_->file_contents_name().AsUTF8Unsafe()); } ui::SetAtomArrayProperty(xwindow_, kXdndActionList, "ATOM", actions); @@ -865,8 +820,8 @@ source_provider_ = NULL; g_current_drag_drop_client = NULL; drag_operation_ = 0; - XDeleteProperty(xdisplay_, xwindow_, atom_cache_.GetAtom(kXdndActionList)); - XDeleteProperty(xdisplay_, xwindow_, atom_cache_.GetAtom(kXdndDirectSave0)); + XDeleteProperty(xdisplay_, xwindow_, ui::GetAtom(kXdndActionList)); + XDeleteProperty(xdisplay_, xwindow_, ui::GetAtom(kXdndDirectSave0)); return negotiated_operation_; } @@ -1007,22 +962,22 @@ DesktopDragDropClientAuraX11* short_circuit = GetForWindow(xid); if (short_circuit) { Atom message_type = xev->xclient.message_type; - if (message_type == atom_cache_.GetAtom(kXdndEnter)) { + if (message_type == ui::GetAtom(kXdndEnter)) { short_circuit->OnXdndEnter(xev->xclient); return; - } else if (message_type == atom_cache_.GetAtom(kXdndLeave)) { + } else if (message_type == ui::GetAtom(kXdndLeave)) { short_circuit->OnXdndLeave(xev->xclient); return; - } else if (message_type == atom_cache_.GetAtom(kXdndPosition)) { + } else if (message_type == ui::GetAtom(kXdndPosition)) { short_circuit->OnXdndPosition(xev->xclient); return; - } else if (message_type == atom_cache_.GetAtom(kXdndStatus)) { + } else if (message_type == ui::GetAtom(kXdndStatus)) { short_circuit->OnXdndStatus(xev->xclient); return; - } else if (message_type == atom_cache_.GetAtom(kXdndFinished)) { + } else if (message_type == ui::GetAtom(kXdndFinished)) { short_circuit->OnXdndFinished(xev->xclient); return; - } else if (message_type == atom_cache_.GetAtom(kXdndDrop)) { + } else if (message_type == ui::GetAtom(kXdndDrop)) { short_circuit->OnXdndDrop(xev->xclient); return; } @@ -1160,22 +1115,22 @@ ::Atom DesktopDragDropClientAuraX11::DragOperationToAtom( int drag_operation) { if (drag_operation & ui::DragDropTypes::DRAG_COPY) - return atom_cache_.GetAtom(kXdndActionCopy); + return ui::GetAtom(kXdndActionCopy); if (drag_operation & ui::DragDropTypes::DRAG_MOVE) - return atom_cache_.GetAtom(kXdndActionMove); + return ui::GetAtom(kXdndActionMove); if (drag_operation & ui::DragDropTypes::DRAG_LINK) - return atom_cache_.GetAtom(kXdndActionLink); + return ui::GetAtom(kXdndActionLink); return None; } ui::DragDropTypes::DragOperation DesktopDragDropClientAuraX11::AtomToDragOperation(::Atom atom) { - if (atom == atom_cache_.GetAtom(kXdndActionCopy)) + if (atom == ui::GetAtom(kXdndActionCopy)) return ui::DragDropTypes::DRAG_COPY; - if (atom == atom_cache_.GetAtom(kXdndActionMove)) + if (atom == ui::GetAtom(kXdndActionMove)) return ui::DragDropTypes::DRAG_MOVE; - if (atom == atom_cache_.GetAtom(kXdndActionLink)) + if (atom == ui::GetAtom(kXdndActionLink)) return ui::DragDropTypes::DRAG_LINK; return ui::DragDropTypes::DRAG_NONE; @@ -1184,11 +1139,11 @@ std::vector<::Atom> DesktopDragDropClientAuraX11::GetOfferedDragOperations() { std::vector<::Atom> operations; if (drag_operation_ & ui::DragDropTypes::DRAG_COPY) - operations.push_back(atom_cache_.GetAtom(kXdndActionCopy)); + operations.push_back(ui::GetAtom(kXdndActionCopy)); if (drag_operation_ & ui::DragDropTypes::DRAG_MOVE) - operations.push_back(atom_cache_.GetAtom(kXdndActionMove)); + operations.push_back(ui::GetAtom(kXdndActionMove)); if (drag_operation_ & ui::DragDropTypes::DRAG_LINK) - operations.push_back(atom_cache_.GetAtom(kXdndActionLink)); + operations.push_back(ui::GetAtom(kXdndActionLink)); return operations; } @@ -1216,7 +1171,7 @@ // sets this nor respects it if set. XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndStatus); + xev.xclient.message_type = ui::GetAtom(kXdndStatus); xev.xclient.format = 32; xev.xclient.window = source_window; xev.xclient.data.l[0] = xwindow_; @@ -1232,7 +1187,7 @@ void DesktopDragDropClientAuraX11::SendXdndEnter(::Window dest_window) { XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndEnter); + xev.xclient.message_type = ui::GetAtom(kXdndEnter); xev.xclient.format = 32; xev.xclient.window = dest_window; xev.xclient.data.l[0] = xwindow_; @@ -1259,7 +1214,7 @@ void DesktopDragDropClientAuraX11::SendXdndLeave(::Window dest_window) { XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndLeave); + xev.xclient.message_type = ui::GetAtom(kXdndLeave); xev.xclient.format = 32; xev.xclient.window = dest_window; xev.xclient.data.l[0] = xwindow_; @@ -1278,7 +1233,7 @@ XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndPosition); + xev.xclient.message_type = ui::GetAtom(kXdndPosition); xev.xclient.format = 32; xev.xclient.window = dest_window; xev.xclient.data.l[0] = xwindow_; @@ -1303,7 +1258,7 @@ void DesktopDragDropClientAuraX11::SendXdndDrop(::Window dest_window) { XEvent xev; xev.xclient.type = ClientMessage; - xev.xclient.message_type = atom_cache_.GetAtom(kXdndDrop); + xev.xclient.message_type = ui::GetAtom(kXdndDrop); xev.xclient.format = 32; xev.xclient.window = dest_window; xev.xclient.data.l[0] = xwindow_;
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h index 6d3f3121..b8792c2 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h
@@ -21,7 +21,6 @@ #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/x11_move_loop_delegate.h" @@ -212,8 +211,6 @@ Display* xdisplay_; ::Window xwindow_; - ui::X11AtomCache atom_cache_; - // Target side information. class X11DragContext; std::unique_ptr<X11DragContext> target_current_context_;
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc index 21cd3ff..862d806 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc
@@ -24,7 +24,6 @@ #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/base/x/x11_util.h" #include "ui/events/event_utils.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h" #include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h" @@ -38,18 +37,6 @@ namespace { -const char* kAtomsToCache[] = { - "XdndActionCopy", - "XdndDrop", - "XdndEnter", - "XdndFinished", - "XdndLeave", - "XdndPosition", - "XdndStatus", - "XdndTypeList", - NULL -}; - class TestDragDropClient; // Collects messages which would otherwise be sent to |xid_| via @@ -195,8 +182,6 @@ // for that window. std::map< ::Window, ClientMessageEventCollector*> collectors_; - ui::X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(TestDragDropClient); }; @@ -310,20 +295,18 @@ aura::Window* window, DesktopNativeCursorManager* cursor_manager) : SimpleTestDragDropClient(window, cursor_manager), - source_xid_(window->GetHost()->GetAcceleratedWidget()), - atom_cache_(gfx::GetXDisplay(), kAtomsToCache) { -} + source_xid_(window->GetHost()->GetAcceleratedWidget()) {} TestDragDropClient::~TestDragDropClient() { } Atom TestDragDropClient::GetAtom(const char* name) { - return atom_cache_.GetAtom(name); + return ui::GetAtom(name); } bool TestDragDropClient::MessageHasType(const XClientMessageEvent& event, const char* type) { - return event.message_type == atom_cache_.GetAtom(type); + return event.message_type == GetAtom(type); } void TestDragDropClient::SetEventCollectorFor( @@ -339,7 +322,7 @@ bool will_accept_drop, ::Atom accepted_action) { XClientMessageEvent event; - event.message_type = atom_cache_.GetAtom("XdndStatus"); + event.message_type = GetAtom("XdndStatus"); event.format = 32; event.window = source_xid_; event.data.l[0] = target_window; @@ -354,7 +337,7 @@ bool accepted_drop, ::Atom performed_action) { XClientMessageEvent event; - event.message_type = atom_cache_.GetAtom("XdndFinished"); + event.message_type = GetAtom("XdndFinished"); event.format = 32; event.window = source_xid_; event.data.l[0] = target_window;
diff --git a/ui/views/widget/desktop_aura/desktop_screen_x11.cc b/ui/views/widget/desktop_aura/desktop_screen_x11.cc index 3432afe4..17145e38 100644 --- a/ui/views/widget/desktop_aura/desktop_screen_x11.cc +++ b/ui/views/widget/desktop_aura/desktop_screen_x11.cc
@@ -35,11 +35,6 @@ namespace { -const char* const kAtomsToCache[] = { - "_NET_WORKAREA", - nullptr -}; - // The delay to perform configuration after RRNotify. See the comment // in |Dispatch()|. const int64_t kConfigureDelayMs = 500; @@ -94,8 +89,7 @@ x_root_window_(DefaultRootWindow(xdisplay_)), has_xrandr_(false), xrandr_event_base_(0), - primary_display_index_(0), - atom_cache_(xdisplay_, kAtomsToCache) { + primary_display_index_(0) { // We only support 1.3+. There were library changes before this and we should // use the new interface instead of the 1.2 one. int randr_version_major = 0; @@ -241,7 +235,7 @@ event->type - xrandr_event_base_ == RRNotify || (event->type == PropertyNotify && event->xproperty.window == x_root_window_ && - event->xproperty.atom == atom_cache_.GetAtom("_NET_WORKAREA")); + event->xproperty.atom == ui::GetAtom("_NET_WORKAREA")); } uint32_t DesktopScreenX11::DispatchEvent(const ui::PlatformEvent& event) { @@ -250,7 +244,7 @@ XRRUpdateConfiguration(event); } else if (event->type - xrandr_event_base_ == RRNotify || (event->type == PropertyNotify && - event->xproperty.atom == atom_cache_.GetAtom("_NET_WORKAREA"))) { + event->xproperty.atom == ui::GetAtom("_NET_WORKAREA"))) { // There's some sort of observer dispatch going on here, but I don't think // it's the screen's? if (configure_timer_.get() && configure_timer_->IsRunning()) { @@ -287,8 +281,7 @@ has_xrandr_(false), xrandr_event_base_(0), displays_(test_displays), - primary_display_index_(0), - atom_cache_(xdisplay_, kAtomsToCache) {} + primary_display_index_(0) {} std::vector<display::Display> DesktopScreenX11::BuildDisplaysFromXRandRInfo() { std::vector<display::Display> displays;
diff --git a/ui/views/widget/desktop_aura/desktop_screen_x11.h b/ui/views/widget/desktop_aura/desktop_screen_x11.h index 0090f7c..fc71915 100644 --- a/ui/views/widget/desktop_aura/desktop_screen_x11.h +++ b/ui/views/widget/desktop_aura/desktop_screen_x11.h
@@ -14,7 +14,6 @@ #include "ui/display/display_change_notifier.h" #include "ui/display/screen.h" #include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/views/views_export.h" typedef unsigned long XID; @@ -97,8 +96,6 @@ display::DisplayChangeNotifier change_notifier_; - ui::X11AtomCache atom_cache_; - DISALLOW_COPY_AND_ASSIGN(DesktopScreenX11); };
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc index d6d99392..aacca36ce 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc
@@ -88,53 +88,6 @@ // should appear on all desktops. const int kAllDesktops = 0xFFFFFFFF; -const char* kAtomsToCache[] = { - "UTF8_STRING", - "WM_DELETE_WINDOW", - "WM_PROTOCOLS", - "_NET_ACTIVE_WINDOW", - "_NET_FRAME_EXTENTS", - "_NET_WM_CM_S0", - "_NET_WM_DESKTOP", - "_NET_WM_ICON", - "_NET_WM_NAME", - "_NET_WM_PID", - "_NET_WM_PING", - "_NET_WM_STATE", - "_NET_WM_STATE_ABOVE", - "_NET_WM_STATE_FULLSCREEN", - "_NET_WM_STATE_HIDDEN", - "_NET_WM_STATE_MAXIMIZED_HORZ", - "_NET_WM_STATE_MAXIMIZED_VERT", - "_NET_WM_STATE_SKIP_TASKBAR", - "_NET_WM_STATE_STICKY", - "_NET_WM_USER_TIME", - "_NET_WM_WINDOW_OPACITY", - "_NET_WM_WINDOW_TYPE", - "_NET_WM_WINDOW_TYPE_DND", - "_NET_WM_WINDOW_TYPE_MENU", - "_NET_WM_WINDOW_TYPE_NORMAL", - "_NET_WM_WINDOW_TYPE_NOTIFICATION", - "_NET_WM_WINDOW_TYPE_TOOLTIP", - "XdndActionAsk", - "XdndActionCopy", - "XdndActionLink", - "XdndActionList", - "XdndActionMove", - "XdndActionPrivate", - "XdndAware", - "XdndDrop", - "XdndEnter", - "XdndFinished", - "XdndLeave", - "XdndPosition", - "XdndProxy", // Proxy windows? - "XdndSelection", - "XdndStatus", - "XdndTypeList", - NULL -}; - const char kX11WindowRolePopup[] = "popup"; const char kX11WindowRoleBubble[] = "bubble"; @@ -190,7 +143,6 @@ : xdisplay_(gfx::GetXDisplay()), xwindow_(0), x_root_window_(DefaultRootWindow(xdisplay_)), - atom_cache_(xdisplay_, kAtomsToCache), window_mapped_in_server_(false), window_mapped_in_client_(false), is_fullscreen_(false), @@ -779,7 +731,7 @@ // https://code.google.com/p/wmii/issues/detail?id=266 static bool wm_supports_active_window = ui::GuessWindowManager() != ui::WM_WMII && - ui::WmSupportsHint(atom_cache_.GetAtom("_NET_ACTIVE_WINDOW")); + ui::WmSupportsHint(ui::GetAtom("_NET_ACTIVE_WINDOW")); Time timestamp = ui::X11EventSource::GetInstance()->GetTimestamp(); @@ -788,7 +740,7 @@ memset(&xclient, 0, sizeof(xclient)); xclient.type = ClientMessage; xclient.xclient.window = xwindow_; - xclient.xclient.message_type = atom_cache_.GetAtom("_NET_ACTIVE_WINDOW"); + xclient.xclient.message_type = ui::GetAtom("_NET_ACTIVE_WINDOW"); xclient.xclient.format = 32; xclient.xclient.data.l[0] = 1; // Specified we are an app. xclient.xclient.data.l[1] = timestamp; @@ -845,9 +797,7 @@ void DesktopWindowTreeHostX11::Maximize() { if (HasWMSpecProperty("_NET_WM_STATE_FULLSCREEN")) { // Unfullscreen the window if it is fullscreen. - SetWMSpecState(false, - atom_cache_.GetAtom("_NET_WM_STATE_FULLSCREEN"), - None); + SetWMSpecState(false, ui::GetAtom("_NET_WM_STATE_FULLSCREEN"), None); // Resize the window so that it does not have the same size as a monitor. // (Otherwise, some window managers immediately put the window back in @@ -867,9 +817,8 @@ // heuristics that are in the PropertyNotify and ConfigureNotify handlers. restored_bounds_in_pixels_ = bounds_in_pixels_; - SetWMSpecState(true, - atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"), - atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ")); + SetWMSpecState(true, ui::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"), + ui::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ")); if (IsMinimized()) ShowWindowWithState(ui::SHOW_STATE_NORMAL); } @@ -881,9 +830,8 @@ void DesktopWindowTreeHostX11::Restore() { should_maximize_after_map_ = false; - SetWMSpecState(false, - atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"), - atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ")); + SetWMSpecState(false, ui::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"), + ui::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ")); if (IsMinimized()) ShowWindowWithState(ui::SHOW_STATE_NORMAL); } @@ -903,9 +851,7 @@ void DesktopWindowTreeHostX11::SetAlwaysOnTop(bool always_on_top) { is_always_on_top_ = always_on_top; - SetWMSpecState(always_on_top, - atom_cache_.GetAtom("_NET_WM_STATE_ABOVE"), - None); + SetWMSpecState(always_on_top, ui::GetAtom("_NET_WM_STATE_ABOVE"), None); } bool DesktopWindowTreeHostX11::IsAlwaysOnTop() const { @@ -913,9 +859,7 @@ } void DesktopWindowTreeHostX11::SetVisibleOnAllWorkspaces(bool always_visible) { - SetWMSpecState(always_visible, - atom_cache_.GetAtom("_NET_WM_STATE_STICKY"), - None); + SetWMSpecState(always_visible, ui::GetAtom("_NET_WM_STATE_STICKY"), None); int new_desktop = 0; if (always_visible) { @@ -930,7 +874,7 @@ memset (&xevent, 0, sizeof (xevent)); xevent.type = ClientMessage; xevent.xclient.window = xwindow_; - xevent.xclient.message_type = atom_cache_.GetAtom("_NET_WM_DESKTOP"); + xevent.xclient.message_type = ui::GetAtom("_NET_WM_DESKTOP"); xevent.xclient.format = 32; xevent.xclient.data.l[0] = new_desktop; xevent.xclient.data.l[1] = 0; @@ -955,12 +899,8 @@ return false; window_title_ = title; std::string utf8str = base::UTF16ToUTF8(title); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_NAME"), - atom_cache_.GetAtom("UTF8_STRING"), - 8, - PropModeReplace, + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_NAME"), + ui::GetAtom("UTF8_STRING"), 8, PropModeReplace, reinterpret_cast<const unsigned char*>(utf8str.c_str()), utf8str.size()); XTextProperty xtp; @@ -1057,9 +997,7 @@ if (unmaximize_and_remaximize) Restore(); - SetWMSpecState(fullscreen, - atom_cache_.GetAtom("_NET_WM_STATE_FULLSCREEN"), - None); + SetWMSpecState(fullscreen, ui::GetAtom("_NET_WM_STATE_FULLSCREEN"), None); if (unmaximize_and_remaximize) Maximize(); @@ -1104,13 +1042,10 @@ unsigned long cardinality = opacity_8bit * channel_multiplier; if (cardinality == 0xffffffff) { - XDeleteProperty(xdisplay_, xwindow_, - atom_cache_.GetAtom("_NET_WM_WINDOW_OPACITY")); + XDeleteProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_WINDOW_OPACITY")); } else { - XChangeProperty(xdisplay_, xwindow_, - atom_cache_.GetAtom("_NET_WM_WINDOW_OPACITY"), - XA_CARDINAL, 32, - PropModeReplace, + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_WINDOW_OPACITY"), + XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&cardinality), 1); } } @@ -1367,22 +1302,22 @@ switch (params.type) { case Widget::InitParams::TYPE_MENU: swa.override_redirect = True; - window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_MENU"); + window_type = ui::GetAtom("_NET_WM_WINDOW_TYPE_MENU"); break; case Widget::InitParams::TYPE_TOOLTIP: swa.override_redirect = True; - window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_TOOLTIP"); + window_type = ui::GetAtom("_NET_WM_WINDOW_TYPE_TOOLTIP"); break; case Widget::InitParams::TYPE_POPUP: swa.override_redirect = True; - window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_NOTIFICATION"); + window_type = ui::GetAtom("_NET_WM_WINDOW_TYPE_NOTIFICATION"); break; case Widget::InitParams::TYPE_DRAG: swa.override_redirect = True; - window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_DND"); + window_type = ui::GetAtom("_NET_WM_WINDOW_TYPE_DND"); break; default: - window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_NORMAL"); + window_type = ui::GetAtom("_NET_WM_WINDOW_TYPE_NORMAL"); break; } // An in-activatable window should not interact with the system wm. @@ -1451,8 +1386,8 @@ // should listen for activation events and anything else that GTK+ listens // for, and do something useful. ::Atom protocols[2]; - protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); - protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); + protocols[0] = ui::GetAtom("WM_DELETE_WINDOW"); + protocols[1] = ui::GetAtom("_NET_WM_PING"); XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with @@ -1465,20 +1400,12 @@ static_assert(sizeof(long) >= sizeof(pid_t), "pid_t should not be larger than long"); long pid = getpid(); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_PID"), - XA_CARDINAL, - 32, - PropModeReplace, - reinterpret_cast<unsigned char*>(&pid), 1); + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_PID"), XA_CARDINAL, + 32, PropModeReplace, reinterpret_cast<unsigned char*>(&pid), + 1); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE"), - XA_ATOM, - 32, - PropModeReplace, + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_WINDOW_TYPE"), + XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&window_type), 1); // List of window state properties (_NET_WM_STATE) to set, if any. @@ -1488,19 +1415,18 @@ if ((params.type == Widget::InitParams::TYPE_POPUP || params.type == Widget::InitParams::TYPE_BUBBLE) && !params.force_show_in_taskbar) { - state_atom_list.push_back( - atom_cache_.GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); + state_atom_list.push_back(ui::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // If the window should stay on top of other windows, add the // _NET_WM_STATE_ABOVE property. is_always_on_top_ = params.keep_on_top; if (is_always_on_top_) - state_atom_list.push_back(atom_cache_.GetAtom("_NET_WM_STATE_ABOVE")); + state_atom_list.push_back(ui::GetAtom("_NET_WM_STATE_ABOVE")); workspace_.clear(); if (params.visible_on_all_workspaces) { - state_atom_list.push_back(atom_cache_.GetAtom("_NET_WM_STATE_STICKY")); + state_atom_list.push_back(ui::GetAtom("_NET_WM_STATE_STICKY")); ui::SetIntProperty(xwindow_, "_NET_WM_DESKTOP", "CARDINAL", kAllDesktops); } else if (!params.workspace.empty()) { int workspace; @@ -1717,13 +1643,9 @@ type == ui::ET_TOUCH_PRESSED) { unsigned long wm_user_time_ms = static_cast<unsigned long>( (ui::EventTimeFromNative(event) - base::TimeTicks()).InMilliseconds()); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_USER_TIME"), - XA_CARDINAL, - 32, - PropModeReplace, - reinterpret_cast<const unsigned char *>(&wm_user_time_ms), + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_USER_TIME"), + XA_CARDINAL, 32, PropModeReplace, + reinterpret_cast<const unsigned char*>(&wm_user_time_ms), 1); } } @@ -1735,7 +1657,7 @@ memset(&xclient, 0, sizeof(xclient)); xclient.type = ClientMessage; xclient.xclient.window = xwindow_; - xclient.xclient.message_type = atom_cache_.GetAtom("_NET_WM_STATE"); + xclient.xclient.message_type = ui::GetAtom("_NET_WM_STATE"); xclient.xclient.format = 32; xclient.xclient.data.l[0] = enabled ? k_NET_WM_STATE_ADD : k_NET_WM_STATE_REMOVE; @@ -1750,8 +1672,8 @@ } bool DesktopWindowTreeHostX11::HasWMSpecProperty(const char* property) const { - return window_properties_.find(atom_cache_.GetAtom(property)) != - window_properties_.end(); + return window_properties_.find(ui::GetAtom(property)) != + window_properties_.end(); } void DesktopWindowTreeHostX11::SetUseNativeFrame(bool use_native_frame) { @@ -1931,10 +1853,10 @@ ? 0 : ui::X11EventSource::GetInstance()->GetTimestamp(); if (show_state == ui::SHOW_STATE_INACTIVE || wm_user_time_ms != 0) { - XChangeProperty( - xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_USER_TIME"), - XA_CARDINAL, 32, PropModeReplace, - reinterpret_cast<const unsigned char*>(&wm_user_time_ms), 1); + XChangeProperty(xdisplay_, xwindow_, ui::GetAtom("_NET_WM_USER_TIME"), + XA_CARDINAL, 32, PropModeReplace, + reinterpret_cast<const unsigned char*>(&wm_user_time_ms), + 1); } ui::X11EventSource* event_source = ui::X11EventSource::GetInstance(); @@ -2192,12 +2114,12 @@ } case ClientMessage: { Atom message_type = xev->xclient.message_type; - if (message_type == atom_cache_.GetAtom("WM_PROTOCOLS")) { + if (message_type == ui::GetAtom("WM_PROTOCOLS")) { Atom protocol = static_cast<Atom>(xev->xclient.data.l[0]); - if (protocol == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { + if (protocol == ui::GetAtom("WM_DELETE_WINDOW")) { // We have received a close message from the window manager. OnHostCloseRequested(); - } else if (protocol == atom_cache_.GetAtom("_NET_WM_PING")) { + } else if (protocol == ui::GetAtom("_NET_WM_PING")) { XEvent reply_event = *xev; reply_event.xclient.window = x_root_window_; @@ -2207,17 +2129,17 @@ SubstructureRedirectMask | SubstructureNotifyMask, &reply_event); } - } else if (message_type == atom_cache_.GetAtom("XdndEnter")) { + } else if (message_type == ui::GetAtom("XdndEnter")) { drag_drop_client_->OnXdndEnter(xev->xclient); - } else if (message_type == atom_cache_.GetAtom("XdndLeave")) { + } else if (message_type == ui::GetAtom("XdndLeave")) { drag_drop_client_->OnXdndLeave(xev->xclient); - } else if (message_type == atom_cache_.GetAtom("XdndPosition")) { + } else if (message_type == ui::GetAtom("XdndPosition")) { drag_drop_client_->OnXdndPosition(xev->xclient); - } else if (message_type == atom_cache_.GetAtom("XdndStatus")) { + } else if (message_type == ui::GetAtom("XdndStatus")) { drag_drop_client_->OnXdndStatus(xev->xclient); - } else if (message_type == atom_cache_.GetAtom("XdndFinished")) { + } else if (message_type == ui::GetAtom("XdndFinished")) { drag_drop_client_->OnXdndFinished(xev->xclient); - } else if (message_type == atom_cache_.GetAtom("XdndDrop")) { + } else if (message_type == ui::GetAtom("XdndDrop")) { drag_drop_client_->OnXdndDrop(xev->xclient); } break; @@ -2261,11 +2183,11 @@ } case PropertyNotify: { ::Atom changed_atom = xev->xproperty.atom; - if (changed_atom == atom_cache_.GetAtom("_NET_WM_STATE")) { + if (changed_atom == ui::GetAtom("_NET_WM_STATE")) { OnWMStateUpdated(); - } else if (changed_atom == atom_cache_.GetAtom("_NET_FRAME_EXTENTS")) { + } else if (changed_atom == ui::GetAtom("_NET_FRAME_EXTENTS")) { OnFrameExtentsUpdated(); - } else if (changed_atom == atom_cache_.GetAtom("_NET_WM_DESKTOP")) { + } else if (changed_atom == ui::GetAtom("_NET_WM_DESKTOP")) { if (UpdateWorkspace()) OnHostWorkspaceChanged(); }
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h index 757b780..c0e1763 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h
@@ -22,7 +22,6 @@ #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host.h" @@ -289,8 +288,6 @@ // The native root window. ::Window x_root_window_; - ui::X11AtomCache atom_cache_; - // Whether the window is mapped with respect to the X server. bool window_mapped_in_server_;
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc index 7f4ec9c..f071e756 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc
@@ -31,7 +31,6 @@ #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/path.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/x11_property_change_waiter.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" @@ -48,18 +47,10 @@ // Blocks till the window state hint, |hint|, is set or unset. class WMStateWaiter : public X11PropertyChangeWaiter { public: - WMStateWaiter(XID window, - const char* hint, - bool wait_till_set) + WMStateWaiter(XID window, const char* hint, bool wait_till_set) : X11PropertyChangeWaiter(window, "_NET_WM_STATE"), hint_(hint), - wait_till_set_(wait_till_set) { - const char* const kAtomsToCache[] = { - hint, - nullptr - }; - atom_cache_.reset(new ui::X11AtomCache(gfx::GetXDisplay(), kAtomsToCache)); - } + wait_till_set_(wait_till_set) {} ~WMStateWaiter() override {} @@ -68,16 +59,13 @@ bool ShouldKeepOnWaiting(const ui::PlatformEvent& event) override { std::vector<Atom> hints; if (ui::GetAtomArrayProperty(xwindow(), "_NET_WM_STATE", &hints)) { - auto it = std::find(hints.cbegin(), hints.cend(), - atom_cache_->GetAtom(hint_)); + auto it = std::find(hints.cbegin(), hints.cend(), ui::GetAtom(hint_)); bool hint_set = (it != hints.cend()); return hint_set != wait_till_set_; } return true; } - std::unique_ptr<ui::X11AtomCache> atom_cache_; - // The name of the hint to wait to get set or unset. const char* hint_; @@ -346,22 +334,16 @@ // Emulate the window manager exiting fullscreen via a window manager // accelerator key. It should not affect the widget's fullscreen state. { - const char* const kAtomsToCache[] = { - "_NET_WM_STATE", - "_NET_WM_STATE_FULLSCREEN", - nullptr - }; Display* display = gfx::GetXDisplay(); - ui::X11AtomCache atom_cache(display, kAtomsToCache); XEvent xclient; memset(&xclient, 0, sizeof(xclient)); xclient.type = ClientMessage; xclient.xclient.window = xid; - xclient.xclient.message_type = atom_cache.GetAtom("_NET_WM_STATE"); + xclient.xclient.message_type = ui::GetAtom("_NET_WM_STATE"); xclient.xclient.format = 32; xclient.xclient.data.l[0] = 0; - xclient.xclient.data.l[1] = atom_cache.GetAtom("_NET_WM_STATE_FULLSCREEN"); + xclient.xclient.data.l[1] = ui::GetAtom("_NET_WM_STATE_FULLSCREEN"); xclient.xclient.data.l[2] = 0; xclient.xclient.data.l[3] = 1; xclient.xclient.data.l[4] = 0; @@ -397,16 +379,8 @@ // Minimize by sending _NET_WM_STATE_HIDDEN { - const char* const kAtomsToCache[] = { - "_NET_WM_STATE", - "_NET_WM_STATE_HIDDEN", - nullptr - }; - - ui::X11AtomCache atom_cache(display, kAtomsToCache); - std::vector< ::Atom> atom_list; - atom_list.push_back(atom_cache.GetAtom("_NET_WM_STATE_HIDDEN")); + atom_list.push_back(ui::GetAtom("_NET_WM_STATE_HIDDEN")); ui::SetAtomArrayProperty(xid, "_NET_WM_STATE", "ATOM", atom_list); XEvent xevent; @@ -416,7 +390,7 @@ xevent.xproperty.send_event = 1; xevent.xproperty.display = display; xevent.xproperty.window = xid; - xevent.xproperty.atom = atom_cache.GetAtom("_NET_WM_STATE"); + xevent.xproperty.atom = ui::GetAtom("_NET_WM_STATE"); xevent.xproperty.state = 0; XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask, @@ -429,16 +403,8 @@ // Show from minimized by sending _NET_WM_STATE_FOCUSED { - const char* const kAtomsToCache[] = { - "_NET_WM_STATE", - "_NET_WM_STATE_FOCUSED", - nullptr - }; - - ui::X11AtomCache atom_cache(display, kAtomsToCache); - std::vector< ::Atom> atom_list; - atom_list.push_back(atom_cache.GetAtom("_NET_WM_STATE_FOCUSED")); + atom_list.push_back(ui::GetAtom("_NET_WM_STATE_FOCUSED")); ui::SetAtomArrayProperty(xid, "_NET_WM_STATE", "ATOM", atom_list); XEvent xevent; @@ -448,7 +414,7 @@ xevent.xproperty.send_event = 1; xevent.xproperty.display = display; xevent.xproperty.window = xid; - xevent.xproperty.atom = atom_cache.GetAtom("_NET_WM_STATE"); + xevent.xproperty.atom = ui::GetAtom("_NET_WM_STATE"); xevent.xproperty.state = 0; XSendEvent(display, DefaultRootWindow(display), False, SubstructureRedirectMask | SubstructureNotifyMask,
diff --git a/ui/views/widget/desktop_aura/x11_desktop_handler.cc b/ui/views/widget/desktop_aura/x11_desktop_handler.cc index 4d9ba57..3ee269bb 100644 --- a/ui/views/widget/desktop_aura/x11_desktop_handler.cc +++ b/ui/views/widget/desktop_aura/x11_desktop_handler.cc
@@ -20,11 +20,6 @@ namespace { -const char* const kAtomsToCache[] = { - "_NET_CURRENT_DESKTOP", - nullptr -}; - // Our global instance. Deleted when our Env() is deleted. views::X11DesktopHandler* g_handler = NULL; @@ -47,8 +42,7 @@ X11DesktopHandler::X11DesktopHandler() : xdisplay_(gfx::GetXDisplay()), - x_root_window_(DefaultRootWindow(xdisplay_)), - atom_cache_(xdisplay_, kAtomsToCache) { + x_root_window_(DefaultRootWindow(xdisplay_)) { if (ui::PlatformEventSource::GetInstance()) ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); aura::Env::GetInstance()->AddObserver(this); @@ -96,8 +90,7 @@ uint32_t X11DesktopHandler::DispatchEvent(const ui::PlatformEvent& event) { switch (event->type) { case PropertyNotify: { - if (event->xproperty.atom == - atom_cache_.GetAtom("_NET_CURRENT_DESKTOP")) { + if (event->xproperty.atom == ui::GetAtom("_NET_CURRENT_DESKTOP")) { if (UpdateWorkspace()) { for (views::X11DesktopHandlerObserver& observer : observers_) observer.OnWorkspaceChanged(workspace_);
diff --git a/ui/views/widget/desktop_aura/x11_desktop_handler.h b/ui/views/widget/desktop_aura/x11_desktop_handler.h index 00484b2..ab0c4cbb 100644 --- a/ui/views/widget/desktop_aura/x11_desktop_handler.h +++ b/ui/views/widget/desktop_aura/x11_desktop_handler.h
@@ -17,7 +17,6 @@ #include "ui/aura/env_observer.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/x11/x11_event_source.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/x11_desktop_handler_observer.h" @@ -81,8 +80,6 @@ // Events selected on x_root_window_. std::unique_ptr<ui::XScopedEventSelector> x_root_window_events_; - ui::X11AtomCache atom_cache_; - base::ObserverList<X11DesktopHandlerObserver> observers_; std::string workspace_;
diff --git a/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc b/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc index 112a741c..35509301 100644 --- a/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc +++ b/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc
@@ -26,7 +26,6 @@ #include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/path.h" #include "ui/gfx/path_x11.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/views/test/views_interactive_ui_test_base.h" #include "ui/views/test/x11_property_change_waiter.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" @@ -41,10 +40,7 @@ class MinimizeWaiter : public X11PropertyChangeWaiter { public: explicit MinimizeWaiter(XID window) - : X11PropertyChangeWaiter(window, "_NET_WM_STATE") { - const char* const kAtomsToCache[] = {"_NET_WM_STATE_HIDDEN", nullptr}; - atom_cache_.reset(new ui::X11AtomCache(gfx::GetXDisplay(), kAtomsToCache)); - } + : X11PropertyChangeWaiter(window, "_NET_WM_STATE") {} ~MinimizeWaiter() override {} @@ -54,14 +50,12 @@ std::vector<Atom> wm_states; if (ui::GetAtomArrayProperty(xwindow(), "_NET_WM_STATE", &wm_states)) { auto it = std::find(wm_states.cbegin(), wm_states.cend(), - atom_cache_->GetAtom("_NET_WM_STATE_HIDDEN")); + ui::GetAtom("_NET_WM_STATE_HIDDEN")); return it == wm_states.cend(); } return true; } - std::unique_ptr<ui::X11AtomCache> atom_cache_; - DISALLOW_COPY_AND_ASSIGN(MinimizeWaiter); }; @@ -400,12 +394,8 @@ CWOverrideRedirect, &swa); { - const char* const kAtomsToCache[] = {"_NET_WM_WINDOW_TYPE_MENU", nullptr}; - ui::X11AtomCache atom_cache(gfx::GetXDisplay(), kAtomsToCache); - ui::SetAtomProperty(menu_xid, - "_NET_WM_WINDOW_TYPE", - "ATOM", - atom_cache.GetAtom("_NET_WM_WINDOW_TYPE_MENU")); + ui::SetAtomProperty(menu_xid, "_NET_WM_WINDOW_TYPE", "ATOM", + ui::GetAtom("_NET_WM_WINDOW_TYPE_MENU")); } ui::SetUseOSWindowFrame(menu_xid, false); ShowAndSetXWindowBounds(menu_xid, gfx::Rect(140, 110, 100, 100));
diff --git a/ui/views/widget/desktop_aura/x11_window_event_filter.cc b/ui/views/widget/desktop_aura/x11_window_event_filter.cc index 5e4721c..b1bee28 100644 --- a/ui/views/widget/desktop_aura/x11_window_event_filter.cc +++ b/ui/views/widget/desktop_aura/x11_window_event_filter.cc
@@ -15,6 +15,7 @@ #include "ui/aura/window_delegate.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" +#include "ui/base/x/x11_util.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/events/event.h" @@ -39,11 +40,6 @@ const int k_NET_WM_MOVERESIZE_SIZE_LEFT = 7; const int k_NET_WM_MOVERESIZE_MOVE = 8; -const char* kAtomsToCache[] = { - "_NET_WM_MOVERESIZE", - NULL -}; - } // namespace namespace views { @@ -53,7 +49,6 @@ : xdisplay_(gfx::GetXDisplay()), xwindow_(window_tree_host->AsWindowTreeHost()->GetAcceleratedWidget()), x_root_window_(DefaultRootWindow(xdisplay_)), - atom_cache_(xdisplay_, kAtomsToCache), window_tree_host_(window_tree_host), click_component_(HTNOWHERE) { } @@ -225,7 +220,7 @@ event.xclient.type = ClientMessage; event.xclient.display = xdisplay_; event.xclient.window = xwindow_; - event.xclient.message_type = atom_cache_.GetAtom("_NET_WM_MOVERESIZE"); + event.xclient.message_type = ui::GetAtom("_NET_WM_MOVERESIZE"); event.xclient.format = 32; event.xclient.data.l[0] = screen_location.x(); event.xclient.data.l[1] = screen_location.y();
diff --git a/ui/views/widget/desktop_aura/x11_window_event_filter.h b/ui/views/widget/desktop_aura/x11_window_event_filter.h index 245b720..49aa5672 100644 --- a/ui/views/widget/desktop_aura/x11_window_event_filter.h +++ b/ui/views/widget/desktop_aura/x11_window_event_filter.h
@@ -11,7 +11,6 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "ui/events/event_handler.h" -#include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/views/views_export.h" @@ -57,8 +56,6 @@ // The native root window. ::Window x_root_window_; - ui::X11AtomCache atom_cache_; - DesktopWindowTreeHost* window_tree_host_; // The non-client component for the target of a MouseEvent. Mouse events can
diff --git a/ui/webui/resources/polymer_resources.grdp b/ui/webui/resources/polymer_resources.grdp index 007afae..de97031 100644 --- a/ui/webui/resources/polymer_resources.grdp +++ b/ui/webui/resources/polymer_resources.grdp
@@ -599,15 +599,9 @@ <structure name="IDR_POLYMER_1_0_PAPER_LISTBOX_PAPER_LISTBOX_HTML" file="../../../third_party/polymer/v1_0/components-chromium/paper-listbox/paper-listbox.html" type="chrome_html" /> - <structure name="IDR_POLYMER_1_0_PAPER_MATERIAL_PAPER_MATERIAL_EXTRACTED_JS" - file="../../../third_party/polymer/v1_0/components-chromium/paper-material/paper-material-extracted.js" - type="chrome_html" /> <structure name="IDR_POLYMER_1_0_PAPER_MATERIAL_PAPER_MATERIAL_SHARED_STYLES_HTML" file="../../../third_party/polymer/v1_0/components-chromium/paper-material/paper-material-shared-styles.html" type="chrome_html" /> - <structure name="IDR_POLYMER_1_0_PAPER_MATERIAL_PAPER_MATERIAL_HTML" - file="../../../third_party/polymer/v1_0/components-chromium/paper-material/paper-material.html" - type="chrome_html" /> <structure name="IDR_POLYMER_1_0_PAPER_MENU_BUTTON_PAPER_MENU_BUTTON_ANIMATIONS_EXTRACTED_JS" file="../../../third_party/polymer/v1_0/components-chromium/paper-menu-button/paper-menu-button-animations-extracted.js" type="chrome_html" />