diff --git a/DEPS b/DEPS index 1c592e8d..53a75fd 100644 --- a/DEPS +++ b/DEPS
@@ -40,7 +40,7 @@ # 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': 'c1889823de68ffd2ef08b5c1969d41c98034ec6a', + 'skia_revision': 'c7be00366bb0171e2d247ea71e291a64e3d10254', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other.
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 2cac47d..1807a89 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -429,6 +429,8 @@ "browser/child_frame.h", "browser/command_line_helper.cc", "browser/command_line_helper.h", + "browser/compositor_frame_consumer.h", + "browser/compositor_frame_producer.h", "browser/compositor_id.cc", "browser/compositor_id.h", "browser/deferred_gpu_command_service.cc", @@ -477,6 +479,7 @@ "browser/parent_output_surface.h", "browser/render_thread_manager.cc", "browser/render_thread_manager.h", + "browser/render_thread_manager_client.h", "browser/renderer_host/auto_login_parser.cc", "browser/renderer_host/auto_login_parser.h", "browser/renderer_host/aw_render_view_host_ext.cc", @@ -519,6 +522,7 @@ "lib/main/webview_jni_onload.cc", "lib/main/webview_jni_onload.h", "public/browser/draw_gl.h", + "public/browser/draw_sw.h", "renderer/aw_content_renderer_client.cc", "renderer/aw_content_renderer_client.h", "renderer/aw_content_settings_client.cc",
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/RenderProcessGoneHelper.java b/android_webview/javatests/src/org/chromium/android_webview/test/RenderProcessGoneHelper.java index d6940ef..b32d48e1 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/RenderProcessGoneHelper.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/RenderProcessGoneHelper.java
@@ -19,6 +19,7 @@ private int mState; private CallbackHelper mCallbackHelper; + private Runnable mOnRenderProcessGoneTask; public RenderProcessGoneHelper() { mCallbackHelper = new CallbackHelper(); @@ -48,6 +49,8 @@ @Override public void onRenderProcessGone() { + if (mOnRenderProcessGoneTask != null) mOnRenderProcessGoneTask.run(); + mState = RENDER_PROCESS_GONE_NOTIFIED_TO_AW_CONTENTS; mCallbackHelper.notifyCalled(); } @@ -63,4 +66,8 @@ mState = AW_CONTENTS_DESTROYED; mCallbackHelper.notifyCalled(); } + + public void setOnRenderProcessGoneTask(Runnable task) { + mOnRenderProcessGoneTask = task; + } } \ No newline at end of file
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/crash/VisualStateCallbackTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/crash/VisualStateCallbackTest.java index 447dd49c..884f4c0 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/crash/VisualStateCallbackTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/crash/VisualStateCallbackTest.java
@@ -153,13 +153,16 @@ @SmallTest @CommandLineFlags .Add(AwSwitches.WEBVIEW_SANDBOXED_RENDERER) - @ParameterizedTest.Set - public void testAddVisualStateCallbackAfterRendererGone() throws Throwable { + @ParameterizedTest.Set + public void testAddVisualStateCallbackAfterRendererGone() throws Throwable { + final VisualStateCallbackImpl vsImpl = new VisualStateCallbackImpl(); + mHelper.setOnRenderProcessGoneTask(new Runnable() { + @Override + public void run() { + mAwContents.insertVisualStateCallback(vsImpl.requestId(), vsImpl); + } + }); loadUrlAsync(mAwContents, "chrome://kill"); - mHelper.waitForRenderProcessGone(); - - VisualStateCallbackImpl vsImpl = new VisualStateCallbackImpl(); - insertVisualStateCallbackOnUIThread(mAwContents, vsImpl.requestId(), vsImpl); mHelper.waitForRenderProcessGoneNotifiedToAwContentsClient(); @@ -174,8 +177,8 @@ @SmallTest @CommandLineFlags .Add(AwSwitches.WEBVIEW_SANDBOXED_RENDERER) - @ParameterizedTest.Set - public void testVisualStateCallbackNotCalledAfterRendererGone() throws Throwable { + @ParameterizedTest.Set + public void testVisualStateCallbackNotCalledAfterRendererGone() throws Throwable { VisualStateCallbackImpl vsImpl = new VisualStateCallbackImpl(); insertVisualStateCallbackOnUIThread(mAwContents, vsImpl.requestId(), vsImpl);
diff --git a/ash/ash_switches.cc b/ash/ash_switches.cc index 9f30a0e..4ec343d 100644 --- a/ash/ash_switches.cc +++ b/ash/ash_switches.cc
@@ -58,9 +58,9 @@ // Enables mirrored screen. const char kAshEnableMirroredScreen[] = "ash-enable-mirrored-screen"; -// Enables a smoother animation for screen rotation. -const char kAshEnableSmoothScreenRotation[] = - "ash-enable-smooth-screen-rotation"; +// Disables a smoother animation for screen rotation. +const char kAshDisableSmoothScreenRotation[] = + "ash-disable-smooth-screen-rotation"; // Specifies the estimated time (in milliseconds) from VSYNC event until when // visible light can be noticed by the user.
diff --git a/ash/ash_switches.h b/ash/ash_switches.h index 6b28dccb..16089dd 100644 --- a/ash/ash_switches.h +++ b/ash/ash_switches.h
@@ -22,12 +22,12 @@ ASH_EXPORT extern const char kAshDeveloperShortcuts[]; ASH_EXPORT extern const char kAshDisableMaximizeModeWindowBackdrop[]; ASH_EXPORT extern const char kAshDisableScreenOrientationLock[]; +ASH_EXPORT extern const char kAshDisableSmoothScreenRotation[]; ASH_EXPORT extern const char kAshDisableTouchExplorationMode[]; ASH_EXPORT extern const char kAshEnableMagnifierKeyScroller[]; ASH_EXPORT extern const char kAshEnablePaletteOnAllDisplays[]; ASH_EXPORT extern const char kAshEnableTouchView[]; ASH_EXPORT extern const char kAshEnableMirroredScreen[]; -ASH_EXPORT extern const char kAshEnableSmoothScreenRotation[]; ASH_EXPORT extern const char kAshEstimatedPresentationDelay[]; ASH_EXPORT extern const char kAshForceEnablePalette[]; ASH_EXPORT extern const char kAshForceTabletMode[];
diff --git a/ash/rotator/screen_rotation_animator.cc b/ash/rotator/screen_rotation_animator.cc index 9c6bf5f6..31a54537 100644 --- a/ash/rotator/screen_rotation_animator.cc +++ b/ash/rotator/screen_rotation_animator.cc
@@ -134,16 +134,6 @@ return request_id < current_request_id; } -// In the following cases, abort rotation: -// 1) if the display was removed, -// 2) the copy request has been canceled or failed. It would fail if, -// for examples: a) The layer is removed from the compositor and destroye -// before committing the request to the compositor. b) The compositor is -// shutdown. -bool AbortRotation(int64_t display_id, cc::CopyOutputResult* result) { - return !IsDisplayIdValid(display_id) || result->IsEmpty(); -} - // Creates a black mask layer and returns the |layer_owner|. std::unique_ptr<ui::LayerOwner> CreateBlackMaskLayerOwner( const gfx::Rect& rect) { @@ -180,9 +170,9 @@ metrics_reporter_( base::MakeUnique<ScreenRotationAnimationMetricsReporter>()), disable_animation_timers_for_test_(false), - has_switch_ash_enable_smooth_screen_rotation_( + has_switch_ash_disable_smooth_screen_rotation_( base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kAshEnableSmoothScreenRotation)), + switches::kAshDisableSmoothScreenRotation)), root_window_(GetRootWindow(display_id_)), screen_rotation_container_layer_( GetScreenRotationContainer(root_window_)->layer()), @@ -212,14 +202,14 @@ } rotation_request->old_rotation = current_rotation; - if (has_switch_ash_enable_smooth_screen_rotation_) { + if (has_switch_ash_disable_smooth_screen_rotation_) { + StartSlowAnimation(std::move(rotation_request)); + } else { std::unique_ptr<cc::CopyOutputRequest> copy_output_request = cc::CopyOutputRequest::CreateRequest( CreateAfterCopyCallbackBeforeRotation(std::move(rotation_request))); RequestCopyScreenRotationContainerLayer(std::move(copy_output_request)); screen_rotation_state_ = COPY_REQUESTED; - } else { - StartSlowAnimation(std::move(rotation_request)); } } @@ -275,7 +265,18 @@ std::unique_ptr<cc::CopyOutputResult> result) { if (IgnoreCopyResult(rotation_request->id, rotation_request_id_)) return; - if (AbortRotation(display_id_, result.get())) { + // Abort rotation and animation if the display was removed. + if (!IsDisplayIdValid(display_id_)) { + ProcessAnimationQueue(); + return; + } + // Abort animation and set the rotation to target rotation when the copy + // request has been canceled or failed. It would fail if, for examples: a) The + // layer is removed from the compositor and destroye before committing the + // request to the compositor. b) The compositor is shutdown. + if (result->IsEmpty()) { + Shell::Get()->display_manager()->SetDisplayRotation( + display_id_, rotation_request->new_rotation, rotation_request->source); ProcessAnimationQueue(); return; } @@ -295,7 +296,13 @@ std::unique_ptr<cc::CopyOutputResult> result) { if (IgnoreCopyResult(rotation_request->id, rotation_request_id_)) return; - if (AbortRotation(display_id_, result.get())) { + // In the following cases, abort animation: + // 1) if the display was removed, + // 2) the copy request has been canceled or failed. It would fail if, + // for examples: a) The layer is removed from the compositor and destroye + // before committing the request to the compositor. b) The compositor is + // shutdown. + if (!IsDisplayIdValid(display_id_) || result->IsEmpty()) { ProcessAnimationQueue(); return; } @@ -344,15 +351,16 @@ rotated_screen_bounds.height() / 2); ui::Layer* new_root_layer; - if (new_layer_tree_owner_ && has_switch_ash_enable_smooth_screen_rotation_) { + if (!new_layer_tree_owner_ || + has_switch_ash_disable_smooth_screen_rotation_) { + new_root_layer = screen_rotation_container_layer_; + } else { new_root_layer = new_layer_tree_owner_->root(); // Add a black mask layer on top of |screen_rotation_container_layer_|. black_mask_layer_owner_ = CreateBlackMaskLayerOwner( gfx::Rect(screen_rotation_container_layer_->size())); AddLayerBelowWindowLayer(root_window_, new_root_layer, black_mask_layer_owner_->layer()); - } else { - new_root_layer = screen_rotation_container_layer_; } std::unique_ptr<ScreenRotationAnimation> new_layer_screen_rotation =
diff --git a/ash/rotator/screen_rotation_animator.h b/ash/rotator/screen_rotation_animator.h index 1a47928..1c1a5c7 100644 --- a/ash/rotator/screen_rotation_animator.h +++ b/ash/rotator/screen_rotation_animator.h
@@ -176,7 +176,7 @@ std::unique_ptr<ui::LayerTreeOwner> new_layer_tree_owner_; std::unique_ptr<ui::LayerOwner> black_mask_layer_owner_; std::unique_ptr<ScreenRotationRequest> last_pending_request_; - bool has_switch_ash_enable_smooth_screen_rotation_; + bool has_switch_ash_disable_smooth_screen_rotation_; aura::Window* root_window_; ui::Layer* screen_rotation_container_layer_; base::WeakPtrFactory<ScreenRotationAnimator> weak_factory_;
diff --git a/ash/rotator/screen_rotation_animator_unittest.cc b/ash/rotator/screen_rotation_animator_unittest.cc index 19de9ce..fa65898 100644 --- a/ash/rotator/screen_rotation_animator_unittest.cc +++ b/ash/rotator/screen_rotation_animator_unittest.cc
@@ -12,6 +12,7 @@ #include "ash/shell.h" #include "ash/shell_port.h" #include "ash/test/ash_test_base.h" +#include "ash/test/ash_test_helper.h" #include "base/callback_forward.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" @@ -222,6 +223,10 @@ void ScreenRotationAnimatorSmoothAnimationTest::SetUp() { AshTestBase::SetUp(); + // Resets the commandline will clear all the switches, including + // "ash-disable-smooth-screen-rotation", so that we can test the smooth screen + // rotation animation. The |animator| is recreated and checking this swtich. + ash_test_helper()->reset_commandline(); display_ = display::Screen::GetScreen()->GetPrimaryDisplay(); if (Shell::GetAshConfig() == Config::MASH) { @@ -230,8 +235,6 @@ return; } - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kAshEnableSmoothScreenRotation); run_loop_ = base::MakeUnique<base::RunLoop>(); SetScreenRotationAnimator(display_.id(), run_loop_->QuitWhenIdleClosure(), run_loop_->QuitWhenIdleClosure());
diff --git a/ash/system/ime_menu/ime_menu_tray.cc b/ash/system/ime_menu/ime_menu_tray.cc index 721c4385..e75c7e0 100644 --- a/ash/system/ime_menu/ime_menu_tray.cc +++ b/ash/system/ime_menu/ime_menu_tray.cc
@@ -286,7 +286,6 @@ label_(new ImeMenuLabel()), show_keyboard_(false), force_show_keyboard_(false), - should_block_shelf_auto_hide_(false), keyboard_suppressed_(false), show_bubble_after_keyboard_hidden_(false) { SetInkDropMode(InkDropMode::ON); @@ -324,7 +323,6 @@ } void ImeMenuTray::ShowImeMenuBubbleInternal() { - should_block_shelf_auto_hide_ = true; views::TrayBubbleView::InitParams init_params( GetAnchorAlignment(), kTrayMenuMinimumWidth, kTrayMenuMinimumWidth); init_params.can_activate = true; @@ -355,7 +353,6 @@ bubble_.reset(); ime_list_view_ = nullptr; SetIsActive(false); - should_block_shelf_auto_hide_ = false; shelf()->UpdateAutoHideState(); } @@ -404,10 +401,6 @@ } } -bool ImeMenuTray::ShouldBlockShelfAutoHide() const { - return should_block_shelf_auto_hide_; -} - bool ImeMenuTray::ShouldShowEmojiHandwritingVoiceButtons() const { // Emoji, handwriting and voice input is not supported for these cases: // 1) features::kEHVInputOnImeMenu is not enabled.
diff --git a/ash/system/ime_menu/ime_menu_tray.h b/ash/system/ime_menu/ime_menu_tray.h index 33a54ff44..dab6966 100644 --- a/ash/system/ime_menu/ime_menu_tray.h +++ b/ash/system/ime_menu/ime_menu_tray.h
@@ -48,9 +48,6 @@ // voice. void ShowKeyboardWithKeyset(const std::string& keyset); - // Returns true if it should block the auto hide behavior of the shelf. - bool ShouldBlockShelfAutoHide() const; - // Returns true if the menu should show emoji, handwriting and voice buttons // on the bottom. Otherwise, the menu will show a 'Customize...' bottom row // for non-MD UI, and a Settings button in the title row for MD. @@ -107,7 +104,6 @@ IMEInfo current_ime_; bool show_keyboard_; bool force_show_keyboard_; - bool should_block_shelf_auto_hide_; bool keyboard_suppressed_; bool show_bubble_after_keyboard_hidden_;
diff --git a/ash/system/ime_menu/ime_menu_tray_unittest.cc b/ash/system/ime_menu/ime_menu_tray_unittest.cc index 5de04e8..c759c18 100644 --- a/ash/system/ime_menu/ime_menu_tray_unittest.cc +++ b/ash/system/ime_menu/ime_menu_tray_unittest.cc
@@ -137,11 +137,14 @@ // Tests that IME menu tray changes background color when tapped/clicked. And // tests that the background color becomes 'inactive' when disabling the IME -// menu feature. +// menu feature. Also makes sure that the shelf won't autohide as long as the +// IME menu is open. TEST_F(ImeMenuTrayTest, PerformAction) { Shell::Get()->system_tray_notifier()->NotifyRefreshIMEMenu(true); ASSERT_TRUE(IsVisible()); ASSERT_FALSE(IsTrayBackgroundActive()); + StatusAreaWidget* status = StatusAreaWidgetTestHelper::GetStatusAreaWidget(); + EXPECT_FALSE(status->ShouldShowShelf()); ui::GestureEvent tap(0, 0, 0, base::TimeTicks(), ui::GestureEventDetails(ui::ET_GESTURE_TAP)); @@ -149,6 +152,10 @@ EXPECT_TRUE(IsTrayBackgroundActive()); EXPECT_TRUE(IsBubbleShown()); + // Auto-hidden shelf would be forced to be visible as long as the bubble is + // open. + EXPECT_TRUE(status->ShouldShowShelf()); + GetTray()->PerformAction(tap); EXPECT_FALSE(IsTrayBackgroundActive()); EXPECT_FALSE(IsBubbleShown()); @@ -161,6 +168,7 @@ EXPECT_FALSE(IsVisible()); EXPECT_FALSE(IsBubbleShown()); EXPECT_FALSE(IsTrayBackgroundActive()); + EXPECT_FALSE(status->ShouldShowShelf()); } // Tests that IME menu list updates when changing the current IME. This should
diff --git a/ash/system/palette/palette_tray.cc b/ash/system/palette/palette_tray.cc index 97a2cca..ab54c99b 100644 --- a/ash/system/palette/palette_tray.cc +++ b/ash/system/palette/palette_tray.cc
@@ -178,10 +178,6 @@ DCHECK(tray_container()); - // The views::TrayBubbleView ctor will cause a shelf auto hide update check. - // Make sure to block auto hiding before that check happens. - should_block_shelf_auto_hide_ = true; - // TODO(tdanderson): Refactor into common row layout code. // TODO(tdanderson|jdufault): Add material design ripple effects to the menu // rows. @@ -314,7 +310,6 @@ } void PaletteTray::HidePalette() { - should_block_shelf_auto_hide_ = false; is_bubble_auto_opened_ = false; num_actions_in_bubble_ = 0; bubble_.reset(); @@ -349,10 +344,6 @@ PaletteModeCancelType::PALETTE_MODE_CANCEL_TYPE_COUNT); } -bool PaletteTray::ShouldBlockShelfAutoHide() const { - return should_block_shelf_auto_hide_; -} - void PaletteTray::OnActiveToolChanged() { ++num_actions_in_bubble_; UpdateTrayIcon();
diff --git a/ash/system/palette/palette_tray.h b/ash/system/palette/palette_tray.h index 5bd0deb6f..0218715a 100644 --- a/ash/system/palette/palette_tray.h +++ b/ash/system/palette/palette_tray.h
@@ -66,9 +66,6 @@ void RecordPaletteOptionsUsage(PaletteTrayOptions option) override; void RecordPaletteModeCancellation(PaletteModeCancelType type) override; - // Returns true if the shelf should not autohide. - bool ShouldBlockShelfAutoHide() const; - // Opens up the palette if it is not already open. Returns true if the palette // was opened. bool ShowPalette(); @@ -117,11 +114,6 @@ // Weak pointer, will be parented by TrayContainer for its lifetime. views::ImageView* icon_; - // The shelf auto-hide state is checked during the tray constructor, so we - // have to use a helper variable instead of just checking if we have a tray - // instance. - bool should_block_shelf_auto_hide_ = false; - // Cached palette enabled/disabled pref value. bool is_palette_enabled_ = true;
diff --git a/ash/system/status_area_widget.cc b/ash/system/status_area_widget.cc index 232602fc..13967cf7 100644 --- a/ash/system/status_area_widget.cc +++ b/ash/system/status_area_widget.cc
@@ -136,18 +136,8 @@ } bool StatusAreaWidget::ShouldShowShelf() const { - if ((system_tray_ && system_tray_->ShouldShowShelf()) || - (web_notification_tray_ && - web_notification_tray_->ShouldBlockShelfAutoHide())) - return true; - - if (palette_tray_ && palette_tray_->ShouldBlockShelfAutoHide()) - return true; - - if (ime_menu_tray_ && ime_menu_tray_->ShouldBlockShelfAutoHide()) - return true; - - return false; + return (system_tray_ && system_tray_->ShouldShowShelf()) || + views::TrayBubbleView::IsATrayBubbleOpen(); } bool StatusAreaWidget::IsMessageBubbleShown() const {
diff --git a/ash/system/web_notification/ash_popup_alignment_delegate.cc b/ash/system/web_notification/ash_popup_alignment_delegate.cc index 360062a0..f2e4d84 100644 --- a/ash/system/web_notification/ash_popup_alignment_delegate.cc +++ b/ash/system/web_notification/ash_popup_alignment_delegate.cc
@@ -122,6 +122,11 @@ widget, kShellWindowId_StatusContainer, init_params); } +bool AshPopupAlignmentDelegate::IsPrimaryDisplayForNotification() const { + return screen_ && + GetCurrentDisplay().id() == screen_->GetPrimaryDisplay().id(); +} + ShelfAlignment AshPopupAlignmentDelegate::GetAlignment() const { return shelf_->GetAlignment(); }
diff --git a/ash/system/web_notification/ash_popup_alignment_delegate.h b/ash/system/web_notification/ash_popup_alignment_delegate.h index 93db7bc..0bf17dcd 100644 --- a/ash/system/web_notification/ash_popup_alignment_delegate.h +++ b/ash/system/web_notification/ash_popup_alignment_delegate.h
@@ -57,6 +57,7 @@ void ConfigureWidgetInitParamsForContainer( views::Widget* widget, views::Widget::InitParams* init_params) override; + bool IsPrimaryDisplayForNotification() const override; private: friend class AshPopupAlignmentDelegateTest;
diff --git a/ash/system/web_notification/web_notification_tray.cc b/ash/system/web_notification/web_notification_tray.cc index 2b0b8d4..a5713b6 100644 --- a/ash/system/web_notification/web_notification_tray.cc +++ b/ash/system/web_notification/web_notification_tray.cc
@@ -273,8 +273,7 @@ status_area_window_(status_area_window), system_tray_(system_tray), show_message_center_on_unlock_(false), - should_update_tray_content_(false), - should_block_shelf_auto_hide_(false) { + should_update_tray_content_(false) { DCHECK(shelf); DCHECK(status_area_window_); DCHECK(system_tray_); @@ -322,7 +321,6 @@ if (!ShouldShowMessageCenter()) return false; - should_block_shelf_auto_hide_ = true; message_center::MessageCenterBubble* message_center_bubble = new message_center::MessageCenterBubble(message_center(), message_center_tray_.get()); @@ -363,7 +361,6 @@ return; SetIsActive(false); message_center_bubble_.reset(); - should_block_shelf_auto_hide_ = false; show_message_center_on_unlock_ = false; shelf()->UpdateAutoHideState(); } @@ -396,10 +393,6 @@ return Shell::Get()->session_controller()->ShouldShowNotificationTray(); } -bool WebNotificationTray::ShouldBlockShelfAutoHide() const { - return should_block_shelf_auto_hide_; -} - bool WebNotificationTray::IsMessageCenterBubbleVisible() const { return (message_center_bubble() && message_center_bubble()->bubble()->IsVisible());
diff --git a/ash/test/ash_test_base.cc b/ash/test/ash_test_base.cc index 47422979..83a8f43 100644 --- a/ash/test/ash_test_base.cc +++ b/ash/test/ash_test_base.cc
@@ -26,7 +26,6 @@ #include "ash/test/test_system_tray_delegate.h" #include "ash/wm/window_positioner.h" #include "ash/wm_window.h" -#include "base/command_line.h" #include "services/ui/public/interfaces/window_manager_constants.mojom.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/screen_position_client.h" @@ -39,7 +38,6 @@ #include "ui/aura/window_tree_host.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/display/display.h" -#include "ui/display/display_switches.h" #include "ui/display/screen.h" #include "ui/display/test/display_manager_test_api.h" #include "ui/display/types/display_constants.h" @@ -121,15 +119,6 @@ // default state. shell::ToplevelWindow::ClearSavedStateForTest(); - // TODO(jamescook): Can we do this without changing command line? - // Use the origin (1,1) so that it doesn't over - // lap with the native mouse cursor. - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (!command_line->HasSwitch(::switches::kHostWindowBounds)) { - command_line->AppendSwitchASCII(::switches::kHostWindowBounds, - "1+1-800x600"); - } - ash_test_helper_->SetUp(start_session_); Shell::GetPrimaryRootWindow()->Show();
diff --git a/ash/test/ash_test_helper.cc b/ash/test/ash_test_helper.cc index 3a48ae3..28d129e 100644 --- a/ash/test/ash_test_helper.cc +++ b/ash/test/ash_test_helper.cc
@@ -5,6 +5,7 @@ #include "ash/test/ash_test_helper.h" #include "ash/accelerators/accelerator_controller_delegate_aura.h" +#include "ash/ash_switches.h" #include "ash/aura/shell_port_classic.h" #include "ash/mus/bridge/shell_port_mash.h" #include "ash/mus/screen_mus.h" @@ -45,6 +46,7 @@ #include "ui/base/test/material_design_controller_test_api.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/context_factories_for_test.h" +#include "ui/display/display_switches.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/managed_display_info.h" #include "ui/display/test/display_manager_test_api.h" @@ -83,6 +85,28 @@ AshTestHelper::~AshTestHelper() {} void AshTestHelper::SetUp(bool start_session) { + command_line_ = base::MakeUnique<base::test::ScopedCommandLine>(); + // TODO(jamescook): Can we do this without changing command line? + // Use the origin (1,1) so that it doesn't over + // lap with the native mouse cursor. + if (!command_line_->GetProcessCommandLine()->HasSwitch( + ::switches::kHostWindowBounds)) { + command_line_->GetProcessCommandLine()->AppendSwitchASCII( + ::switches::kHostWindowBounds, "1+1-800x600"); + } + + // TODO(wutao): We enabled a smooth screen rotation animation, which is using + // an asynchronous method. However for some tests require to evaluate the + // screen rotation immediately after the operation of setting display + // rotation, we need to append a slow screen rotation animation flag to pass + // the tests. When we remove the flag "ash-disable-smooth-screen-rotation", we + // need to disable the screen rotation animation in the test. + if (!command_line_->GetProcessCommandLine()->HasSwitch( + switches::kAshDisableSmoothScreenRotation)) { + command_line_->GetProcessCommandLine()->AppendSwitch( + switches::kAshDisableSmoothScreenRotation); + } + if (config_ == Config::MUS) input_device_client_ = base::MakeUnique<ui::InputDeviceClient>(); @@ -226,6 +250,8 @@ input_device_client_.reset(); + command_line_.reset(); + // WindowManager owns the CaptureController for mus/mash. CHECK(config_ != Config::CLASSIC || !::wm::CaptureController::Get()); }
diff --git a/ash/test/ash_test_helper.h b/ash/test/ash_test_helper.h index a0f7aaf5..a53021f2 100644 --- a/ash/test/ash_test_helper.h +++ b/ash/test/ash_test_helper.h
@@ -14,6 +14,7 @@ #include "ash/test/test_session_controller_client.h" #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/test/scoped_command_line.h" #include "ui/aura/test/mus/test_window_tree_client_setup.h" namespace aura { @@ -117,6 +118,8 @@ session_controller_client_ = std::move(session_controller_client); } + void reset_commandline() { command_line_.reset(); } + private: // These TestSuites need to manipulate |config_|. friend class AshTestSuite; @@ -168,6 +171,8 @@ std::unique_ptr<ui::InputDeviceClient> input_device_client_; + std::unique_ptr<base::test::ScopedCommandLine> command_line_; + DISALLOW_COPY_AND_ASSIGN(AshTestHelper); };
diff --git a/base/metrics/histogram.cc b/base/metrics/histogram.cc index e1d0df6..3e4cebe4 100644 --- a/base/metrics/histogram.cc +++ b/base/metrics/histogram.cc
@@ -14,6 +14,7 @@ #include <algorithm> #include <string> +#include <utility> #include "base/compiler_specific.h" #include "base/debug/alias.h" @@ -718,7 +719,7 @@ if (i != bucket_count() - 1) bucket_value->SetInteger("high", ranges(i + 1)); bucket_value->SetInteger("count", count_at_index); - buckets->Set(index, bucket_value.release()); + buckets->Set(index, std::move(bucket_value)); ++index; } }
diff --git a/base/values.cc b/base/values.cc index 3397f1c3..aa3407fd 100644 --- a/base/values.cc +++ b/base/values.cc
@@ -1059,6 +1059,11 @@ ListValue::ListValue() : Value(Type::LIST) {} +ListValue::ListValue(const ListStorage& in_list) : Value(in_list) {} + +ListValue::ListValue(ListStorage&& in_list) noexcept + : Value(std::move(in_list)) {} + void ListValue::Clear() { list_->clear(); } @@ -1067,10 +1072,6 @@ list_->reserve(n); } -bool ListValue::Set(size_t index, Value* in_value) { - return Set(index, WrapUnique(in_value)); -} - bool ListValue::Set(size_t index, std::unique_ptr<Value> in_value) { if (!in_value) return false;
diff --git a/base/values.h b/base/values.h index 99b30fc..920c0a3 100644 --- a/base/values.h +++ b/base/values.h
@@ -383,6 +383,8 @@ static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value); ListValue(); + explicit ListValue(const ListStorage& in_list); + explicit ListValue(ListStorage&& in_list) noexcept; // Clears the contents of this ListValue void Clear(); @@ -404,8 +406,6 @@ // Values will be used to pad out the list. // Returns true if successful, or false if the index was negative or // the value is a null pointer. - bool Set(size_t index, Value* in_value); - // Preferred version of the above. TODO(estade): remove the above. bool Set(size_t index, std::unique_ptr<Value> in_value); // Gets the Value at the given index. Modifies |out_value| (and returns true) @@ -430,6 +430,8 @@ bool GetBinary(size_t index, Value** out_value); bool GetDictionary(size_t index, const DictionaryValue** out_value) const; bool GetDictionary(size_t index, DictionaryValue** out_value); + + using Value::GetList; bool GetList(size_t index, const ListValue** out_value) const; bool GetList(size_t index, ListValue** out_value);
diff --git a/base/values_unittest.cc b/base/values_unittest.cc index a781dc4..da4d267 100644 --- a/base/values_unittest.cc +++ b/base/values_unittest.cc
@@ -35,6 +35,9 @@ "IsNothrowMoveConstructibleFromList"); static_assert(std::is_nothrow_move_assignable<Value>::value, "IsNothrowMoveAssignable"); + static_assert( + std::is_nothrow_constructible<ListValue, Value::ListStorage&&>::value, + "ListIsNothrowMoveConstructibleFromList"); } // Group of tests for the value constructors. @@ -119,6 +122,28 @@ EXPECT_EQ(Value::Type::LIST, value.type()); } +TEST(ValuesTest, ConstructListFromStorage) { + Value::ListStorage storage; + storage.emplace_back("foo"); + + { + ListValue value(storage); + EXPECT_EQ(Value::Type::LIST, value.type()); + EXPECT_EQ(1u, value.GetList().size()); + EXPECT_EQ(Value::Type::STRING, value.GetList()[0].type()); + EXPECT_EQ("foo", value.GetList()[0].GetString()); + } + + storage.back() = base::Value("bar"); + { + ListValue value(std::move(storage)); + EXPECT_EQ(Value::Type::LIST, value.type()); + EXPECT_EQ(1u, value.GetList().size()); + EXPECT_EQ(Value::Type::STRING, value.GetList()[0].type()); + EXPECT_EQ("bar", value.GetList()[0].GetString()); + } +} + // Group of tests for the copy constructors and copy-assigmnent. For equality // checks comparisons of the interesting fields are done instead of relying on // Equals being correct.
diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index 593a88d..4a341784 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn
@@ -359,20 +359,6 @@ # Force include the header. cflags = [ "/FI$precompiled_header" ] - - # Disable warning for "this file was empty after preprocessing". This - # error is generated only in C mode for ANSI compatibility. It conflicts - # with precompiled headers since the source file that's "compiled" for - # making the precompiled header is empty. - # - # This error doesn't happen every time. In VS2013, it seems if the .pch - # file doesn't exist, no error will be generated (probably MS tested this - # case but forgot the other one?). To reproduce this error, do a build, - # then delete the precompile.c.obj file, then build again. - # - # TODO(sof): determine VS2015 status and retire the setting from all - # precompiled configurations. - cflags_c = [ "/wd4206" ] } else if (is_mac) { precompiled_source = "//build/precompile.h" }
diff --git a/build/config/compiler/compiler.gni b/build/config/compiler/compiler.gni index e4f463a..d1bcc4c 100644 --- a/build/config/compiler/compiler.gni +++ b/build/config/compiler/compiler.gni
@@ -66,35 +66,31 @@ use_pic = true } -# Determine the default setting for enable_frame_pointers, based on the platform +# Determine whether to enable or disable frame pointers, based on the platform # and build arguments. if (is_mac || is_ios) { - _default_enable_frame_pointers = true + enable_frame_pointers = true } else if (is_win) { # 64-bit Windows ABI doesn't support frame pointers. if (target_cpu == "x64") { - _default_enable_frame_pointers = false + enable_frame_pointers = false } else { - _default_enable_frame_pointers = true + enable_frame_pointers = true } +} else if (is_chromeos) { + # ChromeOS requires frame pointers in x64 builds, to support CWP. + # TODO(711784): Building ARM Thumb without frame pointers can lead to code + # in ChromeOS which triggers some ARM A12/A17 errata. They can be disabled + # on non-x64 once that is resolved. + enable_frame_pointers = true } else if (current_cpu == "arm64") { # Ensure that stacks from arm64 crash dumps are usable (crbug.com/391706). - _default_enable_frame_pointers = true -} else if (is_chromeos && current_cpu == "arm" && arm_use_thumb) { - # TODO(711784): Building ARM Thumb without frame pointers can lead to code - # in ChromeOS which triggers some ARM A12/A17 errata. - _default_enable_frame_pointers = true + enable_frame_pointers = true } else { # Explicitly ask for frame pointers, otherwise: # * Stacks may be missing for sanitizer and profiling builds. # * Debug tcmalloc can crash (crbug.com/636489). - _default_enable_frame_pointers = - using_sanitizer || enable_profiling || is_debug -} - -declare_args() { - # True if frame pointers should be generated, false otherwise. - enable_frame_pointers = _default_enable_frame_pointers + enable_frame_pointers = using_sanitizer || enable_profiling || is_debug } # In general assume that if we have frame pointers then we can use them to
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ProfileDataCache.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ProfileDataCache.java index 2078786..4e9e3c5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ProfileDataCache.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ProfileDataCache.java
@@ -17,10 +17,10 @@ import android.graphics.Rect; import org.chromium.base.Callback; +import org.chromium.base.ObserverList; import org.chromium.chrome.R; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.profiles.ProfileDownloader; -import org.chromium.chrome.browser.profiles.ProfileDownloader.Observer; import org.chromium.components.signin.AccountManagerHelper; import org.chromium.ui.display.DisplayAndroid; @@ -29,8 +29,7 @@ /** * Fetches and caches Google Account profile images and full names for the accounts on the device. */ -public class ProfileDataCache implements Observer { - +public class ProfileDataCache implements ProfileDownloader.Observer { private static final int PROFILE_IMAGE_SIZE_DP = 136; // Max size of the user picture. private static final int PROFILE_IMAGE_STROKE_DP = 3; @@ -52,7 +51,7 @@ private final int mImageSizePx; private final int mImageStrokePx; private final int mImageStrokeColor; - private Observer mObserver; + private final ObserverList<ProfileDownloader.Observer> mObservers = new ObserverList<>(); private final Context mContext; private Profile mProfile; @@ -129,7 +128,21 @@ public void destroy() { ProfileDownloader.removeObserver(this); - mObserver = null; + mObservers.clear(); + } + + /** + * @param observer Observer that should be notified when new profile images are available. + */ + public void addObserver(ProfileDownloader.Observer observer) { + mObservers.addObserver(observer); + } + + /** + * @param observer Observer that was added by {@link #addObserver} and should be removed. + */ + public void removeObserver(ProfileDownloader.Observer observer) { + mObservers.removeObserver(observer); } @Override @@ -137,8 +150,8 @@ Bitmap bitmap) { bitmap = getCroppedBitmap(bitmap); mCacheEntries.put(accountId, new CacheEntry(bitmap, fullName, givenName)); - if (mObserver != null) { - mObserver.onProfileDownloaded(accountId, fullName, givenName, bitmap); + for (ProfileDownloader.Observer observer : mObservers) { + observer.onProfileDownloaded(accountId, fullName, givenName, bitmap); } } @@ -167,11 +180,4 @@ return output; } - - /** - * @param observer Observer that should be notified when new profile images are available. - */ - public void setObserver(Observer observer) { - mObserver = observer; - } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentPreferencesUtil.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentPreferencesUtil.java index 1e5f11b..7c5227b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentPreferencesUtil.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentPreferencesUtil.java
@@ -15,9 +15,6 @@ /** Preference to indicate whether payment request has been completed successfully once.*/ private static final String PAYMENT_COMPLETE_ONCE = "payment_complete_once"; - /** Prefix of the preferences to persist Android payment apps' status. */ - public static final String PAYMENT_ANDROID_APP_ENABLED_ = "payment_android_app_enabled_"; - /** Prefix of the preferences to persist use count of the payment instruments. */ public static final String PAYMENT_INSTRUMENT_USE_COUNT_ = "payment_instrument_use_count_";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java index 0930043..0f729292 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java
@@ -139,7 +139,7 @@ */ public void init(ProfileDataCache profileData, Delegate delegate, Listener listener) { mProfileData = profileData; - mProfileData.setObserver(this); + mProfileData.addObserver(this); mDelegate = delegate; mListener = listener; showSigninPage();
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 07a8c596..1c1995e 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2477,16 +2477,11 @@ FEATURE_VALUE_TYPE( features::kDisplayPersistenceToggleInPermissionPrompts)}, #endif -#if BUILDFLAG(ENABLE_PRINT_PREVIEW) -#if !defined(OS_WIN) && !defined(OS_MACOSX) +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && !defined(OS_WIN) && !defined(OS_MACOSX) {"print-pdf-as-image", flag_descriptions::kPrintPdfAsImageName, flag_descriptions::kPrintPdfAsImageDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kPrintPdfAsImage)}, -#endif // !defined(OS_WIN) && !defined(OS_MACOSX) - {"print-scaling", flag_descriptions::kPrintScalingName, - flag_descriptions::kPrintScalingDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kPrintScaling)}, -#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) +#endif #if defined(OS_ANDROID) {"enable-consistent-omnibox-geolocation", flag_descriptions::kEnableConsistentOmniboxGeolocationName, @@ -2721,10 +2716,10 @@ #endif #if defined(USE_ASH) - {"ash-enable-smooth-screen-rotation", - flag_descriptions::kAshEnableSmoothScreenRotationName, - flag_descriptions::kAshEnableSmoothScreenRotationDescription, kOsCrOS, - SINGLE_VALUE_TYPE(ash::switches::kAshEnableSmoothScreenRotation)}, + {"ash-disable-smooth-screen-rotation", + flag_descriptions::kAshDisableSmoothScreenRotationName, + flag_descriptions::kAshDisableSmoothScreenRotationDescription, kOsCrOS, + SINGLE_DISABLE_VALUE_TYPE(ash::switches::kAshDisableSmoothScreenRotation)}, #endif // defined(USE_ASH) #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/android/offline_pages/downloads/resource_throttle.cc b/chrome/browser/android/offline_pages/downloads/resource_throttle.cc index a09b33c4..ee6aec8 100644 --- a/chrome/browser/android/offline_pages/downloads/resource_throttle.cc +++ b/chrome/browser/android/offline_pages/downloads/resource_throttle.cc
@@ -13,11 +13,13 @@ #include "net/base/mime_util.h" namespace { -// Mime type of download resource that should trigger handoff to OfflinePages -// backend for full page load and snapshot. -bool CanDownloadAsOfflinePage(const std::string& contents_mime_type) { - return net::MatchesMimeType(contents_mime_type, "text/html") || - net::MatchesMimeType(contents_mime_type, "application/xhtml+xml"); +// Check if the url and mime type of a download resource should trigger handoff +// to OfflinePages backend for full page load and snapshot. +bool CanDownloadAsOfflinePage( + const GURL& url, const std::string& contents_mime_type) { + return url.SchemeIsHTTPOrHTTPS() && + (net::MatchesMimeType(contents_mime_type, "text/html") || + net::MatchesMimeType(contents_mime_type, "application/xhtml+xml")); } void WillStartOfflineRequestOnUIThread( @@ -49,7 +51,8 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); std::string mime_type; request_->GetMimeType(&mime_type); - if (CanDownloadAsOfflinePage(mime_type)) { + + if (CanDownloadAsOfflinePage(request_->url(), mime_type)) { const content::ResourceRequestInfo* info = content::ResourceRequestInfo::ForRequest(request_); if (!info)
diff --git a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc index 6f08a1a..1b0587dd 100644 --- a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc +++ b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc
@@ -109,7 +109,7 @@ PaymentAppRequestPtr app_request = PaymentAppRequest::New(); - app_request->optionId = ConvertJavaStringToUTF8(env, joption_id); + app_request->option_id = ConvertJavaStringToUTF8(env, joption_id); app_request->origin = GURL(ConvertJavaStringToUTF8(env, jorigin)); for (jsize i = 0; i < env->GetArrayLength(jmethod_data); i++) { @@ -126,7 +126,7 @@ env, Java_ServiceWorkerPaymentAppBridge_getStringifiedDataFromMethodData( env, element)); - app_request->methodData.push_back(std::move(methodData)); + app_request->method_data.push_back(std::move(methodData)); } app_request->total = PaymentItem::New();
diff --git a/chrome/browser/chromeos/login/proxy_auth_dialog_browsertest.cc b/chrome/browser/chromeos/login/proxy_auth_dialog_browsertest.cc index bd78c765..65aa817d 100644 --- a/chrome/browser/chromeos/login/proxy_auth_dialog_browsertest.cc +++ b/chrome/browser/chromeos/login/proxy_auth_dialog_browsertest.cc
@@ -15,10 +15,10 @@ #include "chrome/browser/ui/login/login_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/common/chrome_switches.h" -#include "chrome/common/chrome_switches.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_controller.h" +#include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/test/spawned_test_server/spawned_test_server.h"
diff --git a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc index 39e7bfe4..5454acd 100644 --- a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc
@@ -68,6 +68,7 @@ #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/testing_pref_store.h" +#include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/test/spawned_test_server/spawned_test_server.h"
diff --git a/chrome/browser/component_updater/subresource_filter_component_installer.cc b/chrome/browser/component_updater/subresource_filter_component_installer.cc index a7635db..5016878 100644 --- a/chrome/browser/component_updater/subresource_filter_component_installer.cc +++ b/chrome/browser/component_updater/subresource_filter_component_installer.cc
@@ -112,16 +112,17 @@ // static std::string SubresourceFilterComponentInstallerTraits::GetInstallerTag() { - std::string ruleset_flavor = subresource_filter::GetActiveConfigurations() - ->the_one_and_only() - .ruleset_flavor; + const auto configurations = subresource_filter::GetActiveConfigurations(); + const std::string& ruleset_flavor = + configurations->the_one_and_only().ruleset_flavor; if (ruleset_flavor.empty()) return ruleset_flavor; // We allow 4 ruleset flavor identifiers: a, b, c, d if (ruleset_flavor.size() == 1 && ruleset_flavor.at(0) >= 'a' && - ruleset_flavor.at(0) <= 'd') + ruleset_flavor.at(0) <= 'd') { return ruleset_flavor; + } // Return 'invalid' for any cases where we encounter an invalid installer // tag. This allows us to verify that no clients are encountering invalid @@ -145,8 +146,9 @@ void RegisterSubresourceFilterComponent(ComponentUpdateService* cus) { if (!base::FeatureList::IsEnabled( - subresource_filter::kSafeBrowsingSubresourceFilter)) + subresource_filter::kSafeBrowsingSubresourceFilter)) { return; + } std::unique_ptr<ComponentInstallerTraits> traits( new SubresourceFilterComponentInstallerTraits()); // |cus| will take ownership of |installer| during installer->Register(cus).
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 7fdd922..6127251 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -125,12 +125,6 @@ "If enabled, an option to print PDF files as images will be available " "in print preview."; -const char kPrintScalingName[] = "Print Scaling."; - -const char kPrintScalingDescription[] = - "If enabled, an option to scale documents will be available in print " - "preview."; - const char kNaclName[] = "Native Client"; #if defined(OS_ANDROID) @@ -743,11 +737,11 @@ "Enable the mirrored screen mode. This mode flips the screen image " "horizontally."; -const char kAshEnableSmoothScreenRotationName[] = - "Enable smooth rotation animations."; +const char kAshDisableSmoothScreenRotationName[] = + "Disable smooth rotation animations."; -const char kAshEnableSmoothScreenRotationDescription[] = - "Enable smooth rotation animations."; +const char kAshDisableSmoothScreenRotationDescription[] = + "Disable smooth rotation animations."; const char kMaterialDesignInkDropAnimationFast[] = "Fast";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 2eeb915..ba0e2b9 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -134,12 +134,6 @@ // preview. extern const char kPrintPdfAsImageDescription[]; -// Name for the flag to add the print scaling feature to print preview. -extern const char kPrintScalingName[]; - -// Description for the flag to add the print scaling feature to print preview. -extern const char kPrintScalingDescription[]; - // Name of the 'Native Client' lab. extern const char kNaclName[]; @@ -819,11 +813,11 @@ // Description for the flag to enable the mirrored screen mode. extern const char kAshEnableMirroredScreenDescription[]; -// Title for the flag to enable smooth rotation animations. -extern const char kAshEnableSmoothScreenRotationName[]; +// Title for the flag to disable smooth rotation animations. +extern const char kAshDisableSmoothScreenRotationName[]; -// Description for the flag to enable smooth rotation animations. -extern const char kAshEnableSmoothScreenRotationDescription[]; +// Description for the flag to disable smooth rotation animations. +extern const char kAshDisableSmoothScreenRotationDescription[]; // Description for the flag that sets material design ink drop animation speed // of fast.
diff --git a/chrome/browser/metrics/android_metrics_provider.cc b/chrome/browser/metrics/android_metrics_provider.cc index c7f89e1..79847f4 100644 --- a/chrome/browser/metrics/android_metrics_provider.cc +++ b/chrome/browser/metrics/android_metrics_provider.cc
@@ -16,10 +16,8 @@ namespace { // Increments a particular entry in the ListValue. -void IncrementListValue(base::ListValue* counts, int index) { - int current_count = 0; - counts->GetInteger(index, ¤t_count); - counts->Set(index, new base::Value(current_count + 1)); +void IncrementListValue(base::Value* counts, int index) { + counts->GetList()[index] = base::Value(counts->GetList()[index].GetInt() + 1); } // Takes an int corresponding to a Type and returns the corresponding flag.
diff --git a/chrome/browser/net/proxy_browsertest.cc b/chrome/browser/net/proxy_browsertest.cc index a4267b0..748cd8f 100644 --- a/chrome/browser/net/proxy_browsertest.cc +++ b/chrome/browser/net/proxy_browsertest.cc
@@ -20,6 +20,7 @@ #include "content/public/browser/notification_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" +#include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/spawned_test_server/spawned_test_server.h"
diff --git a/chrome/browser/prefs/chrome_command_line_pref_store_proxy_unittest.cc b/chrome/browser/prefs/chrome_command_line_pref_store_proxy_unittest.cc index 41e1ebb9..021542e 100644 --- a/chrome/browser/prefs/chrome_command_line_pref_store_proxy_unittest.cc +++ b/chrome/browser/prefs/chrome_command_line_pref_store_proxy_unittest.cc
@@ -15,6 +15,7 @@ #include "components/prefs/pref_service.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/sync_preferences/pref_service_mock_factory.h" +#include "content/public/common/content_switches.h" #include "net/proxy/proxy_config_service_common_unittest.h" #include "url/gurl.h"
diff --git a/chrome/browser/prefs/chrome_command_line_pref_store_unittest.cc b/chrome/browser/prefs/chrome_command_line_pref_store_unittest.cc index f52d8aa..a558c093 100644 --- a/chrome/browser/prefs/chrome_command_line_pref_store_unittest.cc +++ b/chrome/browser/prefs/chrome_command_line_pref_store_unittest.cc
@@ -16,6 +16,7 @@ #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "components/ssl_config/ssl_config_prefs.h" +#include "content/public/common/content_switches.h" #include "ui/base/ui_base_switches.h" namespace {
diff --git a/chrome/browser/prefs/proxy_policy_unittest.cc b/chrome/browser/prefs/proxy_policy_unittest.cc index 3d18802..f202bfac 100644 --- a/chrome/browser/prefs/proxy_policy_unittest.cc +++ b/chrome/browser/prefs/proxy_policy_unittest.cc
@@ -26,6 +26,7 @@ #include "components/proxy_config/proxy_config_pref_names.h" #include "components/sync_preferences/pref_service_mock_factory.h" #include "components/sync_preferences/pref_service_syncable.h" +#include "content/public/common/content_switches.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/resources/print_preview/data/app_state.js b/chrome/browser/resources/print_preview/data/app_state.js index 4abb18e..df06e8b6 100644 --- a/chrome/browser/resources/print_preview/data/app_state.js +++ b/chrome/browser/resources/print_preview/data/app_state.js
@@ -215,9 +215,6 @@ this.state_[AppState.Field.RECENT_DESTINATIONS].length = AppState.NUM_DESTINATIONS_; } - if (!loadTimeData.getBoolean('scalingEnabled')) - this.state_[AppState.Field.SCALING] = 100; - }, /**
diff --git a/chrome/browser/resources/print_preview/print_preview.js b/chrome/browser/resources/print_preview/print_preview.js index 64526ba..2218ae5 100644 --- a/chrome/browser/resources/print_preview/print_preview.js +++ b/chrome/browser/resources/print_preview/print_preview.js
@@ -19,13 +19,6 @@ print_preview.Component.call(this); /** - * Whether the print scaling feature is enabled. - * @type {boolean} - * @private - */ - this.scalingEnabled_ = loadTimeData.getBoolean('scalingEnabled'); - - /** * Used to communicate with Chromium's print system. * @type {!print_preview.NativeLayer} * @private @@ -166,17 +159,15 @@ new print_preview.DpiSettings(this.printTicketStore_.dpi); this.addChild(this.dpiSettings_); - if (this.scalingEnabled_) { - /** - * Component that renders the scaling settings. - * @type {!print_preview.ScalingSettings} - * @private - */ - this.scalingSettings_ = - new print_preview.ScalingSettings(this.printTicketStore_.scaling, - this.printTicketStore_.fitToPage); - this.addChild(this.scalingSettings_); - } + /** + * Component that renders the scaling settings. + * @type {!print_preview.ScalingSettings} + * @private + */ + this.scalingSettings_ = + new print_preview.ScalingSettings(this.printTicketStore_.scaling, + this.printTicketStore_.fitToPage); + this.addChild(this.scalingSettings_); /** * Component that renders miscellaneous print options. @@ -219,11 +210,9 @@ this.marginSettings_, this.colorSettings_, this.dpiSettings_, + this.scalingSettings_, this.otherOptionsSettings_, this.advancedOptionsSettings_]; - if (this.scalingEnabled_) { - settingsSections.splice(8, 0, this.scalingSettings_); - } /** * Component representing more/less settings button. @@ -373,12 +362,10 @@ this.nativeLayer_, print_preview.NativeLayer.EventType.PRINT_PRESET_OPTIONS, this.onPrintPresetOptionsFromDocument_.bind(this)); - if (this.scalingEnabled_) { - this.tracker.add( - this.nativeLayer_, - print_preview.NativeLayer.EventType.PAGE_COUNT_READY, - this.onPageCountReady_.bind(this)); - } + this.tracker.add( + this.nativeLayer_, + print_preview.NativeLayer.EventType.PAGE_COUNT_READY, + this.onPageCountReady_.bind(this)); this.tracker.add( this.nativeLayer_, print_preview.NativeLayer.EventType.PRIVET_PRINT_FAILED, @@ -503,8 +490,7 @@ this.mediaSizeSettings_.decorate($('media-size-settings')); this.marginSettings_.decorate($('margin-settings')); this.dpiSettings_.decorate($('dpi-settings')); - if (this.scalingEnabled_) - this.scalingSettings_.decorate($('scaling-settings')); + this.scalingSettings_.decorate($('scaling-settings')); this.otherOptionsSettings_.decorate($('other-options-settings')); this.advancedOptionsSettings_.decorate($('advanced-options-settings')); this.advancedSettings_.decorate($('advanced-settings')); @@ -532,8 +518,7 @@ this.mediaSizeSettings_.isEnabled = isEnabled; this.marginSettings_.isEnabled = isEnabled; this.dpiSettings_.isEnabled = isEnabled; - if (this.scalingEnabled_) - this.scalingSettings_.isEnabled = isEnabled; + this.scalingSettings_.isEnabled = isEnabled; this.otherOptionsSettings_.isEnabled = isEnabled; this.advancedOptionsSettings_.isEnabled = isEnabled; },
diff --git a/chrome/browser/speech/extension_api/tts_extension_api.cc b/chrome/browser/speech/extension_api/tts_extension_api.cc index 26160e97..bfaf352 100644 --- a/chrome/browser/speech/extension_api/tts_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_extension_api.cc
@@ -138,7 +138,7 @@ details->SetBoolean(constants::kIsFinalEventKey, utterance->finished()); std::unique_ptr<base::ListValue> arguments(new base::ListValue()); - arguments->Set(0, details.release()); + arguments->Append(std::move(details)); std::unique_ptr<extensions::Event> event( new extensions::Event(::extensions::events::TTS_ON_EVENT,
diff --git a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc index 0e0d2a8..88b1503a 100644 --- a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc +++ b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc
@@ -60,6 +60,7 @@ #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_status.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "url/gurl.h" @@ -454,17 +455,22 @@ protected: virtual void SetUp() { - TranslateService::InitializeForTesting(); + // Setup the test environment, including the threads and message loops. This + // must be done before base::ThreadTaskRunnerHandle::Get() is called when + // setting up the net::TestURLRequestContextGetter below. + ChromeRenderViewHostTestHarness::SetUp(); - // Clears the translate script so it is fetched everytime and sets the + // Clears the translate script so it is fetched every time and sets the // expiration delay to a large value by default (in case it was zeroed in a // previous test). + TranslateService::InitializeForTesting(); translate::TranslateDownloadManager* download_manager = translate::TranslateDownloadManager::GetInstance(); download_manager->ClearTranslateScriptForTesting(); download_manager->SetTranslateScriptExpirationDelay(60 * 60 * 1000); + download_manager->set_request_context(new net::TestURLRequestContextGetter( + base::ThreadTaskRunnerHandle::Get())); - ChromeRenderViewHostTestHarness::SetUp(); InfoBarService::CreateForWebContents(web_contents()); ChromeTranslateClient::CreateForWebContents(web_contents()); ChromeTranslateClient::FromWebContents(web_contents())
diff --git a/chrome/browser/ui/app_list/search_answer_web_contents_delegate.cc b/chrome/browser/ui/app_list/search_answer_web_contents_delegate.cc index 2192ba0..e7f3ec2 100644 --- a/chrome/browser/ui/app_list/search_answer_web_contents_delegate.cc +++ b/chrome/browser/ui/app_list/search_answer_web_contents_delegate.cc
@@ -34,9 +34,11 @@ profile, content::SiteInstance::Create(profile)))), answer_server_url_(switches::AnswerServerUrl()) { + content::RendererPreferences* renderer_prefs = + web_contents_->GetMutableRendererPrefs(); + renderer_prefs->can_accept_load_drops = false; // We need the OpenURLFromTab() to get called. - web_contents_->GetMutableRendererPrefs() - ->browser_handles_all_top_level_requests = true; + renderer_prefs->browser_handles_all_top_level_requests = true; web_contents_->GetRenderViewHost()->SyncRendererPrefs(); Observe(web_contents_.get()); @@ -76,9 +78,11 @@ replacements.SetQueryStr(prefixed_query); current_request_url_ = answer_server_url_.ReplaceComponents(replacements); - web_contents_->GetController().LoadURL( - current_request_url_, content::Referrer(), - ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); + content::NavigationController::LoadURLParams load_params( + current_request_url_); + load_params.transition_type = ui::PAGE_TRANSITION_AUTO_TOPLEVEL; + load_params.should_clear_history_list = true; + web_contents_->GetController().LoadURLWithParams(load_params); // We are going to call WebContents::GetPreferredSize(). web_contents_->GetRenderViewHost()->EnablePreferredSizeMode();
diff --git a/chrome/browser/ui/cocoa/fullscreen/fullscreen_menubar_tracker.mm b/chrome/browser/ui/cocoa/fullscreen/fullscreen_menubar_tracker.mm index 62f76a830..b9c1486 100644 --- a/chrome/browser/ui/cocoa/fullscreen/fullscreen_menubar_tracker.mm +++ b/chrome/browser/ui/cocoa/fullscreen/fullscreen_menubar_tracker.mm
@@ -6,9 +6,11 @@ #include <Carbon/Carbon.h> +#include "base/mac/mac_util.h" #include "base/macros.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #import "chrome/browser/ui/cocoa/fullscreen/fullscreen_toolbar_controller.h" +#import "chrome/browser/ui/cocoa/fullscreen/fullscreen_toolbar_visibility_lock_controller.h" #include "ui/base/cocoa/appkit_utils.h" namespace { @@ -136,8 +138,23 @@ else if (progress > menubarFraction_) state_ = FullscreenMenubarState::SHOWING; - menubarFraction_ = progress; + // In 10.12. the toolbar to be janky since the UI doesn't update until the + // menubar finished revealing itself. To smooth things out, animate the + // toolbar in/out by locking/releasing its visibility instead of relying on + // the menubar fraction. + // TODO(spqchan): Figure out why it's not updating and make the toolbar drop + // down in sync with the menubar. See crbug.com/672254. + if (base::mac::IsOS10_12()) { + if (state_ == FullscreenMenubarState::SHOWING) { + [[owner_ visibilityLockController] lockToolbarVisibilityForOwner:self + withAnimation:YES]; + } else if (state_ == FullscreenMenubarState::HIDING) { + [[owner_ visibilityLockController] releaseToolbarVisibilityForOwner:self + withAnimation:YES]; + } + } + menubarFraction_ = progress; [owner_ updateToolbarLayout]; } @@ -149,6 +166,8 @@ - (void)activeSpaceDidChange:(NSNotification*)notification { menubarFraction_ = 0.0; state_ = FullscreenMenubarState::HIDDEN; + [[owner_ visibilityLockController] releaseToolbarVisibilityForOwner:self + withAnimation:NO]; [owner_ updateToolbarLayout]; }
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h index bc1e235..dc0758e 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h
@@ -139,6 +139,13 @@ // Handles the |event| that caused |controlView| to become firstResponder. - (void)handleFocusEvent:(NSEvent*)event ofView:(AutocompleteTextField*)controlView; + +// Returns the index of |decoration| as a leading decoration, if it is one. The +// leading-most decoration is at index zero, and increasing indices are closer +// to the start of the omnibox text field. Returns -1 if |decoration| is not a +// leading decoration. +- (int)leadingDecorationIndex:(LocationBarDecoration*)decoration; + @end // Methods which are either only for testing, or only public for testing.
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm index fade689..e09ee0d 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm
@@ -736,6 +736,13 @@ } } +- (int)leadingDecorationIndex:(LocationBarDecoration*)decoration { + for (size_t i = 0; i < leadingDecorations_.size(); ++i) + if (leadingDecorations_[i] == decoration) + return leadingDecorations_.size() - (i + 1); + return -1; +} + @end @implementation AutocompleteTextFieldCell (TestingAPI)
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h index f79f8dc..f0df678 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h
@@ -148,8 +148,10 @@ void OnAccessibilityViewAction(); // Called when the omnibox decoration changes state to update the - // accessibility view's attributes to match. - void UpdateAccessibilityView(); + // accessibility view's attributes to match. The |apparent_frame| rectangle is + // the frame the accessibility view should appear at visually (which may be + // different from its frame in the Cocoa sense). + void UpdateAccessibilityView(NSRect apparent_frame); DecorationMouseState state() const { return state_; }
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm index 7182d5e4..5e8d18d 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_decoration.mm
@@ -38,6 +38,7 @@ // VoiceOver. @interface DecorationAccessibilityView : NSButton { LocationBarDecoration* owner_; // weak + NSRect apparentFrame_; } // NSView: @@ -49,6 +50,8 @@ // This method is called when this DecorationAccessibilityView is activated. - (void)actionDidHappen; + +- (void)setApparentFrame:(NSRect)r; @end @implementation DecorationAccessibilityView @@ -60,6 +63,7 @@ self->owner_ = owner; [self setAction:@selector(actionDidHappen)]; [self setTarget:self]; + self->apparentFrame_ = NSZeroRect; } return self; } @@ -67,11 +71,7 @@ - (BOOL)acceptsFirstResponder { // This NSView is only focusable if the owning LocationBarDecoration can // accept mouse presses. - // TODO(ellyjones): Once the key view loop order in ToolbarController is fixed - // up properly (which will require some redesign of - // LocationBarViewMac::GetDecorationAccessibilityViews()), this method should - // honor |owner_->AcceptsMousePress()|. See https://crbug.com/623883. - return NO; + return owner_->AcceptsMousePress() ? YES : NO; } - (void)drawRect:(NSRect)dirtyRect { @@ -92,6 +92,21 @@ return label ? label : owner_->GetToolTip(); } +- (void)setApparentFrame:(NSRect)r { + apparentFrame_ = r; +} + +// The focus ring (and all other visuals) should be positioned using the +// apparent frame, not the real frame, because of the hack in +// LocationBarViewMac::UpdateAccessibilityView(). +- (void)drawFocusRingMask { + NSRectFill([self focusRingMaskBounds]); +} + +- (NSRect)focusRingMaskBounds { + return [[self superview] convertRect:apparentFrame_ toView:self]; +} + @end @interface DecorationMouseTrackingDelegate : NSObject { @@ -163,8 +178,10 @@ return NSInsetRect(frame, 0.0, kBackgroundFrameYInset); } -void LocationBarDecoration::UpdateAccessibilityView() { - [accessibility_view_.get() setEnabled:AcceptsMousePress()]; +void LocationBarDecoration::UpdateAccessibilityView(NSRect apparent_frame) { + auto v = static_cast<DecorationAccessibilityView*>(accessibility_view_); + [accessibility_view_ setEnabled:AcceptsMousePress()]; + [v setApparentFrame:apparent_frame]; } void LocationBarDecoration::DrawInFrame(NSRect frame, NSView* control_view) {
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm index 4b59a6a..855e5e1 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm
@@ -742,11 +742,36 @@ LocationBarDecoration* decoration) { if (!decoration->IsVisible()) return; - NSRect r = + NSRect apparent_frame = [[field_ cell] frameForDecoration:decoration inFrame:[field_ frame]]; - [decoration->GetAccessibilityView() setFrame:r]; - [decoration->GetAccessibilityView() setNeedsDisplayInRect:r]; - decoration->UpdateAccessibilityView(); + + // This is a bit subtle: + // The decorations' accessibility views can become key to allow keyboard + // access to the location bar decorations, but Cocoa's automatic key view loop + // sorts by top-left coordinate. Since the omnibox's top-left coordinate is + // before its leading decorations, the omnibox would sort before its own + // leading decorations, which was logical but visually unintuitive. Therefore, + // for leading decorations, this method moves their frame to be "just before" + // the omnibox in automatic key view loop order, and gives them an apparent + // frame (see DecorationAccessibilityView) so that they still paint their + // focus rings at the right place. + // + // TODO(lgrey): This hack doesn't work in RTL layouts, but the layout of the + // omnibox is currently screwed up in RTL layouts anyway. See + // https://crbug.com/715627. + NSRect real_frame = apparent_frame; + int left_index = [[field_ cell] leadingDecorationIndex:decoration]; + + // If there are ever too many leading views, the fake x-coords might land + // before the button preceding the omnibox in the key view order. This + // threshold is just a guess. + DCHECK_LT(left_index, 10); + if (left_index != -1) + real_frame.origin.x = [field_ frame].origin.x - left_index - 1; + + decoration->UpdateAccessibilityView(apparent_frame); + [decoration->GetAccessibilityView() setFrame:real_frame]; + [decoration->GetAccessibilityView() setNeedsDisplayInRect:apparent_frame]; } std::vector<LocationBarDecoration*> LocationBarViewMac::GetDecorations() {
diff --git a/chrome/browser/ui/views/payments/payment_sheet_view_controller.cc b/chrome/browser/ui/views/payments/payment_sheet_view_controller.cc index 136622b..f2a8b69a72 100644 --- a/chrome/browser/ui/views/payments/payment_sheet_view_controller.cc +++ b/chrome/browser/ui/views/payments/payment_sheet_view_controller.cc
@@ -207,108 +207,122 @@ return std::move(row); } -// Creates a row with a button in place of the chevron. -// +------------------------------------------+ -// | Name | content_view | button_string | -// +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ -std::unique_ptr<views::Button> CreatePaymentSheetRowWithButton( - views::ButtonListener* listener, - const base::string16& section_name, - std::unique_ptr<views::View> content_view, - const base::string16& button_string, - int button_tag, - int button_id, - int name_column_width) { - std::unique_ptr<views::Button> button( - views::MdTextButton::CreateSecondaryUiBlueButton(listener, - button_string)); - button->set_tag(button_tag); - button->set_id(button_id); - return CreatePaymentSheetRow(listener, section_name, std::move(content_view), - nullptr, std::move(button), - /*clickable=*/false, name_column_width); -} +// A class used to build Payment Sheet Rows. Construct an instance of it, chain +// calls to argument-setting functions, then call one of the CreateWith* +// functions to create the row view. +class PaymentSheetRowBuilder { + public: + PaymentSheetRowBuilder(views::ButtonListener* listener, + const base::string16& section_name, + int name_column_width) + : listener_(listener), + section_name_(section_name), + name_column_width_(name_column_width) {} -// Creates a row with a button in place of the chevron and |truncated_content| -// between |section_name| and the button. -// +------------------------------------------+ -// | Name | truncated_content | button_string | -// +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ -std::unique_ptr<views::Button> CreatePaymentSheetRowWithButton( - views::ButtonListener* listener, - const base::string16& section_name, - const base::string16& truncated_content, - const base::string16& button_string, - int button_tag, - int button_id, - int name_column_width) { - std::unique_ptr<views::Label> content_view = - base::MakeUnique<views::Label>(truncated_content); - content_view->SetHorizontalAlignment(gfx::ALIGN_LEFT); - return CreatePaymentSheetRowWithButton( - listener, section_name, std::move(content_view), button_string, - button_tag, button_id, name_column_width); -} + PaymentSheetRowBuilder& Tag(PaymentSheetViewControllerTags tag) { + tag_ = static_cast<int>(tag); + return *this; + } -// Creates a row with a button in place of the chevron with the string between -// |section_name| and the button built as "|preview|... and |n| more". -// |format_string| is used to assemble the truncated preview and the rest of the -// content string. -// +----------------------------------------------+ -// | Name | preview... and N more | button_string | -// +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ -std::unique_ptr<views::Button> CreatePaymentSheetRowWithButton( - views::ButtonListener* listener, - const base::string16& section_name, - const base::string16& preview_text, - const base::string16& format_string, - int n, - const base::string16& button_string, - int button_tag, - int button_id, - int name_column_width) { - std::unique_ptr<PreviewEliderLabel> content_view = - base::MakeUnique<PreviewEliderLabel>(preview_text, format_string, n); - content_view->SetHorizontalAlignment(gfx::ALIGN_LEFT); - return CreatePaymentSheetRowWithButton( - listener, section_name, std::move(content_view), button_string, - button_tag, button_id, name_column_width); -} + PaymentSheetRowBuilder& Id(DialogViewID id) { + id_ = static_cast<int>(id); + return *this; + } -// Creates a clickable row to be displayed in the Payment Sheet. It contains -// a section name and some content, followed by a chevron as a clickability -// affordance. Both, either, or none of |content_view| and |extra_content_view| -// may be present, the difference between the two being that content is pinned -// to the left and extra_content is pinned to the right. -// The row also displays a light gray horizontal ruler on its lower boundary. -// The name column has a fixed width equal to |name_column_width|. -// +----------------------------+ -// | Name | Content | Extra | > | -// +~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- ruler -std::unique_ptr<views::Button> CreatePaymentSheetRowWithChevron( - views::ButtonListener* listener, - const base::string16& section_name, - std::unique_ptr<views::View> content_view, - std::unique_ptr<views::View> extra_content_view, - int section_tag, - int section_id, - int name_column_width) { - std::unique_ptr<views::ImageView> chevron = - base::MakeUnique<views::ImageView>(); - chevron->set_can_process_events_within_subtree(false); - std::unique_ptr<views::Label> label = - base::MakeUnique<views::Label>(section_name); - chevron->SetImage(gfx::CreateVectorIcon( - views::kSubmenuArrowIcon, - color_utils::DeriveDefaultIconColor(label->enabled_color()))); - std::unique_ptr<views::Button> section = - CreatePaymentSheetRow(listener, section_name, std::move(content_view), - std::move(extra_content_view), std::move(chevron), - /*clickable=*/true, name_column_width); - section->set_tag(section_tag); - section->set_id(section_id); - return section; -} + // Creates a clickable row to be displayed in the Payment Sheet. It contains + // a section name and some content, followed by a chevron as a clickability + // affordance. Both, either, or none of |content_view| and + // |extra_content_view| may be present, the difference between the two being + // that content is pinned to the left and extra_content is pinned to the + // right. The row also displays a light gray horizontal ruler on its lower + // boundary. The name column has a fixed width equal to |name_column_width|. + // +----------------------------+ + // | Name | Content | Extra | > | + // +~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- ruler + std::unique_ptr<views::Button> CreateWithChevron( + std::unique_ptr<views::View> content_view, + std::unique_ptr<views::View> extra_content_view) { + std::unique_ptr<views::ImageView> chevron = + base::MakeUnique<views::ImageView>(); + chevron->set_can_process_events_within_subtree(false); + std::unique_ptr<views::Label> label = + base::MakeUnique<views::Label>(section_name_); + chevron->SetImage(gfx::CreateVectorIcon( + views::kSubmenuArrowIcon, + color_utils::DeriveDefaultIconColor(label->enabled_color()))); + std::unique_ptr<views::Button> section = + CreatePaymentSheetRow(listener_, section_name_, std::move(content_view), + std::move(extra_content_view), std::move(chevron), + /*clickable=*/true, name_column_width_); + section->set_tag(tag_); + section->set_id(id_); + return section; + } + + // Creates a row with a button in place of the chevron and |truncated_content| + // between |section_name| and the button. + // +------------------------------------------+ + // | Name | truncated_content | button_string | + // +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ + std::unique_ptr<views::Button> CreateWithButton( + const base::string16& truncated_content, + const base::string16& button_string, + bool button_enabled) { + std::unique_ptr<views::Label> content_view = + base::MakeUnique<views::Label>(truncated_content); + content_view->SetHorizontalAlignment(gfx::ALIGN_LEFT); + return CreateWithButton(std::move(content_view), button_string, + button_enabled); + } + + // Creates a row with a button in place of the chevron with the string between + // |section_name| and the button built as "|preview|... and |n| more". + // |format_string| is used to assemble the truncated preview and the rest of + // the content string. + // +----------------------------------------------+ + // | Name | preview... and N more | button_string | + // +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ + std::unique_ptr<views::Button> CreateWithButton( + const base::string16& preview_text, + const base::string16& format_string, + int n, + const base::string16& button_string, + bool button_enabled) { + std::unique_ptr<PreviewEliderLabel> content_view = + base::MakeUnique<PreviewEliderLabel>(preview_text, format_string, n); + content_view->SetHorizontalAlignment(gfx::ALIGN_LEFT); + return CreateWithButton(std::move(content_view), button_string, + button_enabled); + } + + private: + // Creates a row with a button in place of the chevron. + // +------------------------------------------+ + // | Name | content_view | button_string | + // +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ + std::unique_ptr<views::Button> CreateWithButton( + std::unique_ptr<views::View> content_view, + const base::string16& button_string, + bool button_enabled) { + std::unique_ptr<views::Button> button( + views::MdTextButton::CreateSecondaryUiBlueButton(listener_, + button_string)); + button->set_tag(tag_); + button->set_id(id_); + button->SetEnabled(button_enabled); + return CreatePaymentSheetRow(listener_, section_name_, + std::move(content_view), nullptr, + std::move(button), + /*clickable=*/false, name_column_width_); + } + + views::ButtonListener* listener_; + base::string16 section_name_; + int name_column_width_; + int tag_; + int id_; + DISALLOW_COPY_AND_ASSIGN(PaymentSheetRowBuilder); +}; // Creates a GridLayout object to be used in the Order Summary section's list of // items and the list of prices. |host| is the view that will be assigned the @@ -565,15 +579,15 @@ item_summaries->SetLayoutManager(item_summaries_layout.release()); item_amounts->SetLayoutManager(item_amounts_layout.release()); - std::unique_ptr<views::Button> section = CreatePaymentSheetRowWithChevron( + PaymentSheetRowBuilder builder( this, l10n_util::GetStringUTF16(IDS_PAYMENT_REQUEST_ORDER_SUMMARY_SECTION_NAME), - std::move(item_summaries), std::move(item_amounts), - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_ORDER_SUMMARY_BUTTON), - static_cast<int>(DialogViewID::PAYMENT_SHEET_SUMMARY_SECTION), widest_name_column_view_width_); - return section; + builder.Tag(PaymentSheetViewControllerTags::SHOW_ORDER_SUMMARY_BUTTON) + .Id(DialogViewID::PAYMENT_SHEET_SUMMARY_SECTION); + + return builder.CreateWithChevron(std::move(item_summaries), + std::move(item_amounts)); } std::unique_ptr<views::View> @@ -600,27 +614,21 @@ // +----------------------------------------------+ std::unique_ptr<views::Button> PaymentSheetViewController::CreateShippingRow() { std::unique_ptr<views::Button> section; + PaymentSheetRowBuilder builder( + this, GetShippingAddressSectionString(spec()->shipping_type()), + widest_name_column_view_width_); + builder.Tag(PaymentSheetViewControllerTags::SHOW_SHIPPING_BUTTON); if (state()->selected_shipping_profile()) { - section = CreatePaymentSheetRowWithChevron( - this, GetShippingAddressSectionString(spec()->shipping_type()), - CreateShippingSectionContent(), nullptr, - static_cast<int>(PaymentSheetViewControllerTags::SHOW_SHIPPING_BUTTON), - static_cast<int>(DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION), - widest_name_column_view_width_); + builder.Id(DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION); + return builder.CreateWithChevron(CreateShippingSectionContent(), nullptr); } else { + builder.Id(DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON); base::string16 button_string = state()->shipping_profiles().size() ? l10n_util::GetStringUTF16(IDS_CHOOSE) : l10n_util::GetStringUTF16(IDS_ADD); - if (state()->shipping_profiles().empty()) { - section = CreatePaymentSheetRowWithButton( - this, GetShippingAddressSectionString(spec()->shipping_type()), - base::ASCIIToUTF16(""), button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_SHIPPING_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(base::ASCIIToUTF16(""), button_string, + /*button_enabled=*/true); } else if (state()->shipping_profiles().size() == 1) { base::string16 truncated_content = state()->shipping_profiles()[0]->ConstructInferredLabel( @@ -630,14 +638,8 @@ autofill::ADDRESS_HOME_COUNTRY, }, 6, state()->GetApplicationLocale()); - section = CreatePaymentSheetRowWithButton( - this, GetShippingAddressSectionString(spec()->shipping_type()), - truncated_content, button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_SHIPPING_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(truncated_content, button_string, + /*button_enabled=*/true); } else { base::string16 format = l10n_util::GetPluralStringFUTF16( IDS_PAYMENT_REQUEST_SHIPPING_ADDRESSES_PREVIEW, @@ -650,18 +652,11 @@ autofill::ADDRESS_HOME_COUNTRY, }, 6, state()->GetApplicationLocale()); - section = CreatePaymentSheetRowWithButton( - this, GetShippingAddressSectionString(spec()->shipping_type()), label, - format, state()->shipping_profiles().size() - 1, button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_SHIPPING_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_ADDRESS_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton( + label, format, state()->shipping_profiles().size() - 1, button_string, + /*button_enabled=*/true); } } - - return section; } // Creates the Payment Method row, which contains a "Payment" label, the user's @@ -677,11 +672,15 @@ PaymentSheetViewController::CreatePaymentMethodRow() { PaymentInstrument* selected_instrument = state()->selected_instrument(); - std::unique_ptr<views::View> content_view; - std::unique_ptr<views::ImageView> card_icon_view; - std::unique_ptr<views::Button> section; + PaymentSheetRowBuilder builder( + this, + l10n_util::GetStringUTF16( + IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME), + widest_name_column_view_width_); + builder.Tag(PaymentSheetViewControllerTags::SHOW_PAYMENT_METHOD_BUTTON); + if (selected_instrument) { - content_view = base::MakeUnique<views::View>(); + std::unique_ptr<views::View> content_view = base::MakeUnique<views::View>(); views::GridLayout* layout = new views::GridLayout(content_view.get()); content_view->SetLayoutManager(layout); @@ -694,65 +693,35 @@ layout->StartRow(0, 0); layout->AddView(new views::Label(selected_instrument->sublabel())); - card_icon_view = CreateInstrumentIconView( + std::unique_ptr<views::ImageView> card_icon_view = CreateInstrumentIconView( selected_instrument->icon_resource_id(), selected_instrument->label()); card_icon_view->SetImageSize(gfx::Size(32, 20)); - section = CreatePaymentSheetRowWithChevron( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME), - std::move(content_view), std::move(card_icon_view), - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_PAYMENT_METHOD_BUTTON), - static_cast<int>(DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION), - widest_name_column_view_width_); + return builder.Id(DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION) + .CreateWithChevron(std::move(content_view), std::move(card_icon_view)); } else { + builder.Id(DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON); base::string16 button_string = state()->available_instruments().size() ? l10n_util::GetStringUTF16(IDS_CHOOSE) : l10n_util::GetStringUTF16(IDS_ADD); if (state()->available_instruments().empty()) { - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME), - base::ASCIIToUTF16(""), button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_PAYMENT_METHOD_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(base::ASCIIToUTF16(""), button_string, + /*button_enabled=*/true); } else if (state()->available_instruments().size() == 1) { - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME), + return builder.CreateWithButton( state()->available_instruments()[0]->label(), button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_PAYMENT_METHOD_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON), - widest_name_column_view_width_); + /*button_enabled=*/true); } else { base::string16 format = l10n_util::GetPluralStringFUTF16( IDS_PAYMENT_REQUEST_PAYMENT_METHODS_PREVIEW, state()->available_instruments().size() - 1); - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME), + return builder.CreateWithButton( state()->available_instruments()[0]->label(), format, state()->available_instruments().size() - 1, button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_PAYMENT_METHOD_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_PAYMENT_METHOD_SECTION_BUTTON), - widest_name_column_view_width_); + /*button_enabled=*/true); } } - - return section; } std::unique_ptr<views::View> @@ -773,33 +742,24 @@ // +----------------------------------------------+ std::unique_ptr<views::Button> PaymentSheetViewController::CreateContactInfoRow() { - std::unique_ptr<views::Button> section; + PaymentSheetRowBuilder builder( + this, + l10n_util::GetStringUTF16(IDS_PAYMENT_REQUEST_CONTACT_INFO_SECTION_NAME), + widest_name_column_view_width_); + builder.Tag(PaymentSheetViewControllerTags::SHOW_CONTACT_INFO_BUTTON); + if (state()->selected_contact_profile()) { - section = CreatePaymentSheetRowWithChevron( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_CONTACT_INFO_SECTION_NAME), - CreateContactInfoSectionContent(), nullptr, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_CONTACT_INFO_BUTTON), - static_cast<int>(DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION), - widest_name_column_view_width_); + return builder.Id(DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION) + .CreateWithChevron(CreateContactInfoSectionContent(), nullptr); } else { + builder.Id(DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON); base::string16 button_string = state()->contact_profiles().size() ? l10n_util::GetStringUTF16(IDS_CHOOSE) : l10n_util::GetStringUTF16(IDS_ADD); if (state()->contact_profiles().empty()) { - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_CONTACT_INFO_SECTION_NAME), - base::ASCIIToUTF16(""), button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_CONTACT_INFO_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(base::ASCIIToUTF16(""), button_string, + /*button_enabled=*/true); } else if (state()->contact_profiles().size() == 1) { base::string16 truncated_content = state()->contact_profiles()[0]->ConstructInferredLabel( @@ -809,16 +769,8 @@ autofill::ADDRESS_HOME_COUNTRY, }, 6, state()->GetApplicationLocale()); - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_CONTACT_INFO_SECTION_NAME), - truncated_content, button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_CONTACT_INFO_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(truncated_content, button_string, + /*button_enabled=*/true); } else { base::string16 preview = state()->contact_profiles()[0]->ConstructInferredLabel( @@ -831,31 +783,36 @@ base::string16 format = l10n_util::GetPluralStringFUTF16( IDS_PAYMENT_REQUEST_CONTACTS_PREVIEW, state()->contact_profiles().size() - 1); - section = CreatePaymentSheetRowWithButton( - this, - l10n_util::GetStringUTF16( - IDS_PAYMENT_REQUEST_CONTACT_INFO_SECTION_NAME), - preview, format, state()->contact_profiles().size() - 1, - button_string, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_CONTACT_INFO_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_CONTACT_INFO_SECTION_BUTTON), - widest_name_column_view_width_); + return builder.CreateWithButton(preview, format, + state()->contact_profiles().size() - 1, + button_string, /*button_enabled=*/true); } } - - return section; } std::unique_ptr<views::Button> PaymentSheetViewController::CreateShippingOptionRow() { + // The Shipping Options row has many different ways of being displayed + // depending on the state of the dialog and Payment Request. + // 1. There is a selected shipping address. The website updated the shipping + // options. + // 1.1 There are no available shipping options: don't display the row. + // 1.2 There are options and one is selected: display the row with the + // selection's label and a chevron. + // 1.3 There are options and none is selected: display a row with a + // choose button and the string "|preview of first option| and N more" + // 2. There is no selected shipping address: display a row with the string + // "Choose an address" and a disabled Choose button. mojom::PaymentShippingOption* selected_option = spec()->selected_shipping_option(); // The shipping option section displays the currently selected option if there // is one. It's not possible to select an option without selecting an address // first. - std::unique_ptr<views::Button> section; + PaymentSheetRowBuilder builder( + this, GetShippingOptionSectionString(spec()->shipping_type()), + widest_name_column_view_width_); + builder.Tag(PaymentSheetViewControllerTags::SHOW_SHIPPING_OPTION_BUTTON); + if (state()->selected_shipping_profile()) { if (spec()->details().shipping_options.empty()) { // TODO(anthonyvd): Display placeholder if there's no available shipping @@ -863,36 +820,35 @@ return nullptr; } - std::unique_ptr<views::View> option_row_content = - current_update_reason_ == - PaymentRequestSpec::UpdateReason::SHIPPING_OPTION - ? CreateCheckingSpinnerView() - : CreateShippingOptionLabel( - selected_option, selected_option - ? spec()->GetFormattedCurrencyAmount( - selected_option->amount->value) - : base::ASCIIToUTF16("")); - section = CreatePaymentSheetRowWithChevron( - this, GetShippingOptionSectionString(spec()->shipping_type()), - std::move(option_row_content), nullptr, - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_SHIPPING_OPTION_BUTTON), - static_cast<int>(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION), - widest_name_column_view_width_); + if (selected_option) { + std::unique_ptr<views::View> option_row_content = + current_update_reason_ == + PaymentRequestSpec::UpdateReason::SHIPPING_OPTION + ? CreateCheckingSpinnerView() + : CreateShippingOptionLabel(selected_option, + spec()->GetFormattedCurrencyAmount( + selected_option->amount->value)); + return builder.Id(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION) + .CreateWithChevron(std::move(option_row_content), nullptr); + } else { + return builder + .Id(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION_BUTTON) + .CreateWithButton( + base::UTF8ToUTF16(spec()->details().shipping_options[0]->label), + l10n_util::GetPluralStringFUTF16( + IDS_PAYMENT_REQUEST_SHIPPING_OPTIONS_PREVIEW, + spec()->details().shipping_options.size() - 1), + spec()->details().shipping_options.size() - 1, + l10n_util::GetStringUTF16(IDS_CHOOSE), + /*button_enabled=*/true); + } } else { - // TODO(anthonyvd): This should be a disabled row with a disabled button and - // some text to indicate that an address must be selected first. - section = CreatePaymentSheetRowWithButton( - this, GetShippingOptionSectionString(spec()->shipping_type()), - base::ASCIIToUTF16(""), l10n_util::GetStringUTF16(IDS_CHOOSE), - static_cast<int>( - PaymentSheetViewControllerTags::SHOW_SHIPPING_OPTION_BUTTON), - static_cast<int>( - DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION_BUTTON), - widest_name_column_view_width_); + return builder + .Id(DialogViewID::PAYMENT_SHEET_SHIPPING_OPTION_SECTION_BUTTON) + .CreateWithButton( + l10n_util::GetStringUTF16(IDS_PAYMENT_REQUEST_CHOOSE_AN_ADDRESS), + l10n_util::GetStringUTF16(IDS_CHOOSE), /*button_enabled=*/false); } - - return section; } } // namespace payments
diff --git a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc index 955e77b..69e4a1f 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_ui.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_ui.cc
@@ -413,13 +413,9 @@ source->AddLocalizedString("moreOptionsLabel", IDS_MORE_OPTIONS_LABEL); source->AddLocalizedString("lessOptionsLabel", IDS_LESS_OPTIONS_LABEL); - bool scaling_enabled = base::FeatureList::IsEnabled(features::kPrintScaling); - source->AddBoolean("scalingEnabled", scaling_enabled); - bool print_pdf_as_image_enabled = base::FeatureList::IsEnabled( features::kPrintPdfAsImage); source->AddBoolean("printPdfAsImageEnabled", print_pdf_as_image_enabled); - #if defined(OS_CHROMEOS) bool cups_and_md_settings_enabled = !base::CommandLine::ForCurrentProcess()->HasSwitch(
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index dc19f25..ea067f4 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -267,13 +267,10 @@ base::FEATURE_ENABLED_BY_DEFAULT}; #endif -// Enables the Print Scaling feature in print preview. #if BUILDFLAG(ENABLE_PRINT_PREVIEW) +// Enables the Print as Image feature in print preview. const base::Feature kPrintPdfAsImage{"PrintPdfAsImage", base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kPrintScaling{"PrintScaling", - base::FEATURE_DISABLED_BY_DEFAULT}; #endif // Enables or disables push subscriptions keeping Chrome running in the
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 71eea375..f61a23d9 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -150,8 +150,6 @@ #if BUILDFLAG(ENABLE_PRINT_PREVIEW) extern const base::Feature kPrintPdfAsImage; - -extern const base::Feature kPrintScaling; #endif extern const base::Feature kPushMessagingBackgroundMode;
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index d3a7262..53bcd053 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -727,11 +727,6 @@ // Uses the pac script at the given URL const char kProxyPacUrl[] = "proxy-pac-url"; -// Uses a specified proxy server, overrides system settings. This switch only -// affects HTTP and HTTPS requests. ARC-apps use only HTTP proxy server with the -// highest priority. -const char kProxyServer[] = "proxy-server"; - // Specifies a comma separated list of QUIC connection options to send to // the server. const char kQuicConnectionOptions[] = "quic-connection-options";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 8404b98b..66adeb74 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -207,7 +207,6 @@ extern const char kProxyAutoDetect[]; extern const char kProxyBypassList[]; extern const char kProxyPacUrl[]; -extern const char kProxyServer[]; extern const char kQuicConnectionOptions[]; extern const char kQuicMaxPacketLength[]; extern const char kQuicVersion[];
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 8aeb6fa..961fd6b 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -9,7 +9,6 @@ import("//build/config/ui.gni") import("//chrome/common/features.gni") import("//chrome/chrome_repack_locales.gni") -import("//chrome/test/base/js2gtest.gni") import("//components/os_crypt/features.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//extensions/features/features.gni") @@ -462,7 +461,6 @@ ldflags = [] deps = [ - ":interactive_ui_tests_js_webui", ":test_support", ":test_support_ui", "//chrome:packed_resources", @@ -471,6 +469,7 @@ "//chrome/browser", "//chrome/browser/devtools", "//chrome/renderer", + "//chrome/test/data/webui:interactive_ui_tests_js_webui", "//components/resources", "//components/sync", "//components/sync:test_support_model", @@ -926,165 +925,6 @@ } } - js2gtest("interactive_ui_tests_js_webui") { - test_type = "webui" - - sources = [ - "data/webui/cr_elements/cr_elements_focus_test.js", - "data/webui/md_history/md_history_focus_test.js", - "data/webui/settings/cr_settings_interactive_ui_tests.js", - ] - - gen_include_files = [ - "data/webui/polymer_browser_test_base.js", - "data/webui/polymer_interactive_ui_test.js", - ] - - deps = [ - "//chrome/browser/ui", - ] - - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - } - - js2gtest("browser_tests_js_webui") { - test_type = "webui" - - # Javascript sources. These are combined with the .cc files in the GYP build - # and are handled by a rule, but in the GN build they're in a separate - # action so need to be separated out. - sources = [ - "../browser/ui/webui/app_list/start_page_browsertest.js", - "../browser/ui/webui/chromeos/bluetooth_pairing_ui_browsertest.js", - "../browser/ui/webui/chromeos/certificate_manager_dialog_browsertest.js", - "../browser/ui/webui/chromeos/set_time_ui_browsertest.js", - "../browser/ui/webui/extensions/chromeos/kiosk_apps_browsertest.js", - "../browser/ui/webui/extensions/extension_settings_browsertest.js", - "../browser/ui/webui/help/help_browsertest.js", - "../browser/ui/webui/identity_internals_ui_browsertest.js", - "../browser/ui/webui/options/autofill_options_browsertest.js", - "../browser/ui/webui/options/browser_options_browsertest.js", - "../browser/ui/webui/options/certificate_manager_browsertest.js", - "../browser/ui/webui/options/chromeos/accounts_options_browsertest.js", - "../browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js", - "../browser/ui/webui/options/chromeos/date_time_options_browsertest.js", - "../browser/ui/webui/options/chromeos/guest_mode_options_browsertest.js", - "../browser/ui/webui/options/chromeos/power_overlay_browsertest.js", - "../browser/ui/webui/options/content_options_browsertest.js", - "../browser/ui/webui/options/content_settings_exception_area_browsertest.js", - "../browser/ui/webui/options/cookies_view_browsertest.js", - "../browser/ui/webui/options/edit_dictionary_browsertest.js", - "../browser/ui/webui/options/font_settings_browsertest.js", - "../browser/ui/webui/options/language_options_browsertest.js", - "../browser/ui/webui/options/language_options_dictionary_download_browsertest.js", - "../browser/ui/webui/options/manage_profile_browsertest.js", - "../browser/ui/webui/options/multilanguage_options_webui_browsertest.js", - "../browser/ui/webui/options/options_browsertest.js", - "../browser/ui/webui/options/options_browsertest_base.js", - "../browser/ui/webui/options/password_manager_browsertest.js", - "../browser/ui/webui/options/profile_settings_reset_browsertest.js", - "../browser/ui/webui/options/search_engine_manager_browsertest.js", - "../browser/ui/webui/options/settings_format_browsertest.js", - "../browser/ui/webui/options/startup_page_list_browsertest.js", - "../browser/ui/webui/sync_internals_browsertest.js", - "../browser/ui/webui/sync_setup_browsertest.js", - "data/chromeos/oobe_webui_browsertest.js", - "data/webui/about_invalidations_browsertest.js", - "data/webui/accessibility_audit_browsertest.js", - "data/webui/assertions.js", - "data/webui/async_gen.js", - "data/webui/bluetooth_internals_browsertest.js", - "data/webui/certificate_viewer_dialog_test.js", - "data/webui/chrome_send_browsertest.js", - "data/webui/cr_elements/cr_elements_browsertest.js", - "data/webui/extensions/cr_extensions_browsertest.js", - "data/webui/history_browsertest.js", - "data/webui/md_bookmarks/md_bookmarks_browsertest.js", - "data/webui/md_downloads/downloads_browsertest.js", - "data/webui/md_history/md_history_browsertest.js", - "data/webui/md_user_manager/user_manager_browsertest.js", - "data/webui/media_router/media_router_elements_browsertest.js", - "data/webui/mock4js_browsertest.js", - "data/webui/net_internals/bandwidth_view.js", - "data/webui/net_internals/chromeos_view.js", - "data/webui/net_internals/dns_view.js", - "data/webui/net_internals/events_view.js", - "data/webui/net_internals/hsts_view.js", - "data/webui/net_internals/log_util.js", - "data/webui/net_internals/log_view_painter.js", - "data/webui/net_internals/main.js", - "data/webui/net_internals/net_internals_test.js", - "data/webui/net_internals/prerender_view.js", - "data/webui/net_internals/sdch_view.js", - "data/webui/net_internals/timeline_view.js", - "data/webui/ntp4.js", - "data/webui/polymer_browser_test_base.js", - "data/webui/print_preview.js", - "data/webui/print_preview_destination_search_test.js", - "data/webui/sandboxstatus_browsertest.js", - "data/webui/text_defaults_browsertest.js", - "data/webui/webui_resource_async_browsertest.js", - ] - - if (!is_asan) { - sources += [ - "data/webui/settings/advanced_page_browsertest.js", - "data/webui/settings/animation_browsertest.js", - "data/webui/settings/basic_page_browsertest.js", - "data/webui/settings/cr_settings_browsertest.js", - "data/webui/settings/help_page_browsertest.js", - "data/webui/settings/languages_page_browsertest.js", - "data/webui/settings/on_startup_browsertest.js", - "data/webui/settings/passwords_and_autofill_fake_data.js", - "data/webui/settings/passwords_and_forms_browsertest.js", - "data/webui/settings/settings_autofill_section_browsertest.js", - "data/webui/settings/settings_idle_load_browsertest.js", - "data/webui/settings/settings_page_browsertest.js", - "data/webui/settings/settings_passwords_section_browsertest.js", - "data/webui/settings/settings_subpage_browsertest.js", - "data/webui/settings/settings_ui_browsertest.js", - "data/webui/settings/site_settings_page_browsertest.js", - ] - - if (is_chromeos) { - sources += [ "data/webui/settings/easy_unlock_browsertest_chromeos.js" ] - } - } - - if (is_chrome_branded) { - # crbug.com/230471 - sources -= [ "data/webui/accessibility_audit_browsertest.js" ] - } - if (!is_chromeos) { - sources -= [ "data/webui/certificate_viewer_dialog_test.js" ] - } else { - sources -= [ "data/webui/md_user_manager/user_manager_browsertest.js" ] - } - if (is_mac) { - sources -= [ - # TODO(rouslan): This test depends on the custom dictionary UI, - # which is disabled on Mac. - "../browser/ui/webui/options/edit_dictionary_browsertest.js", - - # TODO(rouslan): This test depends on hunspell and we cannot run it - # on Mac, which does not use hunspell by default. - "../browser/ui/webui/options/language_options_dictionary_download_browsertest.js", - "../browser/ui/webui/options/multilanguage_options_webui_browsertest.js", - ] - } - if (!enable_app_list) { - sources -= [ "../browser/ui/webui/app_list/start_page_browsertest.js" ] - } - if (!enable_print_preview) { - sources -= [ "data/webui/print_preview.js" ] - } - deps = [ - "//chrome/browser/ui", - "//skia", - ] - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - } - group("telemetry_unittests") { testonly = true deps = [ @@ -1885,7 +1725,6 @@ ] deps += [ - ":browser_tests_js_webui", ":sync_integration_test_support", ":test_support_ui", "//base:i18n", @@ -1896,6 +1735,7 @@ "//chrome:strings", "//chrome/browser", "//chrome/renderer", + "//chrome/test/data/webui:browser_tests_js_webui", "//chrome/test/media_router:media_router_browsertests", "//components/autofill/content/browser:risk_proto", "//components/autofill/content/renderer:test_support", @@ -3022,36 +2862,6 @@ ] } -js2gtest("unit_tests_js") { - test_type = "unit" - sources = [ - "../browser/resources/md_downloads/action_service_unittest.gtestjs", - "../browser/resources/print_preview/data/measurement_system_unittest.gtestjs", - "../browser/resources/print_preview/print_preview_utils_unittest.gtestjs", - "../renderer/resources/extensions/notifications_custom_bindings.gtestjs", - "../test/data/unit/framework_unittest.gtestjs", - ] - extra_js_files = [ - "../browser/resources/md_downloads/action_service.js", - "../browser/resources/print_preview/data/measurement_system.js", - "../browser/resources/print_preview/print_preview_utils.js", - "../renderer/resources/extensions/notifications_custom_bindings.js", - "../renderer/resources/extensions/notifications_test_util.js", - "//ui/webui/resources/js/cr.js", - ] - if (is_chromeos) { - sources += [ - "../browser/resources/chromeos/braille_ime/braille_ime_unittest.gtestjs", - "../browser/resources/chromeos/select_to_speak/select_to_speak_unittest.gtestjs", - ] - extra_js_files += [ - "../browser/resources/chromeos/braille_ime/braille_ime.js", - "../browser/resources/chromeos/select_to_speak/select_to_speak.js", - "../browser/resources/chromeos/select_to_speak/test_support.js", - ] - } -} - test("unit_tests") { sources = [ # histograms.xml is analyzed by AboutFlagsHistogramTest, so this @@ -3843,7 +3653,7 @@ "../utility/media_router/dial_device_description_parser_impl_unittest.cc", ] deps += [ - ":unit_tests_js", + "//chrome/test/data/webui:unit_tests_js", "//components/bubble:test_support", ] data += [
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.cc b/chrome/test/chromedriver/chrome/web_view_impl.cc index 219427c..15245042 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl.cc
@@ -371,13 +371,13 @@ Status WebViewImpl::DispatchTouchEvent(const TouchEvent& event) { base::DictionaryValue params; params.SetString("type", GetAsString(event.type)); - std::unique_ptr<base::ListValue> point_list(new base::ListValue); - std::unique_ptr<base::DictionaryValue> point(new base::DictionaryValue); + auto point = base::MakeUnique<base::DictionaryValue>(); point->SetString("state", GetPointStateString(event.type)); point->SetInteger("x", event.x); point->SetInteger("y", event.y); - point_list->Set(0, point.release()); - params.Set("touchPoints", point_list.release()); + auto point_list = base::MakeUnique<base::ListValue>(); + point_list->Append(std::move(point)); + params.Set("touchPoints", std::move(point_list)); return client_->SendCommand("Input.dispatchTouchEvent", params); }
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn new file mode 100644 index 0000000..4a14def --- /dev/null +++ b/chrome/test/data/webui/BUILD.gn
@@ -0,0 +1,196 @@ +# 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. + +import("//chrome/common/features.gni") +import("//chrome/test/base/js2gtest.gni") + +js2gtest("interactive_ui_tests_js_webui") { + test_type = "webui" + + sources = [ + "cr_elements/cr_elements_focus_test.js", + "md_history/md_history_focus_test.js", + "settings/cr_settings_interactive_ui_tests.js", + ] + + gen_include_files = [ + "polymer_browser_test_base.js", + "polymer_interactive_ui_test.js", + ] + + deps = [ + "//chrome/browser/ui", + ] + + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] +} + +js2gtest("browser_tests_js_webui") { + test_type = "webui" + + # Javascript sources. These are combined with the .cc files in the GYP build + # and are handled by a rule, but in the GN build they're in a separate + # action so need to be separated out. + sources = [ + "../../../browser/ui/webui/app_list/start_page_browsertest.js", + "../../../browser/ui/webui/chromeos/bluetooth_pairing_ui_browsertest.js", + "../../../browser/ui/webui/chromeos/certificate_manager_dialog_browsertest.js", + "../../../browser/ui/webui/chromeos/set_time_ui_browsertest.js", + "../../../browser/ui/webui/extensions/chromeos/kiosk_apps_browsertest.js", + "../../../browser/ui/webui/extensions/extension_settings_browsertest.js", + "../../../browser/ui/webui/help/help_browsertest.js", + "../../../browser/ui/webui/identity_internals_ui_browsertest.js", + "../../../browser/ui/webui/options/autofill_options_browsertest.js", + "../../../browser/ui/webui/options/browser_options_browsertest.js", + "../../../browser/ui/webui/options/certificate_manager_browsertest.js", + "../../../browser/ui/webui/options/chromeos/accounts_options_browsertest.js", + "../../../browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js", + "../../../browser/ui/webui/options/chromeos/date_time_options_browsertest.js", + "../../../browser/ui/webui/options/chromeos/guest_mode_options_browsertest.js", + "../../../browser/ui/webui/options/chromeos/power_overlay_browsertest.js", + "../../../browser/ui/webui/options/content_options_browsertest.js", + "../../../browser/ui/webui/options/content_settings_exception_area_browsertest.js", + "../../../browser/ui/webui/options/cookies_view_browsertest.js", + "../../../browser/ui/webui/options/edit_dictionary_browsertest.js", + "../../../browser/ui/webui/options/font_settings_browsertest.js", + "../../../browser/ui/webui/options/language_options_browsertest.js", + "../../../browser/ui/webui/options/language_options_dictionary_download_browsertest.js", + "../../../browser/ui/webui/options/manage_profile_browsertest.js", + "../../../browser/ui/webui/options/multilanguage_options_webui_browsertest.js", + "../../../browser/ui/webui/options/options_browsertest.js", + "../../../browser/ui/webui/options/options_browsertest_base.js", + "../../../browser/ui/webui/options/password_manager_browsertest.js", + "../../../browser/ui/webui/options/profile_settings_reset_browsertest.js", + "../../../browser/ui/webui/options/search_engine_manager_browsertest.js", + "../../../browser/ui/webui/options/settings_format_browsertest.js", + "../../../browser/ui/webui/options/startup_page_list_browsertest.js", + "../../../browser/ui/webui/sync_internals_browsertest.js", + "../../../browser/ui/webui/sync_setup_browsertest.js", + "../chromeos/oobe_webui_browsertest.js", + "about_invalidations_browsertest.js", + "accessibility_audit_browsertest.js", + "assertions.js", + "async_gen.js", + "bluetooth_internals_browsertest.js", + "certificate_viewer_dialog_test.js", + "chrome_send_browsertest.js", + "cr_elements/cr_elements_browsertest.js", + "extensions/cr_extensions_browsertest.js", + "history_browsertest.js", + "md_bookmarks/md_bookmarks_browsertest.js", + "md_downloads/downloads_browsertest.js", + "md_history/md_history_browsertest.js", + "md_user_manager/user_manager_browsertest.js", + "media_router/media_router_elements_browsertest.js", + "mock4js_browsertest.js", + "net_internals/bandwidth_view.js", + "net_internals/chromeos_view.js", + "net_internals/dns_view.js", + "net_internals/events_view.js", + "net_internals/hsts_view.js", + "net_internals/log_util.js", + "net_internals/log_view_painter.js", + "net_internals/main.js", + "net_internals/net_internals_test.js", + "net_internals/prerender_view.js", + "net_internals/sdch_view.js", + "net_internals/timeline_view.js", + "ntp4.js", + "polymer_browser_test_base.js", + "print_preview.js", + "print_preview_destination_search_test.js", + "sandboxstatus_browsertest.js", + "text_defaults_browsertest.js", + "webui_resource_async_browsertest.js", + ] + + if (!is_asan) { + sources += [ + "settings/advanced_page_browsertest.js", + "settings/animation_browsertest.js", + "settings/basic_page_browsertest.js", + "settings/cr_settings_browsertest.js", + "settings/help_page_browsertest.js", + "settings/languages_page_browsertest.js", + "settings/on_startup_browsertest.js", + "settings/passwords_and_autofill_fake_data.js", + "settings/passwords_and_forms_browsertest.js", + "settings/settings_autofill_section_browsertest.js", + "settings/settings_idle_load_browsertest.js", + "settings/settings_page_browsertest.js", + "settings/settings_passwords_section_browsertest.js", + "settings/settings_subpage_browsertest.js", + "settings/settings_ui_browsertest.js", + "settings/site_settings_page_browsertest.js", + ] + + if (is_chromeos) { + sources += [ "settings/easy_unlock_browsertest_chromeos.js" ] + } + } + + if (is_chrome_branded) { + # crbug.com/230471 + sources -= [ "accessibility_audit_browsertest.js" ] + } + if (!is_chromeos) { + sources -= [ "certificate_viewer_dialog_test.js" ] + } else { + sources -= [ "md_user_manager/user_manager_browsertest.js" ] + } + if (is_mac) { + sources -= [ + # TODO(rouslan): This test depends on the custom dictionary UI, + # which is disabled on Mac. + "../../../browser/ui/webui/options/edit_dictionary_browsertest.js", + + # TODO(rouslan): This test depends on hunspell and we cannot run it + # on Mac, which does not use hunspell by default. + "../../../browser/ui/webui/options/language_options_dictionary_download_browsertest.js", + "../../../browser/ui/webui/options/multilanguage_options_webui_browsertest.js", + ] + } + if (!enable_app_list) { + sources -= + [ "../../../browser/ui/webui/app_list/start_page_browsertest.js" ] + } + if (!enable_print_preview) { + sources -= [ "print_preview.js" ] + } + deps = [ + "//chrome/browser/ui", + "//skia", + ] + defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] +} + +js2gtest("unit_tests_js") { + test_type = "unit" + sources = [ + "../../../browser/resources/md_downloads/action_service_unittest.gtestjs", + "../../../browser/resources/print_preview/data/measurement_system_unittest.gtestjs", + "../../../browser/resources/print_preview/print_preview_utils_unittest.gtestjs", + "../../../renderer/resources/extensions/notifications_custom_bindings.gtestjs", + "../unit/framework_unittest.gtestjs", + ] + extra_js_files = [ + "../../../browser/resources/md_downloads/action_service.js", + "../../../browser/resources/print_preview/data/measurement_system.js", + "../../../browser/resources/print_preview/print_preview_utils.js", + "../../../renderer/resources/extensions/notifications_custom_bindings.js", + "../../../renderer/resources/extensions/notifications_test_util.js", + "//ui/webui/resources/js/cr.js", + ] + if (is_chromeos) { + sources += [ + "../../../browser/resources/chromeos/braille_ime/braille_ime_unittest.gtestjs", + "../../../browser/resources/chromeos/select_to_speak/select_to_speak_unittest.gtestjs", + ] + extra_js_files += [ + "../../../browser/resources/chromeos/braille_ime/braille_ime.js", + "../../../browser/resources/chromeos/select_to_speak/select_to_speak.js", + "../../../browser/resources/chromeos/select_to_speak/test_support.js", + ] + } +}
diff --git a/chrome/test/data/webui/print_preview.js b/chrome/test/data/webui/print_preview.js index e48f4cec..2743ce8 100644 --- a/chrome/test/data/webui/print_preview.js +++ b/chrome/test/data/webui/print_preview.js
@@ -61,19 +61,15 @@ * @override */ testGenPreamble: function() { - // Enable print scaling and print as image for tests. + // Enable print as image for tests on non Windows/Mac. + GEN('#if !defined(OS_WINDOWS) && !defined(OS_MACOSX)'); GEN(' base::FeatureList::ClearInstanceForTesting();'); GEN(' std::unique_ptr<base::FeatureList>'); GEN(' feature_list(new base::FeatureList);'); - GEN(' char enabled_features[128] = {0};'); - GEN(' strcpy(enabled_features, features::kPrintScaling.name);'); - GEN('#if !defined(OS_WINDOWS) && !defined(OS_MACOSX)'); - GEN(' strcat(strcat(enabled_features, ","), '); - GEN(' features::kPrintPdfAsImage.name);'); - GEN('#endif'); GEN(' feature_list->InitializeFromCommandLine('); - GEN(' enabled_features, std::string());'); + GEN(' features::kPrintPdfAsImage.name, std::string());'); GEN(' base::FeatureList::SetInstance(std::move(feature_list));'); + GEN('#endif'); }, /**
diff --git a/components/bookmarks/browser/bookmark_expanded_state_tracker.cc b/components/bookmarks/browser/bookmark_expanded_state_tracker.cc index dd3070b..d0c6b45 100644 --- a/components/bookmarks/browser/bookmark_expanded_state_tracker.cc +++ b/components/bookmarks/browser/bookmark_expanded_state_tracker.cc
@@ -6,6 +6,9 @@ #include <stdint.h> +#include <utility> +#include <vector> + #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "components/bookmarks/browser/bookmark_model.h" @@ -104,13 +107,14 @@ if (!pref_service_) return; - base::ListValue values; - for (Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i) { - values.Set(values.GetSize(), - new base::Value(base::Int64ToString((*i)->id()))); + std::vector<base::Value> values; + values.reserve(nodes.size()); + for (const auto* node : nodes) { + values.emplace_back(base::Int64ToString(node->id())); } - pref_service_->Set(prefs::kBookmarkEditorExpandedNodes, values); + pref_service_->Set(prefs::kBookmarkEditorExpandedNodes, + base::Value(std::move(values))); } } // namespace bookmarks
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc index 04280b0..5545638f 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc
@@ -78,7 +78,8 @@ int64_t length, base::ListValue* list_update) { int64_t value = GetInt64PrefValue(*list_update, index) + length; - list_update->Set(index, new base::Value(base::Int64ToString(value))); + list_update->Set(index, + base::MakeUnique<base::Value>(base::Int64ToString(value))); } // DailyContentLengthUpdate maintains a data saving pref. The pref is a list
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc index e9a5338..da671d34 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc
@@ -163,13 +163,12 @@ for (size_t i = 0; i < kNumDaysInHistory; ++i) { original_daily_content_length_list->Set( - i, new base::Value(base::SizeTToString(i))); + i, base::MakeUnique<base::Value>(base::SizeTToString(i))); } received_daily_content_length_list->Clear(); for (size_t i = 0; i < kNumDaysInHistory / 2; ++i) { - received_daily_content_length_list->Set( - i, new base::Value(base::SizeTToString(i))); + received_daily_content_length_list->AppendString(base::SizeTToString(i)); } }
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc index 8567157..8d241701 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs_unittest.cc
@@ -39,7 +39,7 @@ PrefService* pref_service) { ListPrefUpdate list(local_state_prefs(), pref_name); for (int64_t i = 0; i < 10L; ++i) { - list->Set(i, new base::Value(base::Int64ToString(i + starting_value))); + list->AppendString(base::Int64ToString(i + starting_value)); } }
diff --git a/components/json_schema/json_schema_validator_unittest_base.cc b/components/json_schema/json_schema_validator_unittest_base.cc index d96544c..d49bb067 100644 --- a/components/json_schema/json_schema_validator_unittest_base.cc +++ b/components/json_schema/json_schema_validator_unittest_base.cc
@@ -398,7 +398,7 @@ ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", JSONSchemaValidator::kArrayItemRequired); - instance->Set(0, new base::Value(42)); + instance->Set(0, base::MakeUnique<base::Value>(42)); instance->AppendInteger(42); ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", JSONSchemaValidator::FormatErrorMessage( @@ -409,10 +409,10 @@ base::DictionaryValue* additional_properties = new base::DictionaryValue(); additional_properties->SetString(schema::kType, schema::kAny); schema->Set(schema::kAdditionalProperties, additional_properties); - instance->Set(0, new base::Value("42")); + instance->Set(0, base::MakeUnique<base::Value>("42")); instance->AppendString("anything"); ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Set(2, new base::ListValue()); + instance->Set(2, base::MakeUnique<base::ListValue>()); ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); additional_properties->SetString(schema::kType, schema::kBoolean); @@ -421,7 +421,7 @@ JSONSchemaValidator::kInvalidType, schema::kBoolean, schema::kArray)); - instance->Set(2, new base::Value(false)); + instance->Set(2, base::MakeUnique<base::Value>(false)); ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); base::ListValue* items_schema = NULL; @@ -435,7 +435,7 @@ // for objects. instance->Set(0, base::MakeUnique<base::Value>()); ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Set(0, new base::Value(42)); + instance->Set(0, base::MakeUnique<base::Value>(42)); ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", JSONSchemaValidator::FormatErrorMessage( JSONSchemaValidator::kInvalidType,
diff --git a/components/offline_pages/core/background/request_coordinator.cc b/components/offline_pages/core/background/request_coordinator.cc index c8ef7ae..78cbccf 100644 --- a/components/offline_pages/core/background/request_coordinator.cc +++ b/components/offline_pages/core/background/request_coordinator.cc
@@ -158,6 +158,23 @@ histogram->Add(effective_connection); } +// Record the network quality at request creation time per namespace. +void RecordNetworkQualityAtRequestStartForFailedRequest( + const ClientId& client_id, + const net::EffectiveConnectionType effective_connection) { + // The histogram below is an expansion of the UMA_HISTOGRAM_ENUMERATION + // macro adapted to allow for a dynamically suffixed histogram name. + // Note: The factory creates and owns the histogram. + base::HistogramBase* histogram = base::LinearHistogram::FactoryGet( + AddHistogramSuffix( + client_id, + "OfflinePages.Background.EffectiveConnectionType.OffliningStartType"), + 1, net::EFFECTIVE_CONNECTION_TYPE_LAST - 1, + net::EFFECTIVE_CONNECTION_TYPE_LAST, + base::HistogramBase::kUmaTargetedHistogramFlag); + histogram->Add(effective_connection); +} + // This should use the same algorithm as we use for OfflinePageItem, so the IDs // are similar. int64_t GenerateOfflineId() { @@ -207,6 +224,7 @@ scheduler_(std::move(scheduler)), policy_controller_(new ClientPolicyController()), network_quality_estimator_(network_quality_estimator), + network_quality_at_request_start_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN), active_request_id_(0), last_offlining_status_(Offliner::RequestStatus::UNKNOWN), scheduler_callback_(base::Bind(&EmptySchedulerCallback)), @@ -398,7 +416,7 @@ weak_ptr_factory_.GetWeakPtr(), callback, RequestNotifier::BackgroundSavePageResult::REMOVED)); - // Record the network quality when this request is made. + // Record the network quality when this request is removed. if (network_quality_estimator_) { UMA_HISTOGRAM_ENUMERATION( "OfflinePages.Background.EffectiveConnectionType.RemoveRequests", @@ -427,7 +445,7 @@ base::Bind(&RequestCoordinator::UpdateMultipleRequestsCallback, weak_ptr_factory_.GetWeakPtr())); - // Record the network quality when this request is made. + // Record the network quality when this request is paused. if (network_quality_estimator_) { UMA_HISTOGRAM_ENUMERATION( "OfflinePages.Background.EffectiveConnectionType.PauseRequests", @@ -448,7 +466,7 @@ base::Bind(&RequestCoordinator::UpdateMultipleRequestsCallback, weak_ptr_factory_.GetWeakPtr())); - // Record the network quality when this request is made. + // Record the network quality when this request is resumed. if (network_quality_estimator_) { UMA_HISTOGRAM_ENUMERATION( "OfflinePages.Background.EffectiveConnectionType.ResumeRequests", @@ -876,6 +894,8 @@ } active_request_id_ = request_id; + network_quality_at_request_start_ = + network_quality_estimator_->GetEffectiveConnectionType(); // Start the load and save process in the offliner (Async). if (offliner_->LoadAndSave( @@ -942,6 +962,14 @@ void RequestCoordinator::UpdateRequestForCompletedAttempt( const SavePageRequest& request, Offliner::RequestStatus status) { + // If the request failed, report the connection type as of the start of the + // request. + if (status != Offliner::RequestStatus::SAVED && + status != Offliner::RequestStatus::SAVED_ON_LAST_RETRY) { + RecordNetworkQualityAtRequestStartForFailedRequest( + request.client_id(), network_quality_at_request_start_); + } + if (status == Offliner::RequestStatus::FOREGROUND_CANCELED || status == Offliner::RequestStatus::LOADING_CANCELED) { // Update the request for the canceled attempt.
diff --git a/components/offline_pages/core/background/request_coordinator.h b/components/offline_pages/core/background/request_coordinator.h index 8692d28..2214906 100644 --- a/components/offline_pages/core/background/request_coordinator.h +++ b/components/offline_pages/core/background/request_coordinator.h
@@ -443,6 +443,7 @@ // Unowned pointer to the Network Quality Estimator. net::NetworkQualityEstimator::NetworkQualityProvider* network_quality_estimator_; + net::EffectiveConnectionType network_quality_at_request_start_; // Holds an ID of the currently active request. int64_t active_request_id_; // Status of the most recent offlining.
diff --git a/components/offline_pages/core/background/request_coordinator_unittest.cc b/components/offline_pages/core/background/request_coordinator_unittest.cc index 5933792f..8bdbba1 100644 --- a/components/offline_pages/core/background/request_coordinator_unittest.cc +++ b/components/offline_pages/core/background/request_coordinator_unittest.cc
@@ -784,6 +784,12 @@ EXPECT_TRUE(observer().completed_called()); EXPECT_EQ(RequestCoordinator::BackgroundSavePageResult::LOADING_FAILURE, observer().last_status()); + // We should have a histogram entry for the effective network conditions + // when this failed request began. + histograms().ExpectBucketCount( + "OfflinePages.Background.EffectiveConnectionType.OffliningStartType." + "bookmark", + net::NetworkChangeNotifier::CONNECTION_UNKNOWN, 1); } TEST_F(RequestCoordinatorTest, OfflinerDoneRequestFailedNoNextFailure) {
diff --git a/components/payments/mojom/payment_app.mojom b/components/payments/mojom/payment_app.mojom index ccda4c7..0ac3fbb 100644 --- a/components/payments/mojom/payment_app.mojom +++ b/components/payments/mojom/payment_app.mojom
@@ -58,10 +58,10 @@ struct PaymentAppRequest { url.mojom.Url origin; - array<PaymentMethodData> methodData; + array<PaymentMethodData> method_data; PaymentItem total; array<PaymentDetailsModifier> modifiers; - string optionId; + string option_id; }; struct PaymentAppResponse {
diff --git a/components/payments_strings.grdp b/components/payments_strings.grdp index 424c484..5a7d166b 100644 --- a/components/payments_strings.grdp +++ b/components/payments_strings.grdp
@@ -291,6 +291,10 @@ </message> </if> + <message name="IDS_PAYMENT_REQUEST_CHOOSE_AN_ADDRESS" desc="The string displayed as a placeholder in the shipping options row if no shipping address is selected"> + Choose an address + </message> + <!-- Payment Request section preview strings. They are slightly different on desktop and android because the pluralization and formatting code behaves differently. --> <if expr="not is_android"> <message name="IDS_PAYMENT_REQUEST_PAYMENT_METHODS_PREVIEW" desc="This is a snippet of a payment method a user has saved to Chrome, plus an indication of the number of additional payment methods the user has saved. Its function is to show the user has payment methods that can be used to complete a payment, and thus doesn't have to type the entire payment method. [ICU Syntax]">
diff --git a/components/policy/core/common/configuration_policy_provider_test.cc b/components/policy/core/common/configuration_policy_provider_test.cc index ad5c264..7b2efa4 100644 --- a/components/policy/core/common/configuration_policy_provider_test.cc +++ b/components/policy/core/common/configuration_policy_provider_test.cc
@@ -284,8 +284,8 @@ TEST_P(ConfigurationPolicyProviderTest, StringListValue) { base::ListValue expected_value; - expected_value.Set(0U, new base::Value("first")); - expected_value.Set(1U, new base::Value("second")); + expected_value.AppendString("first"); + expected_value.AppendString("second"); CheckValue(test_keys::kKeyStringList, expected_value, base::Bind(&PolicyProviderTestHarness::InstallStringListPolicy, @@ -302,8 +302,8 @@ expected_value.SetString("string", "omg"); base::ListValue* list = new base::ListValue(); - list->Set(0U, new base::Value("first")); - list->Set(1U, new base::Value("second")); + list->AppendString("first"); + list->AppendString("second"); expected_value.Set("array", list); base::DictionaryValue* dict = new base::DictionaryValue();
diff --git a/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc b/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc index df3f8c1..90c0cb1 100644 --- a/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc +++ b/components/subresource_filter/content/browser/content_subresource_filter_driver_factory.cc
@@ -115,7 +115,7 @@ content::NavigationHandle* navigation_handle) const { const GURL& url(navigation_handle->GetURL()); - auto configurations = GetActiveConfigurations(); + const auto configurations = GetActiveConfigurations(); if (configurations->the_one_and_only().activation_level == ActivationLevel::DISABLED) return ActivationDecision::ACTIVATION_DISABLED; @@ -189,7 +189,7 @@ RecordRedirectChainMatchPattern(); - auto configurations = GetActiveConfigurations(); + const auto configurations = GetActiveConfigurations(); if (configurations->the_one_and_only().should_whitelist_site_on_reload && NavigationIsPageReload(url, referrer, transition)) { // Whitelist this host for the current as well as subsequent navigations. @@ -215,7 +215,7 @@ } void ContentSubresourceFilterDriverFactory::OnFirstSubresourceLoadDisallowed() { - auto configurations = GetActiveConfigurations(); + const auto configurations = GetActiveConfigurations(); if (configurations->the_one_and_only().should_suppress_notifications) return;
diff --git a/components/subresource_filter/core/browser/subresource_filter_features.h b/components/subresource_filter/core/browser/subresource_filter_features.h index 487d0839..cd3e242d 100644 --- a/components/subresource_filter/core/browser/subresource_filter_features.h +++ b/components/subresource_filter/core/browser/subresource_filter_features.h
@@ -59,7 +59,7 @@ // handle multiple simultaneous configurations. class ConfigurationList : public base::RefCountedThreadSafe<ConfigurationList> { public: - ConfigurationList(Configuration config); + explicit ConfigurationList(Configuration config); const Configuration& the_one_and_only() const { return config_; }
diff --git a/components/subresource_filter/core/browser/subresource_filter_features_unittest.cc b/components/subresource_filter/core/browser/subresource_filter_features_unittest.cc index 86ba034..892fe09b 100644 --- a/components/subresource_filter/core/browser/subresource_filter_features_unittest.cc +++ b/components/subresource_filter/core/browser/subresource_filter_features_unittest.cc
@@ -42,7 +42,7 @@ : base::FeatureList::OVERRIDE_USE_DEFAULT, test_case.activation_level_param, kActivationScopeNoSites); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_activation_level, @@ -81,7 +81,7 @@ : base::FeatureList::OVERRIDE_USE_DEFAULT, kActivationLevelDisabled, test_case.activation_scope_param); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(ActivationLevel::DISABLED, actual_configuration.activation_level); @@ -134,7 +134,7 @@ : base::FeatureList::OVERRIDE_USE_DEFAULT, test_case.activation_level_param, test_case.activation_scope_param); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_activation_level, @@ -192,7 +192,7 @@ kActivationLevelDisabled, kActivationScopeNoSites, test_case.activation_list_param); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_activation_list, @@ -231,7 +231,7 @@ {{kPerformanceMeasurementRateParameterName, test_case.perf_measurement_param}}); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_perf_measurement_rate, @@ -267,7 +267,7 @@ {{kSuppressNotificationsParameterName, test_case.suppress_notifications_param}}); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_suppress_notifications_value, @@ -303,7 +303,7 @@ {{kWhitelistSiteOnReloadParameterName, test_case.whitelist_site_on_reload_param}}); - auto active_configurations = GetActiveConfigurations(); + const auto active_configurations = GetActiveConfigurations(); const Configuration& actual_configuration = active_configurations->the_one_and_only(); EXPECT_EQ(test_case.expected_whitelist_site_on_reload_value,
diff --git a/components/translate/core/browser/ranker_model_loader.cc b/components/translate/core/browser/ranker_model_loader.cc index 4a807446..d62fef2 100644 --- a/components/translate/core/browser/ranker_model_loader.cc +++ b/components/translate/core/browser/ranker_model_loader.cc
@@ -4,10 +4,11 @@ #include "components/translate/core/browser/ranker_model_loader.h" +#include <utility> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" -#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/important_file_writer.h" #include "base/macros.h" @@ -16,12 +17,12 @@ #include "base/profiler/scoped_tracker.h" #include "base/sequenced_task_runner.h" #include "base/strings/string_util.h" +#include "base/task_runner_util.h" #include "base/task_scheduler/post_task.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/translate/core/browser/proto/ranker_model.pb.h" #include "components/translate/core/browser/ranker_model.h" #include "components/translate/core/browser/translate_url_fetcher.h" -#include "url/gurl.h" namespace translate { namespace { @@ -31,10 +32,6 @@ constexpr int kUrlFetcherId = 2; -// The maximum number of model download attempts to make. Download may fail -// due to server error or network availability issues. -constexpr int kMaxDownloadAttempts = 8; - // The minimum duration, in minutes, between download attempts. constexpr int kMinRetryDelayMins = 3; @@ -45,6 +42,16 @@ const char kParsetimerHistogram[] = ".Timer.ParseModel"; const char kModelStatusHistogram[] = ".Model.Status"; +// Helper function to UMA log a timer histograms. +void RecordTimerHistogram(const std::string& name, base::TimeDelta duration) { + base::HistogramBase* counter = base::Histogram::FactoryTimeGet( + name, base::TimeDelta::FromMilliseconds(10), + base::TimeDelta::FromMilliseconds(200000), 100, + base::HistogramBase::kUmaTargetedHistogramFlag); + DCHECK(counter); + counter->AddTime(duration); +} + // A helper class to produce a scoped timer histogram that supports using a // non-static-const name. class MyScopedHistogramTimer { @@ -53,13 +60,7 @@ : name_(name.begin(), name.end()), start_(base::TimeTicks::Now()) {} ~MyScopedHistogramTimer() { - base::TimeDelta duration = base::TimeTicks::Now() - start_; - base::HistogramBase* counter = base::Histogram::FactoryTimeGet( - name_, base::TimeDelta::FromMilliseconds(10), - base::TimeDelta::FromMilliseconds(200000), 100, - base::HistogramBase::kUmaTargetedHistogramFlag); - if (counter) - counter->AddTime(duration); + RecordTimerHistogram(name_, base::TimeTicks::Now() - start_); } private: @@ -69,132 +70,221 @@ DISALLOW_COPY_AND_ASSIGN(MyScopedHistogramTimer); }; -} // namespace - -// ============================================================================= -// RankerModelLoader::Backend - -class RankerModelLoader::Backend { - public: - // An internal version of RankerModelLoader::OnModelAvailableCallback that - // bundles calling the real callback with a notification of whether or not - // tha backend is finished. - using InternalOnModelAvailableCallback = - base::Callback<void(std::unique_ptr<RankerModel>, bool)>; - - Backend(const ValidateModelCallback& validate_model_cb, - const InternalOnModelAvailableCallback& on_model_available_cb, - const base::FilePath& model_path, - const GURL& model_url, - const std::string& uma_prefix); - ~Backend(); - - // Reads the model from |model_path_|. - void LoadFromFile(); - - // Reads the model from |model_url_|. - void AsyncLoadFromURL(); - - private: - // Log and return the result of loading a model to UMA. - RankerModelStatus ReportModelStatus(RankerModelStatus model_status); - - // Constructs a model from the given |data|. - std::unique_ptr<chrome_intelligence::RankerModel> CreateModel( - const std::string& data); - - // Accepts downloaded model data. This signature is mandated by the callback - // defined by TransalteURLFetcher. - // - // id - the id given to the TranslateURLFetcher on creation - // success - true of the download was successful - // data - the body of the downloads response - void OnDownloadComplete(int id, bool success, const std::string& data); - - // Transfers ownership of |model| to the client using the - // |internal_on_model_available_cb_|. |is_finished| denotes whether the - // backend is finished (or has given up on) loading the model. - void TransferModelToClient( - std::unique_ptr<chrome_intelligence::RankerModel> model, - bool is_finished); - - // Validates that ranker model loader backend tasks are all performed on the - // same sequence. - base::SequenceChecker sequence_checker_; - - // The TaskRunner on which |this| was constructed. - const scoped_refptr<base::SequencedTaskRunner> origin_task_runner_; - - // Validates a ranker model on behalf of the model loader client. This may - // be called on any sequence and must, therefore, be thread-safe. - const ValidateModelCallback validate_model_cb_; - - // Transfers ownership of a loaded model back to the model loader client. - // This will be called on the sequence on which the model loader was - // constructed. - const InternalOnModelAvailableCallback internal_on_model_available_cb_; - - // The path at which the model is (or should be) cached. - const base::FilePath model_path_; - - // The URL from which to download the model if the model is not in the cache - // or the cached model is invalid/expired. - const GURL model_url_; - - // This will prefix all UMA metrics generated by the model loader. - const std::string uma_prefix_; - - // Used to download model data from |model_url_|. - // TODO(rogerm): Use net::URLFetcher directly? - std::unique_ptr<TranslateURLFetcher> url_fetcher_; - - // The number of times the backend has attempted to download the model. - int download_attempts_; - - // The next time before which no new attempts to download the model should be - // attempted. - base::TimeTicks next_earliest_download_time_; - - // Tracks the last time of the last attempt to download a model. Used for UMA - // reporting of download duration. - base::TimeTicks download_start_time_; - - DISALLOW_COPY_AND_ASSIGN(Backend); -}; - -RankerModelLoader::Backend::Backend( - const ValidateModelCallback& validate_model_cb, - const InternalOnModelAvailableCallback& internal_on_model_available_cb, - const base::FilePath& model_path, - const GURL& model_url, - const std::string& uma_prefix) - : origin_task_runner_(base::SequencedTaskRunnerHandle::Get()), - validate_model_cb_(validate_model_cb), - internal_on_model_available_cb_(internal_on_model_available_cb), - model_path_(model_path), - model_url_(model_url), - uma_prefix_(uma_prefix), - url_fetcher_(base::MakeUnique<TranslateURLFetcher>(kUrlFetcherId)), - download_attempts_(0) { - sequence_checker_.DetachFromSequence(); +std::string LoadFromFile(const base::FilePath& model_path) { + DCHECK(!model_path.empty()); + DVLOG(2) << "Reading data from: " << model_path.value(); + std::string data; + if (!base::ReadFileToString(model_path, &data) || data.empty()) { + DVLOG(2) << "Failed to read data from: " << model_path.value(); + data.clear(); + } + return data; } -RankerModelLoader::Backend::~Backend() {} +void SaveToFile(const GURL& model_url, + const base::FilePath& model_path, + const std::string& model_data, + const std::string& uma_prefix) { + DVLOG(2) << "Saving model from '" << model_url << "'' to '" + << model_path.value() << "'."; + MyScopedHistogramTimer timer(uma_prefix + kWriteTimerHistogram); + base::ImportantFileWriter::WriteFileAtomically(model_path, model_data); +} -RankerModelStatus RankerModelLoader::Backend::ReportModelStatus( - RankerModelStatus model_status) { - base::HistogramBase* histogram = base::LinearHistogram::FactoryGet( - uma_prefix_ + kModelStatusHistogram, 1, - static_cast<int>(RankerModelStatus::MAX), - static_cast<int>(RankerModelStatus::MAX) + 1, - base::HistogramBase::kUmaTargetedHistogramFlag); - if (histogram) - histogram->Add(static_cast<int>(model_status)); - return model_status; +} // namespace + +RankerModelLoader::RankerModelLoader( + ValidateModelCallback validate_model_cb, + OnModelAvailableCallback on_model_available_cb, + base::FilePath model_path, + GURL model_url, + std::string uma_prefix) + : background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( + base::TaskTraits() + .MayBlock() + .WithPriority(base::TaskPriority::BACKGROUND) + .WithShutdownBehavior( + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN))), + validate_model_cb_(std::move(validate_model_cb)), + on_model_available_cb_(std::move(on_model_available_cb)), + model_path_(std::move(model_path)), + model_url_(std::move(model_url)), + uma_prefix_(std::move(uma_prefix)), + url_fetcher_(base::MakeUnique<TranslateURLFetcher>(kUrlFetcherId)), + weak_ptr_factory_(this) {} + +RankerModelLoader::~RankerModelLoader() { + DCHECK(sequence_checker_.CalledOnValidSequence()); +} + +void RankerModelLoader::NotifyOfRankerActivity() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + switch (state_) { + case LoaderState::NOT_STARTED: + if (!model_path_.empty()) { + StartLoadFromFile(); + break; + } + // There was no configured model path. Switch the state to IDLE and + // fall through to consider the URL. + state_ = LoaderState::IDLE; + case LoaderState::IDLE: + if (model_url_.is_valid()) { + StartLoadFromURL(); + break; + } + // There was no configured model URL. Switch the state to FINISHED and + // fall through. + state_ = LoaderState::FINISHED; + case LoaderState::FINISHED: + case LoaderState::LOADING_FROM_FILE: + case LoaderState::LOADING_FROM_URL: + // Nothing to do. + break; + } +} + +void RankerModelLoader::StartLoadFromFile() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK_EQ(state_, LoaderState::NOT_STARTED); + DCHECK(!model_path_.empty()); + state_ = LoaderState::LOADING_FROM_FILE; + load_start_time_ = base::TimeTicks::Now(); + base::PostTaskAndReplyWithResult(background_task_runner_.get(), FROM_HERE, + base::Bind(&LoadFromFile, model_path_), + base::Bind(&RankerModelLoader::OnFileLoaded, + weak_ptr_factory_.GetWeakPtr())); +} + +void RankerModelLoader::OnFileLoaded(const std::string& data) { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK_EQ(state_, LoaderState::LOADING_FROM_FILE); + + // Record the duration of the download. + RecordTimerHistogram(uma_prefix_ + kReadTimerHistogram, + base::TimeTicks::Now() - load_start_time_); + + // Empty data means |model_path| wasn't successfully read. Otherwise, + // parse and validate the model. + std::unique_ptr<RankerModel> model; + if (data.empty()) { + ReportModelStatus(RankerModelStatus::LOAD_FROM_CACHE_FAILED); + } else { + model = CreateAndValidateModel(data); + } + + // If |model| is nullptr, then data is empty or the parse failed. Transition + // to IDLE, from which URL download can be attempted. + if (!model) { + state_ = LoaderState::IDLE; + } else { + // The model is valid. The client is willing/able to use it. Keep track + // of where it originated and whether or not is has expired. + std::string url_spec = model->GetSourceURL(); + bool is_expired = model->IsExpired(); + bool is_finished = url_spec == model_url_.spec() && !is_expired; + + DVLOG(2) << (is_expired ? "Expired m" : "M") << "odel in '" + << model_path_.value() << "' was originally downloaded from '" + << url_spec << "'."; + + // If the cached model came from currently configured |model_url_| and has + // not expired, transition to FINISHED, as there is no need for a model + // download; otherwise, transition to IDLE. + state_ = is_finished ? LoaderState::FINISHED : LoaderState::IDLE; + + // Transfer the model to the client. + on_model_available_cb_.Run(std::move(model)); + } + + // Notify the state machine. This will immediately kick off a download if + // one is required, instead of waiting for the next organic detection of + // ranker activity. + NotifyOfRankerActivity(); +} + +void RankerModelLoader::StartLoadFromURL() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK_EQ(state_, LoaderState::IDLE); + DCHECK(model_url_.is_valid()); + + // Do nothing if the download attempts should be throttled. + if (base::TimeTicks::Now() < next_earliest_download_time_) { + DVLOG(2) << "Last download attempt was too recent."; + ReportModelStatus(RankerModelStatus::DOWNLOAD_THROTTLED); + return; + } + + // Kick off the next download attempt and reset the time of the next earliest + // allowable download attempt. + DVLOG(2) << "Downloading model from: " << model_url_; + state_ = LoaderState::LOADING_FROM_URL; + load_start_time_ = base::TimeTicks::Now(); + next_earliest_download_time_ = + load_start_time_ + base::TimeDelta::FromMinutes(kMinRetryDelayMins); + bool request_started = url_fetcher_->Request( + model_url_, base::Bind(&RankerModelLoader::OnURLFetched, + weak_ptr_factory_.GetWeakPtr())); + + // |url_fetcher_| maintains a request retry counter. If all allowed attempts + // have already been exhausted, then the loader is finished and has abandoned + // loading the model. + if (!request_started) { + DVLOG(2) << "Model download abandoned."; + ReportModelStatus(RankerModelStatus::MODEL_LOADING_ABANDONED); + state_ = LoaderState::FINISHED; + } +} + +void RankerModelLoader::OnURLFetched(int /* id */, + bool success, + const std::string& data) { + DCHECK(sequence_checker_.CalledOnValidSequence()); + DCHECK_EQ(state_, LoaderState::LOADING_FROM_URL); + + // Record the duration of the download. + RecordTimerHistogram(uma_prefix_ + kDownloadTimerHistogram, + base::TimeTicks::Now() - load_start_time_); + + // On request failure, transition back to IDLE. The loader will retry, or + // enforce the max download attempts, later. + if (!success || data.empty()) { + DVLOG(2) << "Download from '" << model_url_ << "'' failed."; + ReportModelStatus(RankerModelStatus::DOWNLOAD_FAILED); + state_ = LoaderState::IDLE; + return; + } + + // Attempt to loads the model. If this fails, transition back to IDLE. The + // loader will retry, or enfore the max download attempts, later. + auto model = CreateAndValidateModel(data); + if (!model) { + DVLOG(2) << "Model from '" << model_url_ << "'' not valid."; + state_ = LoaderState::IDLE; + return; + } + + // The model is valid. Update the metadata to track the source URL and + // download timestamp. + auto* metadata = model->mutable_proto()->mutable_metadata(); + metadata->set_source(model_url_.spec()); + metadata->set_last_modified_sec( + (base::Time::Now() - base::Time()).InSeconds()); + + // Cache the model to model_path_, in the background. + if (!model_path_.empty()) { + background_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&SaveToFile, model_url_, model_path_, + model->SerializeAsString(), uma_prefix_)); + } + + // The loader is finished. Transfer the model to the client. + state_ = LoaderState::FINISHED; + on_model_available_cb_.Run(std::move(model)); } std::unique_ptr<chrome_intelligence::RankerModel> -RankerModelLoader::Backend::CreateModel(const std::string& data) { +RankerModelLoader::CreateAndValidateModel(const std::string& data) { DCHECK(sequence_checker_.CalledOnValidSequence()); MyScopedHistogramTimer timer(uma_prefix_ + kParsetimerHistogram); auto model = RankerModel::FromString(data); @@ -206,216 +296,17 @@ return model; } -void RankerModelLoader::Backend::LoadFromFile() { +RankerModelStatus RankerModelLoader::ReportModelStatus( + RankerModelStatus model_status) { DCHECK(sequence_checker_.CalledOnValidSequence()); - - // If there is not cache path set, move on to loading the model by URL. - if (model_path_.empty()) { - AsyncLoadFromURL(); - return; - } - - DVLOG(2) << "Attempting to load model from: " << model_path_.value(); - - std::string data; - - { - MyScopedHistogramTimer timer(uma_prefix_ + kReadTimerHistogram); - if (!base::ReadFileToString(model_path_, &data) || data.empty()) { - DVLOG(2) << "Failed to read model from: " << model_path_.value(); - data.clear(); - } - } - - // If model data was loaded, check if it can be parsed to a valid model. - if (!data.empty()) { - auto model = CreateModel(data); - if (model) { - // The model is valid. The client is willing/able to use it. Keep track - // of where it originated and whether or not is has expired. - std::string url_spec = model->GetSourceURL(); - bool is_expired = model->IsExpired(); - bool is_finished = url_spec == model_url_.spec() && !is_expired; - - DVLOG(2) << (is_expired ? "Expired m" : "M") << "odel in '" - << model_path_.value() << "' was originally downloaded from '" - << url_spec << "'."; - - // Transfer the model to the client. Beyond this line, |model| is invalid. - TransferModelToClient(std::move(model), is_finished); - - // If the cached model came from currently configured |model_url_| and has - // not expired, there is no need schedule a model download. - if (is_finished) - return; - - // Otherwise, fall out of this block to schedule a download. The client - // can continue to use the valid but expired model until the download - // completes. - } - } - - // Reaching this point means that a model download is required. If there is - // no download URL configured, then there is nothing further to do. - AsyncLoadFromURL(); -} - -void RankerModelLoader::Backend::AsyncLoadFromURL() { - DCHECK(sequence_checker_.CalledOnValidSequence()); - - if (!model_url_.is_valid()) { - // Notify the loader that model loading has been abandoned. - TransferModelToClient(nullptr, true); - return; - } - - // Do nothing if the download attempts should be throttled. - if (base::TimeTicks::Now() < next_earliest_download_time_) { - DVLOG(2) << "Last download attempt was too recent."; - return; - } - - // If a request is already in flight, do not issue a new one. - if (url_fetcher_->state() == TranslateURLFetcher::REQUESTING) { - DVLOG(2) << "Download is in progress."; - return; - } - - // If all allowed attempts have been exhausted, notify the loader that the - // backend has abandoned the download. - if (++download_attempts_ > kMaxDownloadAttempts) { - DVLOG(2) << "Model download abandoned."; - ReportModelStatus(RankerModelStatus::DOWNLOAD_FAILED); - TransferModelToClient(nullptr, true); - return; - } - - DVLOG(2) << "Downloading model from: " << model_url_; - - // Kick off the next download attempt and reset the time of the next earliest - // allowable download attempt. - download_start_time_ = base::TimeTicks::Now(); - next_earliest_download_time_ = - download_start_time_ + base::TimeDelta::FromMinutes(kMinRetryDelayMins); - url_fetcher_->Request( - model_url_, base::Bind(&RankerModelLoader::Backend::OnDownloadComplete, - base::Unretained(this))); -} - -void RankerModelLoader::Backend::OnDownloadComplete(int /* id */, - bool success, - const std::string& data) { - DCHECK(sequence_checker_.CalledOnValidSequence()); - - // Record the duration of the download. - base::TimeDelta duration = base::TimeTicks::Now() - download_start_time_; - base::HistogramBase* counter = base::Histogram::FactoryTimeGet( - uma_prefix_ + kDownloadTimerHistogram, - base::TimeDelta::FromMilliseconds(10), - base::TimeDelta::FromMilliseconds(200000), 100, + base::HistogramBase* histogram = base::LinearHistogram::FactoryGet( + uma_prefix_ + kModelStatusHistogram, 1, + static_cast<int>(RankerModelStatus::MAX), + static_cast<int>(RankerModelStatus::MAX) + 1, base::HistogramBase::kUmaTargetedHistogramFlag); - if (counter) - counter->AddTime(duration); - - // On failure, we just abort. The TranslateRanker will retry on a subsequent - // translation opportunity. The TranslateURLFetcher enforces a limit for - // retried requests. - if (!success || data.empty()) { - DVLOG(2) << "Download from '" << model_url_ << "'' failed."; - return; - } - - auto model = CreateModel(data); - if (!model) { - DVLOG(2) << "Model from '" << model_url_ << "'' not valid."; - return; - } - - url_fetcher_.reset(); - - auto* metadata = model->mutable_proto()->mutable_metadata(); - metadata->set_source(model_url_.spec()); - metadata->set_last_modified_sec( - (base::Time::Now() - base::Time()).InSeconds()); - - if (!model_path_.empty()) { - DVLOG(2) << "Saving model from '" << model_url_ << "'' to '" - << model_path_.value() << "'."; - MyScopedHistogramTimer timer(uma_prefix_ + kWriteTimerHistogram); - base::ImportantFileWriter::WriteFileAtomically(model_path_, - model->SerializeAsString()); - } - - // Notify the owner that a compatible model is available. - TransferModelToClient(std::move(model), true); -} - -void RankerModelLoader::Backend::TransferModelToClient( - std::unique_ptr<chrome_intelligence::RankerModel> model, - bool is_finished) { - DCHECK(sequence_checker_.CalledOnValidSequence()); - origin_task_runner_->PostTask( - FROM_HERE, base::Bind(internal_on_model_available_cb_, - base::Passed(std::move(model)), is_finished)); -} - -// ============================================================================= -// RankerModelLoader - -RankerModelLoader::RankerModelLoader( - const ValidateModelCallback& validate_model_cb, - const OnModelAvailableCallback& on_model_available_cb, - const base::FilePath& model_path, - const GURL& model_url, - const std::string& uma_prefix) - : backend_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - base::TaskTraits() - .MayBlock() - .WithPriority(base::TaskPriority::BACKGROUND) - .WithShutdownBehavior( - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN))), - weak_ptr_factory_(this) { - auto internal_on_model_available_cb = - base::Bind(&RankerModelLoader::InternalOnModelAvailable, - weak_ptr_factory_.GetWeakPtr(), on_model_available_cb); - backend_ = base::MakeUnique<Backend>(validate_model_cb, - internal_on_model_available_cb, - model_path, model_url, uma_prefix); -} - -RankerModelLoader::~RankerModelLoader() { - DCHECK(sequence_checker_.CalledOnValidSequence()); - // This is guaranteed to be sequenced after any pending backend operation. - backend_task_runner_->DeleteSoon(FROM_HERE, backend_.release()); -} - -void RankerModelLoader::Start() { - DCHECK(sequence_checker_.CalledOnValidSequence()); - DCHECK_EQ(state_, LoaderState::NOT_STARTED); - state_ = LoaderState::RUNNING; - backend_task_runner_->PostTask( - FROM_HERE, base::Bind(&RankerModelLoader::Backend::LoadFromFile, - base::Unretained(backend_.get()))); -} - -void RankerModelLoader::NotifyOfRankerActivity() { - DCHECK(sequence_checker_.CalledOnValidSequence()); - if (state_ == LoaderState::RUNNING) { - backend_task_runner_->PostTask( - FROM_HERE, base::Bind(&RankerModelLoader::Backend::AsyncLoadFromURL, - base::Unretained(backend_.get()))); - } -} - -void RankerModelLoader::InternalOnModelAvailable( - const OnModelAvailableCallback& callback, - std::unique_ptr<RankerModel> model, - bool finished) { - DCHECK(sequence_checker_.CalledOnValidSequence()); - if (finished) - state_ = LoaderState::FINISHED; - if (model) - callback.Run(std::move(model)); + if (histogram) + histogram->Add(static_cast<int>(model_status)); + return model_status; } } // namespace translate
diff --git a/components/translate/core/browser/ranker_model_loader.h b/components/translate/core/browser/ranker_model_loader.h index 0fd8806..68445b7 100644 --- a/components/translate/core/browser/ranker_model_loader.h +++ b/components/translate/core/browser/ranker_model_loader.h
@@ -9,14 +9,14 @@ #include <string> #include "base/callback.h" +#include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" - -class GURL; +#include "base/time/time.h" +#include "url/gurl.h" namespace base { -class FilePath; class SequencedTaskRunner; } // namespace base @@ -26,6 +26,8 @@ namespace translate { +class TranslateURLFetcher; + // Enumeration denoting the outcome of an attempt to download the model. This // must be kept in sync with the RankerModelStatus enum in histograms.xml enum class RankerModelStatus { @@ -35,6 +37,8 @@ PARSE_FAILED = 3, VALIDATION_FAILED = 4, INCOMPATIBLE = 5, + LOAD_FROM_CACHE_FAILED = 6, + MODEL_LOADING_ABANDONED = 7, // Insert new values above this line. MAX @@ -46,21 +50,16 @@ public: // Callback to validate a ranker model on behalf of the model loader client. // For example, the callback might validate that the model is compatible with - // the features generated when ranking translation offerings. This callback - // may be called on any sequence and must, therefore, be thread-safe. This - // callback may be invoked after the RankerModelLoader has been destroyed - // and must, therefore, only access memory that it can guarantee to be - // valid. - using ValidateModelCallback = base::Callback<RankerModelStatus( - const chrome_intelligence::RankerModel& model)>; + // the features generated when ranking translation offerings. This will be + // called on the sequence on which the model loader was constructed. + using ValidateModelCallback = base::RepeatingCallback<RankerModelStatus( + const chrome_intelligence::RankerModel&)>; // Called to transfer ownership of a loaded model back to the model loader // client. This will be called on the sequence on which the model loader was - // constructed. This callback may be invoked after the RankerModelLoader has - // been destroyed and must, therefore, only access memory that it can - // guarantee to be valid. - using OnModelAvailableCallback = base::Callback<void( - std::unique_ptr<chrome_intelligence::RankerModel> model)>; + // constructed. + using OnModelAvailableCallback = base::RepeatingCallback<void( + std::unique_ptr<chrome_intelligence::RankerModel>)>; // |validate_model_callback| may be called on any sequence; it must be thread // safe. @@ -79,56 +78,113 @@ // // |uma_prefix| will be used as a prefix for the names of all UMA metrics // generated by this loader. - RankerModelLoader(const ValidateModelCallback& validate_model_callback, - const OnModelAvailableCallback& on_model_available_callback, - const base::FilePath& model_path, - const GURL& model_url, - const std::string& uma_prefix); + RankerModelLoader(ValidateModelCallback validate_model_callback, + OnModelAvailableCallback on_model_available_callback, + base::FilePath model_path, + GURL model_url, + std::string uma_prefix); ~RankerModelLoader(); - // Asynchronously initiates loading the model from the cache file path and URL - // previously configured. - void Start(); - // Call this method periodically to notify the model loader the ranker is - // actively in use. The user's engagement with the feature is used as a proxy - // for network activity. If a model download is pending, this will trigger - // (subject to retry and frequency limits) a model download attempt. + // actively in use. The user's engagement with the ranked feature is used + // as a proxy for network availability and activity. If a model download + // is pending, this will trigger (subject to retry and frequency limits) a + // model download attempt. void NotifyOfRankerActivity(); private: - // The model loader backend to which the actual loading functionality is - // delegated. - class Backend; - friend class Backend; - // A enum to track the current loader state. - enum class LoaderState { NOT_STARTED, RUNNING, FINISHED }; + enum class LoaderState { + // The loader is newly created and has not started trying to load the model. + // This state can transition to LOADING_FROM_FILE or, if |model_path_| is + // empty, to LOADING_FROM_URL. If both |model_path_| and |model_url_| are + // empty/invalid then it can transition to FINISHED. + NOT_STARTED, + // The loader is busy loading the model from |model_path_| in the + // background. This state can transition to FINISHED if the loaded model is + // compatible and up to date; otherwise, this state can transition to IDLE. + LOADING_FROM_FILE, + // The loader is not currently busy. The loader can transition to the + // LOADING_FROM_URL_ state if |model_url_| is valid; the loader can also + // transition to FINISHED if it the maximum number of download attempts + // has been reached. + IDLE, + // The loader is busy loading the model from |model_url_| in the background. + // This state can transition to FINISHED if the loaded model is valid; + // otherwise, this state can re-transition to IDLE. + LOADING_FROM_URL, + // The loader has finished. This is the terminal state. + FINISHED + }; - // Helper method to forward OnModelAvailable callbacks while noting whether - // or not the loader has finished its work. - void InternalOnModelAvailable( - const OnModelAvailableCallback& callback, - std::unique_ptr<chrome_intelligence::RankerModel> model, - bool finished); + // Asynchronously initiates loading the model from model_path_; + void StartLoadFromFile(); + + // Called when the background worker has finished loading |data| from + // |model_path_|. If |data| is empty, the load from |model_path_| failed. + void OnFileLoaded(const std::string& data); + + // Asynchronously initiates loading the model from |model_url_|. + void StartLoadFromURL(); + + // Called when |url_fetcher_| has finished loading |data| from |model_url_|. + // + // This call signature is mandated by TranslateURLFetcher. + // + // id - the id given to the TranslateURLFetcher on creation + // success - true of the download was successful + // data - the body of the downloads response + void OnURLFetched(int id, bool success, const std::string& data); + + // Parse |data| and return a validated model. Returns nullptr on failure. + std::unique_ptr<chrome_intelligence::RankerModel> CreateAndValidateModel( + const std::string& data); + + // Helper function to log |model_status| to UMA and return it. + RankerModelStatus ReportModelStatus(RankerModelStatus model_status); // Validates that ranker model loader tasks are all performed on the same // sequence. base::SequenceChecker sequence_checker_; - // The task runner on which backend tasks are performed. - const scoped_refptr<base::SequencedTaskRunner> backend_task_runner_; + // The task runner on which background tasks are performed. + const scoped_refptr<base::SequencedTaskRunner> background_task_runner_; - // The model loader backend to which the actual loading functionality is - // delegated. |backend_| may outlive its RankerModelLoader. When the - // RankerModelLoader is destroyed, ownership of |backend_| is transferred - // to a delete task posted |backend_task_runner_|. - std::unique_ptr<Backend> backend_; + // Validates a ranker model on behalf of the model loader client. This will be + // called on the sequence on which the model leader was constructed. + const ValidateModelCallback validate_model_cb_; + + // Transfers ownership of a loaded model back to the model loader client. + // This will be called on the sequence on which the model loader was + // constructed. + const OnModelAvailableCallback on_model_available_cb_; + + // The path at which the model is (or should be) cached. + const base::FilePath model_path_; + + // The URL from which to download the model if the model is not in the cache + // or the cached model is invalid/expired. + const GURL model_url_; + + // This will prefix all UMA metrics generated by the model loader. + const std::string uma_prefix_; + + // Used to download model data from |model_url_|. + std::unique_ptr<TranslateURLFetcher> url_fetcher_; + + // The next time before which no new attempts to download the model should be + // attempted. + base::TimeTicks next_earliest_download_time_; + + // Tracks the last time of the last attempt to load a model, either from file + // of from URL. Used for UMA reporting of load durations. + base::TimeTicks load_start_time_; // The current state of the loader. LoaderState state_ = LoaderState::NOT_STARTED; + // Creates weak pointer references to the loader. base::WeakPtrFactory<RankerModelLoader> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(RankerModelLoader);
diff --git a/components/translate/core/browser/ranker_model_loader_unittest.cc b/components/translate/core/browser/ranker_model_loader_unittest.cc index 9a8be00..c312c2d09 100644 --- a/components/translate/core/browser/ranker_model_loader_unittest.cc +++ b/components/translate/core/browser/ranker_model_loader_unittest.cc
@@ -12,6 +12,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" @@ -199,8 +200,7 @@ base::Bind(&RankerModelLoaderTest::OnModelAvailable, base::Unretained(this)), model_path, model_url, "RankerModelLoaderTest"); - - loader->Start(); + loader->NotifyOfRankerActivity(); base::RunLoop().RunUntilIdle(); return true;
diff --git a/components/translate/core/browser/translate_download_manager.cc b/components/translate/core/browser/translate_download_manager.cc index 88c0177..1687fa1 100644 --- a/components/translate/core/browser/translate_download_manager.cc +++ b/components/translate/core/browser/translate_download_manager.cc
@@ -24,6 +24,7 @@ TranslateDownloadManager::~TranslateDownloadManager() {} void TranslateDownloadManager::Shutdown() { + DCHECK(sequence_checker_.CalledOnValidSequence()); language_list_.reset(); script_.reset(); request_context_ = NULL; @@ -99,11 +100,13 @@ } void TranslateDownloadManager::ResetForTesting() { + DCHECK(sequence_checker_.CalledOnValidSequence()); language_list_.reset(new TranslateLanguageList); script_.reset(new TranslateScript); } void TranslateDownloadManager::SetTranslateScriptExpirationDelay(int delay_ms) { + DCHECK(sequence_checker_.CalledOnValidSequence()); if (script_.get() == NULL) { NOTREACHED(); return;
diff --git a/components/translate/core/browser/translate_download_manager.h b/components/translate/core/browser/translate_download_manager.h index ed0ba219..fe6c66d0 100644 --- a/components/translate/core/browser/translate_download_manager.h +++ b/components/translate/core/browser/translate_download_manager.h
@@ -9,6 +9,7 @@ #include <string> #include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" #include "components/translate/core/browser/translate_language_list.h" #include "components/translate/core/browser/translate_script.h" #include "net/url_request/url_request_context_getter.h" @@ -31,24 +32,36 @@ // The request context used to download the resources. // Should be set before this class can be used. net::URLRequestContextGetter* request_context() { + DCHECK(sequence_checker_.CalledOnValidSequence()); return request_context_.get(); } void set_request_context(net::URLRequestContextGetter* context) { - request_context_ = context; + DCHECK(sequence_checker_.CalledOnValidSequence()); + request_context_ = context; } // The application locale. // Should be set before this class can be used. - const std::string& application_locale() { return application_locale_; } + const std::string& application_locale() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + return application_locale_; + } void set_application_locale(const std::string& locale) { + DCHECK(sequence_checker_.CalledOnValidSequence()); application_locale_ = locale; } // The language list. - TranslateLanguageList* language_list() { return language_list_.get(); } + TranslateLanguageList* language_list() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + return language_list_.get(); + } // The translate script. - TranslateScript* script() { return script_.get(); } + TranslateScript* script() { + DCHECK(sequence_checker_.CalledOnValidSequence()); + return script_.get(); + } // Let the caller decide if and when we should fetch the language list from // the translate server. This is a NOOP if prefs::kEnableTranslate is set to @@ -90,6 +103,10 @@ TranslateDownloadManager(); virtual ~TranslateDownloadManager(); + // Validates that accesses to the download manager are performed on the same + // sequence. + base::SequenceChecker sequence_checker_; + std::unique_ptr<TranslateLanguageList> language_list_; // An instance of TranslateScript which manages JavaScript source for
diff --git a/components/translate/core/browser/translate_ranker_impl.cc b/components/translate/core/browser/translate_ranker_impl.cc index 906c498..1c84e84 100644 --- a/components/translate/core/browser/translate_ranker_impl.cc +++ b/components/translate/core/browser/translate_ranker_impl.cc
@@ -156,7 +156,8 @@ base::Bind(&TranslateRankerImpl::OnModelAvailable, weak_ptr_factory_.GetWeakPtr()), model_path, model_url, kUmaPrefix); - model_loader_->Start(); + // Kick off the initial load from cache. + model_loader_->NotifyOfRankerActivity(); } }
diff --git a/components/translate/core/browser/translate_script_unittest.cc b/components/translate/core/browser/translate_script_unittest.cc index e654784..984c43a 100644 --- a/components/translate/core/browser/translate_script_unittest.cc +++ b/components/translate/core/browser/translate_script_unittest.cc
@@ -8,6 +8,8 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/strings/stringprintf.h" +#include "base/test/scoped_task_scheduler.h" +#include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/common/translate_switches.h" @@ -15,6 +17,7 @@ #include "net/base/url_util.h" #include "net/http/http_request_headers.h" #include "net/url_request/test_url_fetcher_factory.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -29,6 +32,9 @@ script_.reset(new TranslateScript); DCHECK(script_.get()); TranslateDownloadManager::GetInstance()->set_application_locale("en"); + TranslateDownloadManager::GetInstance()->set_request_context( + new net::TestURLRequestContextGetter( + base::ThreadTaskRunnerHandle::Get())); } void TearDown() override { script_.reset(); } @@ -46,7 +52,13 @@ void OnComplete(bool success, const std::string& script) { } + // Sets up the task scheduling/task-runner environment for each test. + base::test::ScopedTaskScheduler scoped_task_scheduler_; + + // The translate script. std::unique_ptr<TranslateScript> script_; + + // Factory to create programmatic URL fetchers. net::TestURLFetcherFactory url_fetcher_factory_; DISALLOW_COPY_AND_ASSIGN(TranslateScriptTest);
diff --git a/components/translate/core/browser/translate_url_fetcher.cc b/components/translate/core/browser/translate_url_fetcher.cc index dbbff31..d097d14a 100644 --- a/components/translate/core/browser/translate_url_fetcher.cc +++ b/components/translate/core/browser/translate_url_fetcher.cc
@@ -4,6 +4,7 @@ #include "components/translate/core/browser/translate_url_fetcher.h" +#include "base/memory/ref_counted.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/translate/core/browser/translate_download_manager.h" #include "net/base/load_flags.h" @@ -46,13 +47,22 @@ url_ = url; callback_ = callback; + // If the TranslateDownloadManager's request context getter is nullptr then + // shutdown is in progress. Abort the request, which can't proceed with a + // null request_context_getter. + scoped_refptr<net::URLRequestContextGetter> request_context_getter = + TranslateDownloadManager::GetInstance()->request_context(); + if (request_context_getter == nullptr) + return false; + + // Create and initialize the URL fetcher. fetcher_ = net::URLFetcher::Create(id_, url_, net::URLFetcher::GET, this); data_use_measurement::DataUseUserData::AttachToFetcher( fetcher_.get(), data_use_measurement::DataUseUserData::TRANSLATE); fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); - fetcher_->SetRequestContext( - TranslateDownloadManager::GetInstance()->request_context()); + fetcher_->SetRequestContext(request_context_getter.get()); + // Set retry parameter for HTTP status code 5xx. This doesn't work against // 106 (net::ERR_INTERNET_DISCONNECTED) and so on. // TranslateLanguageList handles network status, and implements retry.
diff --git a/content/browser/accessibility/accessibility_win_browsertest.cc b/content/browser/accessibility/accessibility_win_browsertest.cc index 7ca9e9f..4b6f4d7 100644 --- a/content/browser/accessibility/accessibility_win_browsertest.cc +++ b/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -1915,7 +1915,6 @@ // is not called again after its window is added to the root window. // Ensure that we still get a legacy HWND for accessibility. - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); @@ -1950,7 +1949,6 @@ } IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest, TestAccNavigateInTables) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); AccessibilityNotificationWaiter waiter(shell()->web_contents(), kAccessibilityModeComplete,
diff --git a/content/browser/accessibility/hit_testing_browsertest.cc b/content/browser/accessibility/hit_testing_browsertest.cc index 18009a1..6e959d6 100644 --- a/content/browser/accessibility/hit_testing_browsertest.cc +++ b/content/browser/accessibility/hit_testing_browsertest.cc
@@ -105,7 +105,6 @@ IN_PROC_BROWSER_TEST_F(AccessibilityHitTestingBrowserTest, HitTestingInIframes) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); NavigateToURL(shell(), GURL(url::kAboutBlankURL)); @@ -166,7 +165,6 @@ IN_PROC_BROWSER_TEST_F(AccessibilityHitTestingBrowserTest, CachingAsyncHitTestingInIframes) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); NavigateToURL(shell(), GURL(url::kAboutBlankURL));
diff --git a/content/browser/accessibility/snapshot_ax_tree_browsertest.cc b/content/browser/accessibility/snapshot_ax_tree_browsertest.cc index 2a36197..0f093fc 100644 --- a/content/browser/accessibility/snapshot_ax_tree_browsertest.cc +++ b/content/browser/accessibility/snapshot_ax_tree_browsertest.cc
@@ -93,7 +93,6 @@ IN_PROC_BROWSER_TEST_F(SnapshotAXTreeBrowserTest, SnapshotAccessibilityTreeFromMultipleFrames) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); NavigateToURL(shell(), embedded_test_server()->GetURL(
diff --git a/content/browser/android/render_widget_host_connector_browsertest.cc b/content/browser/android/render_widget_host_connector_browsertest.cc index 2856c7b..e1840ff7 100644 --- a/content/browser/android/render_widget_host_connector_browsertest.cc +++ b/content/browser/android/render_widget_host_connector_browsertest.cc
@@ -28,8 +28,6 @@ RenderWidgetHostConnectorTest::RenderWidgetHostConnectorTest() {} void RenderWidgetHostConnectorTest::SetUpOnMainThread() { - host_resolver()->AddRule("*", "127.0.0.1"); - SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); }
diff --git a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc index 0e41996..f86207f9 100644 --- a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -146,6 +146,7 @@ net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem"); expired_cert_ = net::ImportCertFromFile(net::GetTestCertsDirectory(), "expired_cert.pem"); + host_resolver()->AddRule("*", "127.0.0.1"); } protected: @@ -943,7 +944,6 @@ } IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, CrossSiteNoDetach) { - host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -976,7 +976,6 @@ } IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, CrossSitePauseInBeforeUnload) { - host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -998,7 +997,6 @@ } IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, InspectDuringFrameSwap) { - host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -1271,7 +1269,6 @@ IN_PROC_BROWSER_TEST_F(IsolatedDevToolsProtocolTest, ControlNavigationsChildFrames) { - host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -1675,7 +1672,6 @@ void SetUpOnMainThread() override { DevToolsProtocolTest::SetUpOnMainThread(); - host_resolver()->AddRule("*", "127.0.0.1"); content::SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); }
diff --git a/content/browser/devtools/site_per_process_devtools_browsertest.cc b/content/browser/devtools/site_per_process_devtools_browsertest.cc index e119d802..62817ef0 100644 --- a/content/browser/devtools/site_per_process_devtools_browsertest.cc +++ b/content/browser/devtools/site_per_process_devtools_browsertest.cc
@@ -19,10 +19,13 @@ namespace content { -class SitePerProcessDevToolsBrowserTest - : public SitePerProcessBrowserTest { +class SitePerProcessDevToolsBrowserTest : public SitePerProcessBrowserTest { public: SitePerProcessDevToolsBrowserTest() {} + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + SitePerProcessBrowserTest::SetUpOnMainThread(); + } }; class TestClient: public DevToolsAgentHostClient { @@ -66,7 +69,6 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsBrowserTest, MAYBE_CrossSiteIframeAgentHost) { DevToolsAgentHost::List list; - host_resolver()->AddRule("*", "127.0.0.1"); GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); NavigateToURL(shell(), main_url); @@ -138,7 +140,6 @@ } IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsBrowserTest, AgentHostForFrames) { - host_resolver()->AddRule("*", "127.0.0.1"); GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); NavigateToURL(shell(), main_url); @@ -179,7 +180,6 @@ IN_PROC_BROWSER_TEST_F(SitePerProcessDevToolsBrowserTest, AgentHostForPageEqualsOneForMainFrame) { - host_resolver()->AddRule("*", "127.0.0.1"); GURL main_url(embedded_test_server()->GetURL("/site_per_process_main.html")); NavigateToURL(shell(), main_url);
diff --git a/content/browser/download/download_browsertest.cc b/content/browser/download/download_browsertest.cc index 1d409a8d..67bc08d 100644 --- a/content/browser/download/download_browsertest.cc +++ b/content/browser/download/download_browsertest.cc
@@ -90,6 +90,9 @@ // Default request count for parallel download tests. constexpr int kTestRequestCount = 3; +const std::string kOriginOne = "one.example"; +const std::string kOriginTwo = "two.example"; + class MockDownloadItemObserver : public DownloadItem::Observer { public: MockDownloadItemObserver() {} @@ -595,6 +598,11 @@ base::Bind( &net::URLRequestMockHTTPJob::AddUrlHandlers, mock_base, make_scoped_refptr(content::BrowserThread::GetBlockingPool()))); + ASSERT_TRUE(embedded_test_server()->Start()); + const std::string real_host = + embedded_test_server()->host_port_pair().host(); + host_resolver()->AddRule(kOriginOne, real_host); + host_resolver()->AddRule(kOriginTwo, real_host); } void SetUpCommandLine(base::CommandLine* command_line) override { @@ -2302,7 +2310,6 @@ TestDownloadRequestHandler::Parameters::WithSingleInterruption(); request_handler.StartServing(parameters); - ASSERT_TRUE(embedded_test_server()->Start()); GURL document_url = embedded_test_server()->GetURL( std::string("/download/download-link.html?dl=") .append(request_handler.url().spec())); @@ -2472,8 +2479,6 @@ // A request for a non-existent resource should still result in a DownloadItem // that's created in an interrupted state. IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeServerError) { - ASSERT_TRUE(embedded_test_server()->Start()); - GURL download_url = embedded_test_server()->GetURL("/download/does-not-exist"); GURL document_url = embedded_test_server()->GetURL( @@ -2500,7 +2505,6 @@ // A request that fails before it gets a response from the server should also // result in a DownloadItem that's created in an interrupted state. IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeNetworkError) { - ASSERT_TRUE(embedded_test_server()->Start()); TestDownloadRequestHandler request_handler; TestDownloadRequestHandler::Parameters parameters; @@ -2520,8 +2524,6 @@ // A request that fails due to it being rejected by policy should result in a // DownloadItem that's marked as interrupted. IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeInvalidURL) { - ASSERT_TRUE(embedded_test_server()->Start()); - GURL document_url = embedded_test_server()->GetURL( "/download/download-attribute.html?target=about:version"); DownloadItem* download = StartDownloadAndReturnItem(shell(), document_url); @@ -2533,8 +2535,6 @@ } IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeBlobURL) { - ASSERT_TRUE(embedded_test_server()->Start()); - GURL document_url = embedded_test_server()->GetURL("/download/download-attribute-blob.html"); DownloadItem* download = StartDownloadAndReturnItem(shell(), document_url); @@ -2547,15 +2547,6 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeSameSiteCookie) { base::ThreadRestrictions::ScopedAllowIO allow_io_during_test; - const std::string kOriginOne = "one.example"; - const std::string kOriginTwo = "two.example"; - - ASSERT_TRUE(embedded_test_server()->Start()); - - const std::string real_host = embedded_test_server()->host_port_pair().host(); - host_resolver()->AddRule(kOriginOne, real_host); - host_resolver()->AddRule(kOriginTwo, real_host); - GURL echo_cookie_url = embedded_test_server()->GetURL(kOriginOne, "/echoheader?cookie"); @@ -2644,8 +2635,6 @@ } IN_PROC_BROWSER_TEST_F(DownloadContentTest, DuplicateContentDisposition) { - ASSERT_TRUE(embedded_test_server()->Start()); - // double-content-disposition.txt is served with two Content-Disposition // headers, both of which are identical. NavigateToURLAndWaitForDownload( @@ -2663,8 +2652,6 @@ } IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadAttributeSameOriginIFrame) { - ASSERT_TRUE(embedded_test_server()->Start()); - GURL frame_url = embedded_test_server()->GetURL( "/download/download-attribute.html?target=/download/download-test.lib"); GURL document_url = embedded_test_server()->GetURL(
diff --git a/content/browser/frame_host/navigation_handle_impl_browsertest.cc b/content/browser/frame_host/navigation_handle_impl_browsertest.cc index 64a6b3bf..892d64c 100644 --- a/content/browser/frame_host/navigation_handle_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_handle_impl_browsertest.cc
@@ -1147,6 +1147,10 @@ void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kEnableBrowserSideNavigation); } + + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + } }; // Test to verify that error pages caused by NavigationThrottle blocking a @@ -1154,7 +1158,6 @@ // that requested the navigation. IN_PROC_BROWSER_TEST_F(PlzNavigateNavigationHandleImplBrowserTest, ErrorPageBlockedNavigation) { - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -1190,7 +1193,6 @@ // destination URL. IN_PROC_BROWSER_TEST_F(PlzNavigateNavigationHandleImplBrowserTest, ErrorPageNetworkError) { - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start());
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index 201de60..12cac29a 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -147,9 +147,12 @@ original_file_path, replacement_text, replacement_path); } - void StartServer() { + void SetUpOnMainThread() override { // Support multiple sites on the test server. host_resolver()->AddRule("*", "127.0.0.1"); + } + + void StartServer() { ASSERT_TRUE(embedded_test_server()->Start()); foo_host_port_ = embedded_test_server()->host_port_pair(); @@ -157,7 +160,6 @@ } void StartEmbeddedServer() { - // Support multiple sites on the embedded test server. host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start());
diff --git a/content/browser/frame_host/render_frame_message_filter_browsertest.cc b/content/browser/frame_host/render_frame_message_filter_browsertest.cc index 5ffd7b7..4539190 100644 --- a/content/browser/frame_host/render_frame_message_filter_browsertest.cc +++ b/content/browser/frame_host/render_frame_message_filter_browsertest.cc
@@ -54,12 +54,16 @@ switches::kEnableExperimentalWebPlatformFeatures); ContentBrowserTest::SetUp(); } + + void SetUpOnMainThread() override { + // Support multiple sites on the test server. + host_resolver()->AddRule("*", "127.0.0.1"); + } }; // Exercises basic cookie operations via javascript, including an http page // interacting with secure cookies. IN_PROC_BROWSER_TEST_F(RenderFrameMessageFilterBrowserTest, Cookies) { - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -122,7 +126,6 @@ // SameSite cookies (that aren't marked as http-only) should be available to // JavaScript. IN_PROC_BROWSER_TEST_F(RenderFrameMessageFilterBrowserTest, SameSiteCookies) { - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); @@ -173,7 +176,6 @@ return; } - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); NavigateToURL(shell(),
diff --git a/content/browser/loader/resource_dispatcher_host_browsertest.cc b/content/browser/loader/resource_dispatcher_host_browsertest.cc index d330139..806df8c 100644 --- a/content/browser/loader/resource_dispatcher_host_browsertest.cc +++ b/content/browser/loader/resource_dispatcher_host_browsertest.cc
@@ -873,6 +873,7 @@ content::BrowserThread::IO, FROM_HERE, base::Bind(&RequestDataResourceDispatcherHostDelegate::SetDelegate, base::Unretained(delegate_.get()))); + host_resolver()->AddRule("*", "127.0.0.1"); } protected: @@ -912,7 +913,6 @@ IN_PROC_BROWSER_TEST_F(RequestDataResourceDispatcherHostBrowserTest, BasicCrossSite) { - host_resolver()->AddRule("*", "127.0.0.1"); GURL top_url(embedded_test_server()->GetURL( "a.com", "/nested_page_with_subresources.html")); GURL nested_url(embedded_test_server()->GetURL( @@ -1099,7 +1099,6 @@ IN_PROC_BROWSER_TEST_F(RequestDataResourceDispatcherHostBrowserTest, CrossOriginNested) { - host_resolver()->AddRule("*", "127.0.0.1"); GURL top_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b)")); GURL top_js_url(
diff --git a/content/browser/payments/payment_app_browsertest.cc b/content/browser/payments/payment_app_browsertest.cc index e6183f0..995ebdc 100644 --- a/content/browser/payments/payment_app_browsertest.cc +++ b/content/browser/payments/payment_app_browsertest.cc
@@ -95,7 +95,7 @@ int64_t registration_id) { payments::mojom::PaymentAppRequestPtr app_request = payments::mojom::PaymentAppRequest::New(); - app_request->methodData.push_back( + app_request->method_data.push_back( payments::mojom::PaymentMethodData::New()); app_request->total = payments::mojom::PaymentItem::New(); app_request->total->amount = payments::mojom::PaymentCurrencyAmount::New();
diff --git a/content/browser/payments/payment_app_provider_impl_unittest.cc b/content/browser/payments/payment_app_provider_impl_unittest.cc index 83be68b4..5ced822c8 100644 --- a/content/browser/payments/payment_app_provider_impl_unittest.cc +++ b/content/browser/payments/payment_app_provider_impl_unittest.cc
@@ -135,7 +135,7 @@ payments::mojom::PaymentAppRequestPtr app_request = payments::mojom::PaymentAppRequest::New(); - app_request->methodData.push_back(payments::mojom::PaymentMethodData::New()); + app_request->method_data.push_back(payments::mojom::PaymentMethodData::New()); app_request->total = payments::mojom::PaymentItem::New(); app_request->total->amount = payments::mojom::PaymentCurrencyAmount::New();
diff --git a/content/browser/renderer_host/p2p/socket_host_tcp.cc b/content/browser/renderer_host/p2p/socket_host_tcp.cc index 039c619..1961e1b0 100644 --- a/content/browser/renderer_host/p2p/socket_host_tcp.cc +++ b/content/browser/renderer_host/p2p/socket_host_tcp.cc
@@ -49,6 +49,15 @@ namespace content { +P2PSocketHostTcp::SendBuffer::SendBuffer() : rtc_packet_id(-1) {} +P2PSocketHostTcp::SendBuffer::SendBuffer( + int32_t rtc_packet_id, + scoped_refptr<net::DrainableIOBuffer> buffer) + : rtc_packet_id(rtc_packet_id), buffer(buffer) {} +P2PSocketHostTcp::SendBuffer::SendBuffer(const SendBuffer& rhs) + : rtc_packet_id(rhs.rtc_packet_id), buffer(rhs.buffer) {} +P2PSocketHostTcp::SendBuffer::~SendBuffer() {} + P2PSocketHostTcpBase::P2PSocketHostTcpBase( IPC::Sender* message_sender, int socket_id, @@ -383,25 +392,24 @@ DoSend(to, data, options); } -void P2PSocketHostTcpBase::WriteOrQueue( - scoped_refptr<net::DrainableIOBuffer>& buffer) { +void P2PSocketHostTcpBase::WriteOrQueue(SendBuffer& send_buffer) { IncrementTotalSentPackets(); - if (write_buffer_.get()) { - write_queue_.push(buffer); + if (write_buffer_.buffer.get()) { + write_queue_.push(send_buffer); IncrementDelayedPackets(); - IncrementDelayedBytes(buffer->size()); + IncrementDelayedBytes(send_buffer.buffer->size()); return; } - write_buffer_ = buffer; + write_buffer_ = send_buffer; DoWrite(); } void P2PSocketHostTcpBase::DoWrite() { - while (write_buffer_.get() && state_ == STATE_OPEN && !write_pending_) { + while (write_buffer_.buffer.get() && state_ == STATE_OPEN && + !write_pending_) { int result = socket_->Write( - write_buffer_.get(), - write_buffer_->BytesRemaining(), + write_buffer_.buffer.get(), write_buffer_.buffer->BytesRemaining(), base::Bind(&P2PSocketHostTcp::OnWritten, base::Unretained(this))); HandleWriteResult(result); } @@ -417,19 +425,22 @@ } void P2PSocketHostTcpBase::HandleWriteResult(int result) { - DCHECK(write_buffer_.get()); + DCHECK(write_buffer_.buffer.get()); if (result >= 0) { - write_buffer_->DidConsume(result); - if (write_buffer_->BytesRemaining() == 0) { - message_sender_->Send( - new P2PMsg_OnSendComplete(id_, P2PSendPacketMetrics())); + write_buffer_.buffer->DidConsume(result); + if (write_buffer_.buffer->BytesRemaining() == 0) { + base::TimeTicks send_time = base::TimeTicks::Now(); + message_sender_->Send(new P2PMsg_OnSendComplete( + id_, + P2PSendPacketMetrics(0, write_buffer_.rtc_packet_id, send_time))); if (write_queue_.empty()) { - write_buffer_ = nullptr; + write_buffer_.buffer = nullptr; + write_buffer_.rtc_packet_id = -1; } else { write_buffer_ = write_queue_.front(); write_queue_.pop(); // Update how many bytes are still waiting to be sent. - DecrementDelayedBytes(write_buffer_->size()); + DecrementDelayedBytes(write_buffer_.buffer->size()); } } } else if (result == net::ERR_IO_PENDING) { @@ -484,7 +495,11 @@ } bool P2PSocketHostTcpBase::SetOption(P2PSocketOption option, int value) { - DCHECK_EQ(STATE_OPEN, state_); + if (state_ != STATE_OPEN) { + DCHECK_EQ(state_, STATE_ERROR); + return false; + } + switch (option) { case P2P_SOCKET_OPT_RCVBUF: return socket_->SetReceiveBufferSize(value) == net::OK; @@ -530,17 +545,20 @@ const std::vector<char>& data, const rtc::PacketOptions& options) { int size = kPacketHeaderSize + data.size(); - scoped_refptr<net::DrainableIOBuffer> buffer = - new net::DrainableIOBuffer(new net::IOBuffer(size), size); - *reinterpret_cast<uint16_t*>(buffer->data()) = base::HostToNet16(data.size()); - memcpy(buffer->data() + kPacketHeaderSize, &data[0], data.size()); + SendBuffer send_buffer(options.packet_id, new net::DrainableIOBuffer( + new net::IOBuffer(size), size)); + *reinterpret_cast<uint16_t*>(send_buffer.buffer->data()) = + base::HostToNet16(data.size()); + memcpy(send_buffer.buffer->data() + kPacketHeaderSize, &data[0], data.size()); cricket::ApplyPacketOptions( - reinterpret_cast<uint8_t*>(buffer->data()) + kPacketHeaderSize, - buffer->BytesRemaining() - kPacketHeaderSize, options.packet_time_params, + reinterpret_cast<uint8_t*>(send_buffer.buffer->data()) + + kPacketHeaderSize, + send_buffer.buffer->BytesRemaining() - kPacketHeaderSize, + options.packet_time_params, (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds()); - WriteOrQueue(buffer); + WriteOrQueue(send_buffer); } // P2PSocketHostStunTcp @@ -604,24 +622,24 @@ // Add any pad bytes to the total size. int size = data.size() + pad_bytes; - scoped_refptr<net::DrainableIOBuffer> buffer = - new net::DrainableIOBuffer(new net::IOBuffer(size), size); - memcpy(buffer->data(), &data[0], data.size()); + SendBuffer send_buffer(options.packet_id, new net::DrainableIOBuffer( + new net::IOBuffer(size), size)); + memcpy(send_buffer.buffer->data(), &data[0], data.size()); cricket::ApplyPacketOptions( - reinterpret_cast<uint8_t*>(buffer->data()), data.size(), + reinterpret_cast<uint8_t*>(send_buffer.buffer->data()), data.size(), options.packet_time_params, (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds()); if (pad_bytes) { char padding[4] = {0}; DCHECK_LE(pad_bytes, 4); - memcpy(buffer->data() + data.size(), padding, pad_bytes); + memcpy(send_buffer.buffer->data() + data.size(), padding, pad_bytes); } - WriteOrQueue(buffer); + WriteOrQueue(send_buffer); if (dump_outgoing_rtp_packet_) - DumpRtpPacket(buffer->data(), data.size(), false); + DumpRtpPacket(send_buffer.buffer->data(), data.size(), false); } int P2PSocketHostStunTcp::GetExpectedPacketSize(
diff --git a/content/browser/renderer_host/p2p/socket_host_tcp.h b/content/browser/renderer_host/p2p/socket_host_tcp.h index a7771c98..9e8fe2d 100644 --- a/content/browser/renderer_host/p2p/socket_host_tcp.h +++ b/content/browser/renderer_host/p2p/socket_host_tcp.h
@@ -54,13 +54,23 @@ bool SetOption(P2PSocketOption option, int value) override; protected: + struct SendBuffer { + SendBuffer(); + SendBuffer(int32_t packet_id, scoped_refptr<net::DrainableIOBuffer> buffer); + SendBuffer(const SendBuffer& rhs); + ~SendBuffer(); + + int32_t rtc_packet_id; + scoped_refptr<net::DrainableIOBuffer> buffer; + }; + // Derived classes will provide the implementation. virtual int ProcessInput(char* input, int input_len) = 0; virtual void DoSend(const net::IPEndPoint& to, const std::vector<char>& data, const rtc::PacketOptions& options) = 0; - void WriteOrQueue(scoped_refptr<net::DrainableIOBuffer>& buffer); + void WriteOrQueue(SendBuffer& send_buffer); void OnPacket(const std::vector<char>& data); void OnError(); @@ -91,8 +101,8 @@ std::unique_ptr<net::StreamSocket> socket_; scoped_refptr<net::GrowableIOBuffer> read_buffer_; - std::queue<scoped_refptr<net::DrainableIOBuffer> > write_queue_; - scoped_refptr<net::DrainableIOBuffer> write_buffer_; + std::queue<SendBuffer> write_queue_; + SendBuffer write_buffer_; bool write_pending_;
diff --git a/content/browser/renderer_host/p2p/socket_host_tcp_unittest.cc b/content/browser/renderer_host/p2p/socket_host_tcp_unittest.cc index b018b27..82b8ee9 100644 --- a/content/browser/renderer_host/p2p/socket_host_tcp_unittest.cc +++ b/content/browser/renderer_host/p2p/socket_host_tcp_unittest.cc
@@ -184,6 +184,19 @@ EXPECT_EQ(0U, sent_data_.size()); } +// Verify that SetOption() doesn't crash after an error. +TEST_F(P2PSocketHostTcpTest, SetOptionAfterError) { + // Get the sender into the error state. + EXPECT_CALL(sender_, + Send(MatchMessage(static_cast<uint32_t>(P2PMsg_OnError::ID)))) + .WillOnce(DoAll(DeleteArg<0>(), Return(true))); + socket_host_->Send(dest_.ip_address, {1, 2, 3, 4}, rtc::PacketOptions(), 0); + testing::Mock::VerifyAndClearExpectations(&sender_); + + // Verify that SetOptions() fails, but doesn't crash. + EXPECT_FALSE(socket_host_->SetOption(P2P_SOCKET_OPT_RCVBUF, 2048)); +} + // Verify that we can send data after we've received STUN response // from the other side. TEST_F(P2PSocketHostTcpTest, SendAfterStunRequest) { @@ -249,6 +262,35 @@ EXPECT_EQ(expected_data, sent_data_); } +TEST_F(P2PSocketHostTcpTest, PacketIdIsPropagated) { + base::MessageLoop message_loop; + + socket_->set_async_write(true); + + const int32_t kRtcPacketId = 1234; + + base::TimeTicks now = base::TimeTicks::Now(); + + EXPECT_CALL(sender_, Send(MatchSendPacketMetrics(kRtcPacketId, now))) + .Times(1) + .WillRepeatedly(DoAll(DeleteArg<0>(), Return(true))); + + rtc::PacketOptions options; + options.packet_id = kRtcPacketId; + std::vector<char> packet1; + CreateStunRequest(&packet1); + + socket_host_->Send(dest_.ip_address, packet1, options, 0); + + base::RunLoop().RunUntilIdle(); + + std::string expected_data; + expected_data.append(IntToSize(packet1.size())); + expected_data.append(packet1.begin(), packet1.end()); + + EXPECT_EQ(expected_data, sent_data_); +} + TEST_F(P2PSocketHostTcpTest, SendDataWithPacketOptions) { std::vector<char> request_packet; CreateStunRequest(&request_packet);
diff --git a/content/browser/renderer_host/p2p/socket_host_test_utils.h b/content/browser/renderer_host/p2p/socket_host_test_utils.h index 8d2d2440..7b7552f9 100644 --- a/content/browser/renderer_host/p2p/socket_host_test_utils.h +++ b/content/browser/renderer_host/p2p/socket_host_test_utils.h
@@ -123,4 +123,15 @@ return std::get<1>(params) == address; } +MATCHER_P2(MatchSendPacketMetrics, rtc_packet_id, test_start_time, "") { + if (arg->type() != P2PMsg_OnSendComplete::ID) + return false; + + P2PMsg_OnSendComplete::Param params; + P2PMsg_OnSendComplete::Read(arg, ¶ms); + return std::get<1>(params).rtc_packet_id == rtc_packet_id && + std::get<1>(params).send_time >= test_start_time && + std::get<1>(params).send_time <= base::TimeTicks::Now(); +} + #endif // CONTENT_BROWSER_RENDERER_HOST_P2P_SOCKET_HOST_TEST_UTILS_H_
diff --git a/content/browser/renderer_host/p2p/socket_host_udp.cc b/content/browser/renderer_host/p2p/socket_host_udp.cc index e4e744b..375e5571 100644 --- a/content/browser/renderer_host/p2p/socket_host_udp.cc +++ b/content/browser/renderer_host/p2p/socket_host_udp.cc
@@ -422,7 +422,11 @@ } bool P2PSocketHostUdp::SetOption(P2PSocketOption option, int value) { - DCHECK_EQ(STATE_OPEN, state_); + if (state_ != STATE_OPEN) { + DCHECK_EQ(state_, STATE_ERROR); + return false; + } + switch (option) { case P2P_SOCKET_OPT_RCVBUF: return socket_->SetReceiveBufferSize(value) == net::OK;
diff --git a/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc b/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc index 6627511..4b68cd51 100644 --- a/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc +++ b/content/browser/renderer_host/p2p/socket_host_udp_unittest.cc
@@ -281,6 +281,19 @@ ASSERT_EQ(sent_packets_.size(), 0U); } +// Verify that SetOption() doesn't crash after an error. +TEST_F(P2PSocketHostUdpTest, SetOptionAfterError) { + // Get the sender into the error state. + EXPECT_CALL(sender_, + Send(MatchMessage(static_cast<uint32_t>(P2PMsg_OnError::ID)))) + .WillOnce(DoAll(DeleteArg<0>(), Return(true))); + socket_host_->Send(dest1_, {1, 2, 3, 4}, rtc::PacketOptions(), 0); + testing::Mock::VerifyAndClearExpectations(&sender_); + + // Verify that SetOptions() fails, but doesn't crash. + EXPECT_FALSE(socket_host_->SetOption(P2P_SOCKET_OPT_RCVBUF, 2048)); +} + // Verify that we can send data after we've received STUN request // from the other side. TEST_F(P2PSocketHostUdpTest, SendAfterStunRequest) {
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index a0e5792..232e80d 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -1988,7 +1988,6 @@ const ViewHostMsg_UpdateRect_Params& params, const TimeTicks& paint_start) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::DidUpdateBackingStore"); - TimeTicks update_start = TimeTicks::Now(); NotificationService::current()->Notify( NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE, @@ -2006,11 +2005,6 @@ ViewHostMsg_UpdateRect_Flags::is_resize_ack(params.flags); if (is_resize_ack) WasResized(); - - // Log the time delta for processing a paint message. - TimeTicks now = TimeTicks::Now(); - TimeDelta delta = now - update_start; - UMA_HISTOGRAM_TIMES("MPArch.RWH_DidUpdateBackingStore", delta); } void RenderWidgetHostImpl::OnQueueSyntheticGesture(
diff --git a/content/browser/renderer_host/render_widget_host_view_browsertest.cc b/content/browser/renderer_host/render_widget_host_view_browsertest.cc index 3183991..b346290f 100644 --- a/content/browser/renderer_host/render_widget_host_view_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_view_browsertest.cc
@@ -232,11 +232,18 @@ DISALLOW_COPY_AND_ASSIGN(CommitBeforeSwapAckSentHelper); }; -using RenderWidgetHostViewBrowserTestBase = ContentBrowserTest; +class RenderWidgetHostViewBrowserTestBase : public ContentBrowserTest { + public: + ~RenderWidgetHostViewBrowserTestBase() override {} + + protected: + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + } +}; IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewBrowserTestBase, CompositorWorksWhenReusingRenderer) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); auto* web_contents = shell()->web_contents(); // Load a page that draws new frames infinitely.
diff --git a/content/browser/utility_process_host_impl.cc b/content/browser/utility_process_host_impl.cc index 4cb3c3d..a2c181a 100644 --- a/content/browser/utility_process_host_impl.cc +++ b/content/browser/utility_process_host_impl.cc
@@ -319,6 +319,7 @@ switches::kLogNetLog, switches::kNoSandbox, switches::kProfilerTiming, + switches::kProxyServer, switches::kTestingFixedHttpPort, switches::kTestingFixedHttpsPort, #if defined(OS_MACOSX)
diff --git a/content/browser/web_contents/opened_by_dom_browsertest.cc b/content/browser/web_contents/opened_by_dom_browsertest.cc index 699121d..0f506b5 100644 --- a/content/browser/web_contents/opened_by_dom_browsertest.cc +++ b/content/browser/web_contents/opened_by_dom_browsertest.cc
@@ -47,6 +47,10 @@ IsolateAllSitesForTesting(command_line); } + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + } + bool AttemptCloseFromJavaScript(WebContents* web_contents) { CloseTrackingDelegate close_tracking_delegate; WebContentsDelegate* old_delegate = web_contents->GetDelegate(); @@ -114,7 +118,6 @@ // Tests that window.close() works in a popup window that has navigated a few // times and swapped processes. IN_PROC_BROWSER_TEST_F(OpenedByDOMTest, CrossProcessPopup) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); GURL url1 = embedded_test_server()->GetURL("/site_isolation/blank.html?1");
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index cb7fccec..71c3c423 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -68,6 +68,12 @@ ContentBrowserTest::SetUp(); } + void SetUpOnMainThread() override { + // Setup the server to allow serving separate sites, so we can perform + // cross-process navigation. + host_resolver()->AddRule("*", "127.0.0.1"); + } + private: DISALLOW_COPY_AND_ASSIGN(WebContentsImplBrowserTest); }; @@ -436,9 +442,6 @@ net::HostPortPair foo_host_port; GURL cross_site_url; - // Setup the server to allow serving separate sites, so we can perform - // cross-process navigation. - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); foo_host_port = embedded_test_server()->host_port_pair(); @@ -594,7 +597,6 @@ // a DidStopLoading. See http://crbug.com/429399. IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, LoadProgressAfterInterruptedNav) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); // Start at a real page. @@ -1002,7 +1004,6 @@ TestJavaScriptDialogManager dialog_manager; wc->SetDelegate(&dialog_manager); - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); NavigateToURL(shell(), @@ -1281,7 +1282,6 @@ IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, RenderWidgetDeletedWhileMouseLockPending) { - host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(embedded_test_server()->Start()); std::unique_ptr<MouseLockDelegate> delegate(new MouseLockDelegate());
diff --git a/content/common/common_param_traits_unittest.cc b/content/common/common_param_traits_unittest.cc index fd6cd2a..8e5c323 100644 --- a/content/common/common_param_traits_unittest.cc +++ b/content/common/common_param_traits_unittest.cc
@@ -88,9 +88,9 @@ TEST(IPCMessageTest, ListValue) { base::ListValue input; - input.Set(0, new base::Value(42.42)); - input.Set(1, new base::Value("forty")); - input.Set(2, base::MakeUnique<base::Value>()); + input.AppendDouble(42.42); + input.AppendString("forty"); + input.Append(base::MakeUnique<base::Value>()); IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::WriteParam(&msg, input); @@ -111,20 +111,20 @@ TEST(IPCMessageTest, DictionaryValue) { base::DictionaryValue input; input.Set("null", base::MakeUnique<base::Value>()); - input.Set("bool", new base::Value(true)); - input.Set("int", new base::Value(42)); + input.SetBoolean("bool", true); + input.SetInteger("int", 42); - std::unique_ptr<base::DictionaryValue> subdict(new base::DictionaryValue()); - subdict->Set("str", new base::Value("forty two")); - subdict->Set("bool", new base::Value(false)); + auto subdict = base::MakeUnique<base::DictionaryValue>(); + subdict->SetString("str", "forty two"); + subdict->SetBoolean("bool", false); - std::unique_ptr<base::ListValue> sublist(new base::ListValue()); - sublist->Set(0, new base::Value(42.42)); - sublist->Set(1, new base::Value("forty")); - sublist->Set(2, new base::Value("two")); - subdict->Set("list", sublist.release()); + auto sublist = base::MakeUnique<base::ListValue>(); + sublist->AppendDouble(42.42); + sublist->AppendString("forty"); + sublist->AppendString("two"); + subdict->Set("list", std::move(sublist)); - input.Set("dict", subdict.release()); + input.Set("dict", std::move(subdict)); IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::WriteParam(&msg, input);
diff --git a/content/network/network_context.cc b/content/network/network_context.cc index 040a678..c889176 100644 --- a/content/network/network_context.cc +++ b/content/network/network_context.cc
@@ -15,7 +15,8 @@ #include "net/dns/mapped_host_resolver.h" #include "net/log/net_log_util.h" #include "net/log/write_to_file_net_log_observer.h" -#include "net/proxy/proxy_service.h" +#include "net/proxy/proxy_config.h" +#include "net/proxy/proxy_config_service_fixed.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" @@ -58,7 +59,6 @@ } builder.set_accept_language("en-us,en"); builder.set_user_agent(GetContentClient()->GetUserAgent()); - builder.set_proxy_service(net::ProxyService::CreateDirect()); net::URLRequestContextBuilder::HttpCacheParams cache_params; // We store the cache in memory so we can run many shells in parallel when @@ -72,6 +72,17 @@ builder.SetProtocolHandler(url::kDataScheme, base::MakeUnique<net::DataProtocolHandler>()); + if (command_line->HasSwitch(switches::kProxyServer)) { + net::ProxyConfig config; + config.proxy_rules().ParseFromString( + command_line->GetSwitchValueASCII(switches::kProxyServer)); + std::unique_ptr<net::ProxyConfigService> fixed_config_service = + base::MakeUnique<net::ProxyConfigServiceFixed>(config); + builder.set_proxy_config_service(std::move(fixed_config_service)); + } else { + builder.set_proxy_service(net::ProxyService::CreateDirect()); + } + return builder.Build(); }
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 7322b1d..8feb5e30 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -747,6 +747,14 @@ // renderer or plugin host. If it's empty, it's the browser. const char kProcessType[] = "type"; +// Uses a specified proxy server, overrides system settings. This switch only +// affects HTTP and HTTPS requests. ARC-apps use only HTTP proxy server with the +// highest priority. +// TODO(yzshen): Move this switch back to chrome/common/chrome_switches.{h,cc}, +// once the network service is able to access the corresponding setting via the +// pref service. +const char kProxyServer[] = "proxy-server"; + // Enables more web features over insecure connections. Designed to be used // for testing purposes only. const char kReduceSecurityForTesting[] = "reduce-security-for-testing";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index 372092a..b63210d3 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -217,6 +217,7 @@ CONTENT_EXPORT extern const char kProcessPerSite[]; CONTENT_EXPORT extern const char kProcessPerTab[]; CONTENT_EXPORT extern const char kProcessType[]; +CONTENT_EXPORT extern const char kProxyServer[]; CONTENT_EXPORT extern const char kReduceSecurityForTesting[]; CONTENT_EXPORT extern const char kReducedReferrerGranularity[]; CONTENT_EXPORT extern const char kRegisterPepperPlugins[];
diff --git a/content/renderer/media_recorder/vea_encoder.cc b/content/renderer/media_recorder/vea_encoder.cc index 6bff812..ae0c9b0 100644 --- a/content/renderer/media_recorder/vea_encoder.cc +++ b/content/renderer/media_recorder/vea_encoder.cc
@@ -151,8 +151,8 @@ return; } - // Drop frames if there is no output buffers available. - if (output_buffers_.empty()) { + // Drop frames if RequireBitstreamBuffers() hasn't been called. + if (output_buffers_.empty() || vea_requested_input_coded_size_.IsEmpty()) { // TODO(emircan): Investigate if resetting encoder would help. DVLOG(3) << "Might drop frame."; last_frame_.reset(new std::pair<scoped_refptr<VideoFrame>, base::TimeTicks>( @@ -199,6 +199,10 @@ reinterpret_cast<uint8_t*>(input_buffer->memory()), input_buffer->mapped_size(), input_buffer->handle(), 0, frame->timestamp()); + if (!video_frame) { + NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError); + return; + } video_frame->AddDestructionObserver(media::BindToCurrentLoop( base::Bind(&VEAEncoder::FrameFinished, this, base::Passed(std::move(input_buffer))))); @@ -229,6 +233,7 @@ DCHECK_GT(bits_per_second_, 0); input_visible_size_ = size; + vea_requested_input_coded_size_ = gfx::Size(); video_encoder_ = gpu_factories_->CreateVideoEncodeAccelerator(); if (!video_encoder_ || !video_encoder_->Initialize(media::PIXEL_FORMAT_I420, input_visible_size_,
diff --git a/content/renderer/service_worker/service_worker_type_converters.cc b/content/renderer/service_worker/service_worker_type_converters.cc index fa2a709..5f05beea 100644 --- a/content/renderer/service_worker/service_worker_type_converters.cc +++ b/content/renderer/service_worker/service_worker_type_converters.cc
@@ -38,10 +38,10 @@ output.origin = blink::WebString::FromUTF8(input->origin.spec()); output.method_data = - blink::WebVector<blink::WebPaymentMethodData>(input->methodData.size()); - for (size_t i = 0; i < input->methodData.size(); i++) { + blink::WebVector<blink::WebPaymentMethodData>(input->method_data.size()); + for (size_t i = 0; i < input->method_data.size(); i++) { output.method_data[i] = mojo::ConvertTo<blink::WebPaymentMethodData>( - std::move(input->methodData[i])); + std::move(input->method_data[i])); } output.total = mojo::ConvertTo<blink::WebPaymentItem>(input->total); @@ -53,7 +53,7 @@ mojo::ConvertTo<blink::WebPaymentDetailsModifier>(input->modifiers[i]); } - output.option_id = blink::WebString::FromUTF8(input->optionId); + output.option_id = blink::WebString::FromUTF8(input->option_id); return output; }
diff --git a/content/shell/browser/layout_test/layout_test_download_manager_delegate.cc b/content/shell/browser/layout_test/layout_test_download_manager_delegate.cc index 9f7b098..9516f096 100644 --- a/content/shell/browser/layout_test/layout_test_download_manager_delegate.cc +++ b/content/shell/browser/layout_test/layout_test_download_manager_delegate.cc
@@ -35,7 +35,8 @@ bool LayoutTestDownloadManagerDelegate::ShouldOpenDownload( DownloadItem* item, const DownloadOpenDelayedCallback& callback) { - if (BlinkTestController::Get()->IsMainWindow(item->GetWebContents()) && + if (BlinkTestController::Get() && + BlinkTestController::Get()->IsMainWindow(item->GetWebContents()) && item->GetMimeType() == "text/html") { BlinkTestController::Get()->OpenURL( net::FilePathToFileURL(item->GetFullPath()));
diff --git a/content/shell/browser/shell_url_request_context_getter.cc b/content/shell/browser/shell_url_request_context_getter.cc index 3ace069a..3c75eaa 100644 --- a/content/shell/browser/shell_url_request_context_getter.cc +++ b/content/shell/browser/shell_url_request_context_getter.cc
@@ -14,7 +14,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/threading/sequenced_worker_pool.h" +#include "base/task_scheduler/post_task.h" #include "build/build_config.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" @@ -257,8 +257,12 @@ set_protocol = job_factory->SetProtocolHandler( url::kFileScheme, base::MakeUnique<net::FileProtocolHandler>( - BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( - base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))); + base::CreateTaskRunnerWithTraits( + base::TaskTraits() + .MayBlock() + .WithPriority(base::TaskPriority::USER_VISIBLE) + .WithShutdownBehavior( + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN)))); DCHECK(set_protocol); #endif
diff --git a/content/test/browser_test_utils_browsertest.cc b/content/test/browser_test_utils_browsertest.cc index 9303cd3d..a59ef49d 100644 --- a/content/test/browser_test_utils_browsertest.cc +++ b/content/test/browser_test_utils_browsertest.cc
@@ -47,12 +47,16 @@ class CrossSiteRedirectorBrowserTest : public ContentBrowserTest { public: CrossSiteRedirectorBrowserTest() {} + + void SetUpOnMainThread() override { + // Map all hosts to localhost and setup the EmbeddedTestServer for + // redirects. + host_resolver()->AddRule("*", "127.0.0.1"); + } }; IN_PROC_BROWSER_TEST_F(CrossSiteRedirectorBrowserTest, VerifyCrossSiteRedirectURL) { - // Map all hosts to localhost and setup the EmbeddedTestServer for redirects. - host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start());
diff --git a/content/test/data/gpu/pixel_canvas2d_untagged.html b/content/test/data/gpu/pixel_canvas2d_untagged.html new file mode 100644 index 0000000..64e9d23 --- /dev/null +++ b/content/test/data/gpu/pixel_canvas2d_untagged.html
@@ -0,0 +1,48 @@ +<!DOCTYPE HTML> +<html> +<head> +<script> +// This browser pixel test checks if the 2D canvas with no color space tag +// displays the pixels correctly. + +var g_swapsBeforeAck = 15; + +function main() +{ + draw(); + waitForFinish(); +} + +function draw() +{ + var ctx = document.getElementById("c").getContext("2d"); + var image = ctx.createImageData(257, 257); + for(var i = 0 ; i < 257 * 257 ; i++) + { + image.data[4 * i] = 127; + image.data[(4 * i) + 1] = 127; + image.data[(4 * i) + 2] = 127; + image.data[(4 * i) + 3] = 255; + } + ctx.putImageData(image, 0, 0); +} + +function waitForFinish() +{ + if (g_swapsBeforeAck == 0) { + domAutomationController.setAutomationId(1); + domAutomationController.send("SUCCESS"); + } else { + g_swapsBeforeAck--; + document.getElementById('container').style.zIndex = g_swapsBeforeAck + 1; + window.webkitRequestAnimationFrame(waitForFinish); + } +} +</script> +</head> +<body onload="main()"> +<div id="container" style="position:absolute; top:0px; left:0px"> +<canvas id="c" width="257" height="257"></canvas> +</div> +</body> +</html>
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index 73ab14d..01e8a1fc 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -50,5 +50,8 @@ self.Flaky('Pixel_OffscreenCanvas2DResizeOnWorker', ['win10', ('intel', 0x1912)], bug=690663) + # TODO(zakerinasab): check / generate reference images. + self.Fail('Pixel_Canvas2DUntagged', bug=713632) + # TODO(jbauman): Fix this. self.Fail('Pixel_DirectComposition_Video_MP4', ['win', 'intel'], bug=704389)
diff --git a/content/test/gpu/gpu_tests/pixel_test_pages.py b/content/test/gpu/gpu_tests/pixel_test_pages.py index 6228c9a..bebeb63 100644 --- a/content/test/gpu/gpu_tests/pixel_test_pages.py +++ b/content/test/gpu/gpu_tests/pixel_test_pages.py
@@ -55,6 +55,12 @@ revision=7), PixelTestPage( + 'pixel_canvas2d_untagged.html', + base_name + '_Canvas2DUntagged', + test_rect=[0, 0, 257, 257], + revision=0), + + PixelTestPage( 'pixel_css3d.html', base_name + '_CSS3DBlueBox', test_rect=[0, 0, 300, 300],
diff --git a/device/vr/android/gvr/gvr_device.cc b/device/vr/android/gvr/gvr_device.cc index 17a824a4..e86d2f1d 100644 --- a/device/vr/android/gvr/gvr_device.cc +++ b/device/vr/android/gvr/gvr_device.cc
@@ -36,7 +36,13 @@ void GvrDevice::RequestPresent(mojom::VRSubmitFrameClientPtr submit_client, const base::Callback<void(bool)>& callback) { - gvr_provider_->RequestPresent(std::move(submit_client), callback); + GvrDelegateProvider* delegate_provider = gvr_provider_->GetDelegateProvider(); + if (!delegate_provider) + return callback.Run(false); + + // RequestWebVRPresent is async as we may trigger a DON flow that pauses + // Chrome. + delegate_provider->RequestWebVRPresent(std::move(submit_client), callback); } void GvrDevice::SetSecureOrigin(bool secure_origin) { @@ -47,7 +53,9 @@ } void GvrDevice::ExitPresent() { - gvr_provider_->ExitPresent(); + GvrDelegateProvider* delegate_provider = gvr_provider_->GetDelegateProvider(); + if (delegate_provider) + delegate_provider->ExitWebVRPresent(); OnExitPresent(); }
diff --git a/device/vr/android/gvr/gvr_device_provider.cc b/device/vr/android/gvr/gvr_device_provider.cc index 65d8cdc..9955078 100644 --- a/device/vr/android/gvr/gvr_device_provider.cc +++ b/device/vr/android/gvr/gvr_device_provider.cc
@@ -4,17 +4,9 @@ #include "device/vr/android/gvr/gvr_device_provider.h" -#include <jni.h> - -#include "base/android/context_utils.h" -#include "base/android/jni_android.h" -#include "base/android/jni_utils.h" -#include "base/android/scoped_java_ref.h" #include "device/vr/android/gvr/gvr_delegate_provider.h" #include "device/vr/android/gvr/gvr_device.h" #include "device/vr/vr_device.h" -#include "device/vr/vr_device_manager.h" -#include "device/vr/vr_service.mojom.h" namespace device { @@ -49,25 +41,6 @@ provider->SetDeviceProvider(this); } -void GvrDeviceProvider::RequestPresent( - mojom::VRSubmitFrameClientPtr submit_client, - const base::Callback<void(bool)>& callback) { - GvrDelegateProvider* delegate_provider = GetDelegateProvider(); - if (!delegate_provider) - return callback.Run(false); - - // RequestWebVRPresent is async as we may trigger a DON flow that pauses - // Chrome. - delegate_provider->RequestWebVRPresent(std::move(submit_client), callback); -} - -// VR presentation exit requested by the API. -void GvrDeviceProvider::ExitPresent() { - GvrDelegateProvider* delegate_provider = GetDelegateProvider(); - if (delegate_provider) - delegate_provider->ExitWebVRPresent(); -} - void GvrDeviceProvider::SetListeningForActivate(bool listening) { GvrDelegateProvider* delegate_provider = GetDelegateProvider(); if (!delegate_provider)
diff --git a/device/vr/android/gvr/gvr_device_provider.h b/device/vr/android/gvr/gvr_device_provider.h index d215e603..57d2323 100644 --- a/device/vr/android/gvr/gvr_device_provider.h +++ b/device/vr/android/gvr/gvr_device_provider.h
@@ -7,11 +7,9 @@ #include <memory> -#include "base/callback.h" #include "base/macros.h" #include "device/vr/vr_device_provider.h" #include "device/vr/vr_export.h" -#include "device/vr/vr_service.mojom.h" namespace device { @@ -28,11 +26,6 @@ void SetListeningForActivate(bool listening) override; - // Called from GvrDevice. - void RequestPresent(mojom::VRSubmitFrameClientPtr submit_client, - const base::Callback<void(bool)>& callback); - void ExitPresent(); - device::GvrDelegateProvider* GetDelegateProvider(); GvrDevice* Device() { return vr_device_.get(); }
diff --git a/extensions/browser/api/declarative/declarative_api.cc b/extensions/browser/api/declarative/declarative_api.cc index 863f92ed..8049813f 100644 --- a/extensions/browser/api/declarative/declarative_api.cc +++ b/extensions/browser/api/declarative/declarative_api.cc
@@ -58,7 +58,7 @@ if (iter->IsType(base::Value::Type::BINARY)) { base::Value* binary = NULL; if (args->GetBinary(index, &binary)) - args->Set(index, ConvertBinaryToBase64(binary).release()); + args->Set(index, ConvertBinaryToBase64(binary)); } else if (iter->IsType(base::Value::Type::LIST)) { base::ListValue* list; iter->GetAsList(&list);
diff --git a/extensions/browser/api/device_permissions_manager.cc b/extensions/browser/api/device_permissions_manager.cc index 38b2c76..fc33617 100644 --- a/extensions/browser/api/device_permissions_manager.cc +++ b/extensions/browser/api/device_permissions_manager.cc
@@ -151,7 +151,7 @@ if (!MatchesDevicePermissionEntry(dict_value, entry)) { continue; } - devices->Set(i, entry->ToValue().release()); + devices->Set(i, entry->ToValue()); break; } }
diff --git a/extensions/common/extension_l10n_util.cc b/extensions/common/extension_l10n_util.cc index 4422ca3..ac0ac641 100644 --- a/extensions/common/extension_l10n_util.cc +++ b/extensions/common/extension_l10n_util.cc
@@ -15,6 +15,7 @@ #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -92,7 +93,7 @@ std::string result; if (list->GetString(i, &result)) { if (messages.ReplaceMessages(&result, error)) - list->Set(i, new base::Value(result)); + list->Set(i, base::MakeUnique<base::Value>(result)); else ret = false; }
diff --git a/extensions/renderer/BUILD.gn b/extensions/renderer/BUILD.gn index e978448..c7e2e16d 100644 --- a/extensions/renderer/BUILD.gn +++ b/extensions/renderer/BUILD.gn
@@ -36,6 +36,8 @@ "api_event_handler.h", "api_event_listeners.cc", "api_event_listeners.h", + "api_invocation_errors.cc", + "api_invocation_errors.h", "api_last_error.cc", "api_last_error.h", "api_request_handler.cc", @@ -311,6 +313,7 @@ "api_bindings_system_unittest.h", "api_event_handler_unittest.cc", "api_event_listeners_unittest.cc", + "api_invocation_errors_unittest.cc", "api_last_error_unittest.cc", "api_request_handler_unittest.cc", "api_test_base.cc",
diff --git a/extensions/renderer/api_invocation_errors.cc b/extensions/renderer/api_invocation_errors.cc new file mode 100644 index 0000000..34d147f --- /dev/null +++ b/extensions/renderer/api_invocation_errors.cc
@@ -0,0 +1,100 @@ +// 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 "extensions/renderer/api_invocation_errors.h" + +#include <vector> + +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" + +namespace extensions { +namespace api_errors { + +const char kTypeString[] = "string"; +const char kTypeDouble[] = "number"; +const char kTypeBoolean[] = "boolean"; +const char kTypeInteger[] = "integer"; +const char kTypeObject[] = "object"; +const char kTypeList[] = "array"; +const char kTypeBinary[] = "binary"; +const char kTypeFunction[] = "function"; +const char kTypeUndefined[] = "undefined"; +const char kTypeNull[] = "null"; + +std::string InvalidEnumValue(const std::set<std::string>& valid_enums) { + std::vector<base::StringPiece> options(valid_enums.begin(), + valid_enums.end()); + std::string options_str = base::JoinString(options, ", "); + return base::StringPrintf("Value must be one of %s.", options_str.c_str()); +} + +std::string MissingRequiredProperty(const char* property_name) { + return base::StringPrintf("Missing required property '%s'.", property_name); +} + +std::string UnexpectedProperty(const char* property_name) { + return base::StringPrintf("Unexpected property: '%s'.", property_name); +} + +std::string TooFewArrayItems(int minimum, int found) { + return base::StringPrintf("Array must have at least %d items; found %d.", + minimum, found); +} + +std::string TooManyArrayItems(int maximum, int found) { + return base::StringPrintf("Array must have at most %d items; found %d.", + maximum, found); +} + +std::string TooFewStringChars(int minimum, int found) { + return base::StringPrintf( + "String must have at least %d characters; found %d.", minimum, found); +} + +std::string TooManyStringChars(int maximum, int found) { + return base::StringPrintf("String must have at most %d characters; found %d.", + maximum, found); +} + +std::string NumberTooSmall(int minimum) { + return base::StringPrintf("Value must be at least %d.", minimum); +} + +std::string NumberTooLarge(int maximum) { + return base::StringPrintf("Value must be at most %d.", maximum); +} + +std::string InvalidType(const char* expected_type, const char* actual_type) { + return base::StringPrintf("Invalid type: expected %s, found %s.", + expected_type, actual_type); +} + +std::string NotAnInstance(const char* instance_type) { + return base::StringPrintf("Value must be an instance of %s.", instance_type); +} + +std::string InvalidChoice() { + return "Value did not match any choice."; +} + +std::string UnserializableValue() { + return "Value is unserializable."; +} + +std::string ScriptThrewError() { + return "Script threw an error."; +} + +std::string IndexError(uint32_t index, const std::string& error) { + return base::StringPrintf("Error at index %u: %s", index, error.c_str()); +} + +std::string PropertyError(const char* property_name, const std::string& error) { + return base::StringPrintf("Error at property '%s': %s", property_name, + error.c_str()); +} + +} // namespace api_errors +} // namespace extensions
diff --git a/extensions/renderer/api_invocation_errors.h b/extensions/renderer/api_invocation_errors.h new file mode 100644 index 0000000..4458b6dc --- /dev/null +++ b/extensions/renderer/api_invocation_errors.h
@@ -0,0 +1,58 @@ +// 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 EXTENSIONS_RENDERER_API_INVOCATION_ERRORS_H_ +#define EXTENSIONS_RENDERER_API_INVOCATION_ERRORS_H_ + +#include <set> +#include <string> + +#include "base/strings/string_piece.h" + +// A collection of error-related strings and utilities for parsing API +// invocations. +namespace extensions { +namespace api_errors { + +// Strings for the expected types. +extern const char kTypeString[]; +extern const char kTypeDouble[]; +extern const char kTypeBoolean[]; +extern const char kTypeInteger[]; +extern const char kTypeObject[]; +extern const char kTypeList[]; +extern const char kTypeBinary[]; +extern const char kTypeFunction[]; +extern const char kTypeUndefined[]; +extern const char kTypeNull[]; + +// Methods to return a formatted string describing an error related to argument +// parsing. +std::string InvalidEnumValue(const std::set<std::string>& valid_enums); +std::string MissingRequiredProperty(const char* property_name); +std::string UnexpectedProperty(const char* property_name); +std::string TooFewArrayItems(int minimum, int found); +std::string TooManyArrayItems(int maximum, int found); +std::string TooFewStringChars(int minimum, int found); +std::string TooManyStringChars(int maximum, int found); +std::string NumberTooSmall(int minimum); +std::string NumberTooLarge(int maximum); +std::string InvalidType(const char* expected_type, const char* actual_type); +std::string NotAnInstance(const char* instance_type); +std::string InvalidChoice(); +std::string UnserializableValue(); +std::string ScriptThrewError(); + +// Returns an message indicating an error was found while parsing a given index +// in an array. +std::string IndexError(uint32_t index, const std::string& error); + +// Returns a message indicating that an error was found while parsing a given +// property on an object. +std::string PropertyError(const char* property_name, const std::string& error); + +} // namespace api_errors +} // namespace extensions + +#endif // EXTENSIONS_RENDERER_API_INVOCATION_ERRORS_H_
diff --git a/extensions/renderer/api_invocation_errors_unittest.cc b/extensions/renderer/api_invocation_errors_unittest.cc new file mode 100644 index 0000000..2149cc5 --- /dev/null +++ b/extensions/renderer/api_invocation_errors_unittest.cc
@@ -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. + +#include "extensions/renderer/api_invocation_errors.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { +namespace api_errors { + +// Tests chaining errors for more complicated errors. More of a set of example +// strings than a test of the logic itself (which is pretty simple). +TEST(APIInvocationErrors, ChainedErrors) { + EXPECT_EQ("Error at index 0: Invalid type: expected string, found integer.", + IndexError(0, InvalidType(kTypeString, kTypeInteger))); + EXPECT_EQ( + "Error at property 'foo': Invalid type: expected string, found integer.", + PropertyError("foo", InvalidType(kTypeString, kTypeInteger))); + EXPECT_EQ( + "Error at property 'foo': Error at index 1: " + "Invalid type: expected string, found integer.", + PropertyError("foo", + IndexError(1, InvalidType(kTypeString, kTypeInteger)))); +} + +} // namespace api_errors +} // namespace extensions
diff --git a/extensions/renderer/argument_spec.cc b/extensions/renderer/argument_spec.cc index fd3e1a97..0876859 100644 --- a/extensions/renderer/argument_spec.cc +++ b/extensions/renderer/argument_spec.cc
@@ -5,9 +5,10 @@ #include "extensions/renderer/argument_spec.h" #include "base/memory/ptr_util.h" -#include "base/strings/stringprintf.h" +#include "base/strings/string_piece.h" #include "base/values.h" #include "content/public/child/v8_value_converter.h" +#include "extensions/renderer/api_invocation_errors.h" #include "extensions/renderer/api_type_reference_map.h" #include "gin/converter.h" #include "gin/dictionary.h" @@ -16,21 +17,56 @@ namespace { +// Returns a type string for the given |value|. +const char* GetV8ValueTypeString(v8::Local<v8::Value> value) { + DCHECK(!value.IsEmpty()); + + if (value->IsNull()) + return api_errors::kTypeNull; + if (value->IsUndefined()) + return api_errors::kTypeUndefined; + if (value->IsInt32()) + return api_errors::kTypeInteger; + if (value->IsNumber()) + return api_errors::kTypeDouble; + if (value->IsBoolean()) + return api_errors::kTypeBoolean; + if (value->IsString()) + return api_errors::kTypeString; + + // Note: check IsArray(), IsFunction(), and IsArrayBuffer[View]() before + // IsObject() since arrays, functions, and array buffers are objects. + if (value->IsArray()) + return api_errors::kTypeList; + if (value->IsFunction()) + return api_errors::kTypeFunction; + if (value->IsArrayBuffer() || value->IsArrayBufferView()) + return api_errors::kTypeBinary; + if (value->IsObject()) + return api_errors::kTypeObject; + + // TODO(devlin): The list above isn't exhaustive (it's missing at least + // Symbol and Uint32). We may want to include those, since saying + // "expected int, found other" isn't super helpful. On the other hand, authors + // should be able to see what they passed. + return "other"; +} + +// Returns true if |value| is within the bounds specified by |minimum| and +// |maximum|, populating |error| otherwise. template <class T> -bool ParseFundamentalValueHelper(v8::Local<v8::Value> arg, - v8::Local<v8::Context> context, - const base::Optional<int>& minimum, - const base::Optional<int>& maximum, - std::unique_ptr<base::Value>* out_value) { - T val; - if (!gin::Converter<T>::FromV8(context->GetIsolate(), arg, &val)) +bool CheckFundamentalBounds(T value, + const base::Optional<int>& minimum, + const base::Optional<int>& maximum, + std::string* error) { + if (minimum && value < *minimum) { + *error = api_errors::NumberTooSmall(*minimum); return false; - if (minimum && val < *minimum) + } + if (maximum && value > *maximum) { + *error = api_errors::NumberTooLarge(*maximum); return false; - if (maximum && val > *maximum) - return false; - if (out_value) - *out_value = base::MakeUnique<base::Value>(val); + } return true; } @@ -168,8 +204,10 @@ std::unique_ptr<base::Value>* out_value, std::string* error) const { if (type_ == ArgumentType::FUNCTION) { - if (!value->IsFunction()) + if (!value->IsFunction()) { + *error = GetInvalidTypeError(value); return false; + } if (out_value) { // Certain APIs (contextMenus) have functions as parameters other than the @@ -194,7 +232,7 @@ if (choice->ParseArgument(context, value, refs, out_value, error)) return true; } - *error = "Did not match any of the choices"; + *error = api_errors::InvalidChoice(); return false; } @@ -207,7 +245,7 @@ // parameter and then an optional callback, we wouldn't necessarily be able // to match the arguments if we allowed functions as objects. if (!value->IsObject() || value->IsFunction() || value->IsArray()) { - *error = "Wrong type"; + *error = GetInvalidTypeError(value); return false; } v8::Local<v8::Object> object = value.As<v8::Object>(); @@ -215,7 +253,7 @@ } if (type_ == ArgumentType::LIST) { if (!value->IsArray()) { - *error = "Wrong type"; + *error = GetInvalidTypeError(value); return false; } v8::Local<v8::Array> array = value.As<v8::Array>(); @@ -223,7 +261,7 @@ } if (type_ == ArgumentType::BINARY) { if (!value->IsArrayBuffer() && !value->IsArrayBufferView()) { - *error = "Wrong type"; + *error = GetInvalidTypeError(value); return false; } return ParseArgumentToAny(context, value, out_value, error); @@ -245,26 +283,47 @@ std::unique_ptr<base::Value>* out_value, std::string* error) const { DCHECK(IsFundamentalType()); + switch (type_) { - case ArgumentType::INTEGER: - return ParseFundamentalValueHelper<int32_t>(value, context, minimum_, - maximum_, out_value); - case ArgumentType::DOUBLE: - return ParseFundamentalValueHelper<double>(value, context, minimum_, - maximum_, out_value); - case ArgumentType::STRING: { - if (!value->IsString()) + case ArgumentType::INTEGER: { + if (!value->IsInt32()) { + *error = GetInvalidTypeError(value); return false; + } + int int_val = value.As<v8::Int32>()->Value(); + if (!CheckFundamentalBounds(int_val, minimum_, maximum_, error)) + return false; + if (out_value) + *out_value = base::MakeUnique<base::Value>(int_val); + return true; + } + case ArgumentType::DOUBLE: { + if (!value->IsNumber()) { + *error = GetInvalidTypeError(value); + return false; + } + double double_val = value.As<v8::Number>()->Value(); + if (!CheckFundamentalBounds(double_val, minimum_, maximum_, error)) + return false; + if (out_value) + *out_value = base::MakeUnique<base::Value>(double_val); + return true; + } + case ArgumentType::STRING: { + if (!value->IsString()) { + *error = GetInvalidTypeError(value); + return false; + } v8::Local<v8::String> v8_string = value.As<v8::String>(); size_t length = static_cast<size_t>(v8_string->Length()); if (min_length_ && length < *min_length_) { - *error = "Less than min length"; + *error = api_errors::TooFewStringChars(*min_length_, length); return false; } if (max_length_ && length > *max_length_) { - *error = "Greater than max length"; + *error = api_errors::TooManyStringChars(*max_length_, length); return false; } @@ -277,8 +336,10 @@ // We already checked that this is a string, so this should never fail. CHECK(gin::Converter<std::string>::FromV8(context->GetIsolate(), value, &s)); - if (!enum_values_.empty() && enum_values_.count(s) == 0) + if (!enum_values_.empty() && enum_values_.count(s) == 0) { + *error = api_errors::InvalidEnumValue(enum_values_); return false; + } if (out_value) { // TODO(devlin): If base::Value ever takes a std::string&&, we // could use std::move to construct. @@ -287,8 +348,10 @@ return true; } case ArgumentType::BOOLEAN: { - if (!value->IsBoolean()) + if (!value->IsBoolean()) { + *error = GetInvalidTypeError(value); return false; + } if (out_value) { *out_value = base::MakeUnique<base::Value>(value.As<v8::Boolean>()->Value()); @@ -314,17 +377,22 @@ result = base::MakeUnique<base::DictionaryValue>(); v8::Local<v8::Array> own_property_names; - if (!object->GetOwnPropertyNames(context).ToLocal(&own_property_names)) + if (!object->GetOwnPropertyNames(context).ToLocal(&own_property_names)) { + *error = api_errors::ScriptThrewError(); return false; + } // Track all properties we see from |properties_| to check if any are missing. // Use ArgumentSpec* instead of std::string for comparison + copy efficiency. std::set<const ArgumentSpec*> seen_properties; uint32_t length = own_property_names->Length(); + std::string property_error; for (uint32_t i = 0; i < length; ++i) { v8::Local<v8::Value> key; - if (!own_property_names->Get(context, i).ToLocal(&key)) + if (!own_property_names->Get(context, i).ToLocal(&key)) { + *error = api_errors::ScriptThrewError(); return false; + } // In JS, all keys are strings or numbers (or symbols, but those are // excluded by GetOwnPropertyNames()). If you try to set anything else // (e.g. an object), it is converted to a string. @@ -339,7 +407,7 @@ } else if (additional_properties_) { property_spec = additional_properties_.get(); } else { - *error = base::StringPrintf("Unknown property: %s", *utf8_key); + *error = api_errors::UnexpectedProperty(*utf8_key); return false; } @@ -359,7 +427,7 @@ // TODO(devlin): This matches current behavior, but it is correct? if (prop_value->IsUndefined() || prop_value->IsNull()) { if (!property_spec->optional_) { - *error = base::StringPrintf("Missing key: %s", *utf8_key); + *error = api_errors::MissingRequiredProperty(*utf8_key); return false; } continue; @@ -367,7 +435,9 @@ std::unique_ptr<base::Value> property; if (!property_spec->ParseArgument(context, prop_value, refs, - result ? &property : nullptr, error)) { + result ? &property : nullptr, + &property_error)) { + *error = api_errors::PropertyError(*utf8_key, property_error); return false; } if (result) @@ -377,7 +447,7 @@ for (const auto& pair : properties_) { const ArgumentSpec* spec = pair.second.get(); if (!spec->optional_ && seen_properties.count(spec) == 0) { - *error = "Missing key: " + pair.first; + *error = api_errors::MissingRequiredProperty(pair.first.c_str()); return false; } } @@ -410,7 +480,7 @@ } while (next_check->IsObject()); if (!found) { - *error = "Object is not of correct instance"; + *error = api_errors::NotAnInstance(instance_of_->c_str()); return false; } } @@ -429,12 +499,12 @@ uint32_t length = value->Length(); if (min_length_ && length < *min_length_) { - *error = "Less than min length"; + *error = api_errors::TooFewArrayItems(*min_length_, length); return false; } if (max_length_ && length > *max_length_) { - *error = "Greater than max length"; + *error = api_errors::TooManyArrayItems(*max_length_, length); return false; } @@ -443,6 +513,7 @@ if (out_value) result = base::MakeUnique<base::ListValue>(); + std::string item_error; for (uint32_t i = 0; i < length; ++i) { v8::MaybeLocal<v8::Value> maybe_subvalue = value->Get(context, i); v8::Local<v8::Value> subvalue; @@ -456,8 +527,9 @@ if (!maybe_subvalue.ToLocal(&subvalue)) return false; std::unique_ptr<base::Value> item; - if (!list_element_type_->ParseArgument(context, subvalue, refs, - result ? &item : nullptr, error)) { + if (!list_element_type_->ParseArgument( + context, subvalue, refs, result ? &item : nullptr, &item_error)) { + *error = api_errors::IndexError(i, item_error); return false; } if (result) @@ -479,7 +551,7 @@ std::unique_ptr<base::Value> converted( converter->FromV8Value(value, context)); if (!converted) { - *error = "Could not convert to 'any'."; + *error = api_errors::UnserializableValue(); return false; } if (type_ == ArgumentType::BINARY) @@ -489,4 +561,44 @@ return true; } +std::string ArgumentSpec::GetInvalidTypeError( + v8::Local<v8::Value> value) const { + const char* expected_type = nullptr; + switch (type_) { + case ArgumentType::INTEGER: + expected_type = api_errors::kTypeInteger; + break; + case ArgumentType::DOUBLE: + expected_type = api_errors::kTypeDouble; + break; + case ArgumentType::BOOLEAN: + expected_type = api_errors::kTypeBoolean; + break; + case ArgumentType::STRING: + expected_type = api_errors::kTypeString; + break; + case ArgumentType::OBJECT: + expected_type = + instance_of_ ? instance_of_->c_str() : api_errors::kTypeObject; + break; + case ArgumentType::LIST: + expected_type = api_errors::kTypeList; + break; + case ArgumentType::BINARY: + expected_type = api_errors::kTypeBinary; + break; + case ArgumentType::FUNCTION: + expected_type = api_errors::kTypeFunction; + break; + case ArgumentType::REF: + expected_type = ref_->c_str(); + break; + case ArgumentType::CHOICES: + case ArgumentType::ANY: + NOTREACHED(); + } + + return api_errors::InvalidType(expected_type, GetV8ValueTypeString(value)); +} + } // namespace extensions
diff --git a/extensions/renderer/argument_spec.h b/extensions/renderer/argument_spec.h index 66b87a1..922d992 100644 --- a/extensions/renderer/argument_spec.h +++ b/extensions/renderer/argument_spec.h
@@ -113,6 +113,10 @@ std::unique_ptr<base::Value>* out_value, std::string* error) const; + // Returns an error message indicating the type of |value| does not match the + // expected type. + std::string GetInvalidTypeError(v8::Local<v8::Value> value) const; + // The name of the argument. std::string name_;
diff --git a/extensions/renderer/argument_spec_unittest.cc b/extensions/renderer/argument_spec_unittest.cc index 4bf8d25..2b2e491 100644 --- a/extensions/renderer/argument_spec_unittest.cc +++ b/extensions/renderer/argument_spec_unittest.cc
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "extensions/renderer/argument_spec.h" #include "base/memory/ptr_util.h" #include "base/values.h" #include "extensions/renderer/api_binding_test_util.h" +#include "extensions/renderer/api_invocation_errors.h" #include "extensions/renderer/api_type_reference_map.h" -#include "extensions/renderer/argument_spec.h" #include "gin/converter.h" #include "gin/public/isolate_holder.h" #include "gin/test/v8_test.h" @@ -20,44 +21,77 @@ ArgumentSpecUnitTest() : type_refs_(APITypeReferenceMap::InitializeTypeCallback()) {} ~ArgumentSpecUnitTest() override {} + + enum class TestResult { + PASS, + FAIL, + THROW, + }; + + struct RunTestParams { + RunTestParams(const ArgumentSpec& spec, + base::StringPiece script_source, + TestResult result) + : spec(spec), script_source(script_source), expected_result(result) {} + + const ArgumentSpec& spec; + base::StringPiece script_source; + TestResult expected_result; + base::StringPiece expected_json; + base::StringPiece expected_error; + base::StringPiece expected_thrown_message; + const base::Value* expected_value = nullptr; + bool should_convert = true; + }; + void ExpectSuccess(const ArgumentSpec& spec, const std::string& script_source, const std::string& expected_json_single_quotes) { - RunTest(spec, script_source, true, TestResult::PASS, - ReplaceSingleQuotes(expected_json_single_quotes), nullptr, - std::string()); + RunTestParams params(spec, script_source, TestResult::PASS); + std::string expected_json = + ReplaceSingleQuotes(expected_json_single_quotes); + params.expected_json = expected_json; + RunTest(params); } void ExpectSuccess(const ArgumentSpec& spec, const std::string& script_source, const base::Value& expected_value) { - RunTest(spec, script_source, true, TestResult::PASS, std::string(), - &expected_value, std::string()); + RunTestParams params(spec, script_source, TestResult::PASS); + params.expected_value = &expected_value; + RunTest(params); } void ExpectSuccessWithNoConversion(const ArgumentSpec& spec, const std::string& script_source) { - RunTest(spec, script_source, false, TestResult::PASS, std::string(), - nullptr, std::string()); + RunTestParams params(spec, script_source, TestResult::PASS); + params.should_convert = false; + RunTest(params); } void ExpectFailure(const ArgumentSpec& spec, - const std::string& script_source) { - RunTest(spec, script_source, true, TestResult::FAIL, std::string(), nullptr, - std::string()); + const std::string& script_source, + const std::string& expected_error) { + RunTestParams params(spec, script_source, TestResult::FAIL); + params.expected_error = expected_error; + RunTest(params); } void ExpectFailureWithNoConversion(const ArgumentSpec& spec, - const std::string& script_source) { - RunTest(spec, script_source, false, TestResult::FAIL, std::string(), - nullptr, std::string()); + const std::string& script_source, + const std::string& expected_error) { + RunTestParams params(spec, script_source, TestResult::FAIL); + params.should_convert = false; + params.expected_error = expected_error; + RunTest(params); } void ExpectThrow(const ArgumentSpec& spec, const std::string& script_source, const std::string& expected_thrown_message) { - RunTest(spec, script_source, true, TestResult::THROW, std::string(), - nullptr, expected_thrown_message); + RunTestParams params(spec, script_source, TestResult::THROW); + params.expected_thrown_message = expected_thrown_message; + RunTest(params); } void AddTypeRef(const std::string& id, std::unique_ptr<ArgumentSpec> spec) { @@ -65,73 +99,68 @@ } private: - enum class TestResult { PASS, FAIL, THROW, }; - - void RunTest(const ArgumentSpec& spec, - const std::string& script_source, - bool should_convert, - TestResult expected_result, - const std::string& expected_json, - const base::Value* expected_value, - const std::string& expected_thrown_message); + void RunTest(const RunTestParams& params); APITypeReferenceMap type_refs_; DISALLOW_COPY_AND_ASSIGN(ArgumentSpecUnitTest); }; -void ArgumentSpecUnitTest::RunTest(const ArgumentSpec& spec, - const std::string& script_source, - bool should_convert, - TestResult expected_result, - const std::string& expected_json, - const base::Value* expected_value, - const std::string& expected_thrown_message) { +void ArgumentSpecUnitTest::RunTest(const RunTestParams& params) { v8::Isolate* isolate = instance_->isolate(); v8::HandleScope handle_scope(instance_->isolate()); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(instance_->isolate(), context_); v8::TryCatch try_catch(isolate); - v8::Local<v8::Value> val = V8ValueFromScriptSource(context, script_source); - ASSERT_FALSE(val.IsEmpty()) << script_source; + v8::Local<v8::Value> val = + V8ValueFromScriptSource(context, params.script_source); + ASSERT_FALSE(val.IsEmpty()) << params.script_source; std::string error; std::unique_ptr<base::Value> out_value; - bool did_succeed = - spec.ParseArgument(context, val, type_refs_, - should_convert ? &out_value : nullptr, &error); - bool should_succeed = expected_result == TestResult::PASS; - ASSERT_EQ(should_succeed, did_succeed) << script_source << ", " << error; - ASSERT_EQ(did_succeed && should_convert, !!out_value); - bool should_throw = expected_result == TestResult::THROW; - ASSERT_EQ(should_throw, try_catch.HasCaught()) << script_source; - if (should_succeed && should_convert) { + bool did_succeed = params.spec.ParseArgument( + context, val, type_refs_, params.should_convert ? &out_value : nullptr, + &error); + bool should_succeed = params.expected_result == TestResult::PASS; + ASSERT_EQ(should_succeed, did_succeed) + << params.script_source << ", " << error; + ASSERT_EQ(did_succeed && params.should_convert, !!out_value); + bool should_throw = params.expected_result == TestResult::THROW; + ASSERT_EQ(should_throw, try_catch.HasCaught()) << params.script_source; + + if (!params.expected_error.empty()) + EXPECT_EQ(params.expected_error, error) << params.script_source; + + if (should_succeed && params.should_convert) { ASSERT_TRUE(out_value); - if (expected_value) - EXPECT_TRUE(expected_value->Equals(out_value.get())) << script_source; + if (params.expected_value) + EXPECT_TRUE(params.expected_value->Equals(out_value.get())) + << params.script_source; else - EXPECT_EQ(expected_json, ValueToString(*out_value)); + EXPECT_EQ(params.expected_json, ValueToString(*out_value)); } else if (should_throw) { - EXPECT_EQ(expected_thrown_message, + EXPECT_EQ(params.expected_thrown_message, gin::V8ToString(try_catch.Message()->Get())); } } TEST_F(ArgumentSpecUnitTest, Test) { + using namespace api_errors; + { ArgumentSpec spec(*ValueFromString("{'type': 'integer'}")); ExpectSuccess(spec, "1", "1"); ExpectSuccess(spec, "-1", "-1"); ExpectSuccess(spec, "0", "0"); ExpectSuccess(spec, "0.0", "0"); - ExpectFailure(spec, "undefined"); - ExpectFailure(spec, "null"); - ExpectFailure(spec, "1.1"); - ExpectFailure(spec, "'foo'"); - ExpectFailure(spec, "'1'"); - ExpectFailure(spec, "{}"); - ExpectFailure(spec, "[1]"); + ExpectFailure(spec, "undefined", InvalidType(kTypeInteger, kTypeUndefined)); + ExpectFailure(spec, "null", InvalidType(kTypeInteger, kTypeNull)); + ExpectFailure(spec, "1.1", InvalidType(kTypeInteger, kTypeDouble)); + ExpectFailure(spec, "'foo'", InvalidType(kTypeInteger, kTypeString)); + ExpectFailure(spec, "'1'", InvalidType(kTypeInteger, kTypeString)); + ExpectFailure(spec, "({})", InvalidType(kTypeInteger, kTypeObject)); + ExpectFailure(spec, "[1]", InvalidType(kTypeInteger, kTypeList)); } { @@ -142,69 +171,71 @@ ExpectSuccess(spec, "1.1", "1.1"); ExpectSuccess(spec, "1.", "1.0"); ExpectSuccess(spec, ".1", "0.1"); - ExpectFailure(spec, "undefined"); - ExpectFailure(spec, "null"); - ExpectFailure(spec, "'foo'"); - ExpectFailure(spec, "'1.1'"); - ExpectFailure(spec, "{}"); - ExpectFailure(spec, "[1.1]"); + ExpectFailure(spec, "undefined", InvalidType(kTypeDouble, kTypeUndefined)); + ExpectFailure(spec, "null", InvalidType(kTypeDouble, kTypeNull)); + ExpectFailure(spec, "'foo'", InvalidType(kTypeDouble, kTypeString)); + ExpectFailure(spec, "'1.1'", InvalidType(kTypeDouble, kTypeString)); + ExpectFailure(spec, "({})", InvalidType(kTypeDouble, kTypeObject)); + ExpectFailure(spec, "[1.1]", InvalidType(kTypeDouble, kTypeList)); } { ArgumentSpec spec(*ValueFromString("{'type': 'integer', 'minimum': 1}")); ExpectSuccess(spec, "2", "2"); ExpectSuccess(spec, "1", "1"); - ExpectFailure(spec, "0"); - ExpectFailure(spec, "-1"); + ExpectFailure(spec, "0", NumberTooSmall(1)); + ExpectFailure(spec, "-1", NumberTooSmall(1)); } { ArgumentSpec spec(*ValueFromString("{'type': 'integer', 'maximum': 10}")); ExpectSuccess(spec, "10", "10"); ExpectSuccess(spec, "1", "1"); - ExpectFailure(spec, "11"); + ExpectFailure(spec, "11", NumberTooLarge(10)); } { ArgumentSpec spec(*ValueFromString("{'type': 'string'}")); ExpectSuccess(spec, "'foo'", "'foo'"); ExpectSuccess(spec, "''", "''"); - ExpectFailure(spec, "1"); - ExpectFailure(spec, "{}"); - ExpectFailure(spec, "['foo']"); + ExpectFailure(spec, "1", InvalidType(kTypeString, kTypeInteger)); + ExpectFailure(spec, "({})", InvalidType(kTypeString, kTypeObject)); + ExpectFailure(spec, "['foo']", InvalidType(kTypeString, kTypeList)); } { ArgumentSpec spec( *ValueFromString("{'type': 'string', 'enum': ['foo', 'bar']}")); + std::set<std::string> valid_enums = {"foo", "bar"}; ExpectSuccess(spec, "'foo'", "'foo'"); ExpectSuccess(spec, "'bar'", "'bar'"); - ExpectFailure(spec, "['foo']"); - ExpectFailure(spec, "'fo'"); - ExpectFailure(spec, "'foobar'"); - ExpectFailure(spec, "'baz'"); - ExpectFailure(spec, "''"); + ExpectFailure(spec, "['foo']", InvalidType(kTypeString, kTypeList)); + ExpectFailure(spec, "'fo'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "'foobar'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "'baz'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "''", InvalidEnumValue(valid_enums)); } { ArgumentSpec spec(*ValueFromString( "{'type': 'string', 'enum': [{'name': 'foo'}, {'name': 'bar'}]}")); + std::set<std::string> valid_enums = {"foo", "bar"}; ExpectSuccess(spec, "'foo'", "'foo'"); ExpectSuccess(spec, "'bar'", "'bar'"); - ExpectFailure(spec, "['foo']"); - ExpectFailure(spec, "'fo'"); - ExpectFailure(spec, "'foobar'"); - ExpectFailure(spec, "'baz'"); - ExpectFailure(spec, "''"); + ExpectFailure(spec, "['foo']", InvalidType(kTypeString, kTypeList)); + ExpectFailure(spec, "'fo'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "'foobar'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "'baz'", InvalidEnumValue(valid_enums)); + ExpectFailure(spec, "''", InvalidEnumValue(valid_enums)); } { ArgumentSpec spec(*ValueFromString("{'type': 'boolean'}")); ExpectSuccess(spec, "true", "true"); ExpectSuccess(spec, "false", "false"); - ExpectFailure(spec, "1"); - ExpectFailure(spec, "'true'"); - ExpectFailure(spec, "null"); + ExpectFailure(spec, "1", InvalidType(kTypeBoolean, kTypeInteger)); + ExpectFailure(spec, "'true'", InvalidType(kTypeBoolean, kTypeString)); + ExpectFailure(spec, "null", InvalidType(kTypeBoolean, kTypeNull)); } { @@ -214,13 +245,16 @@ ExpectSuccess(spec, "['foo']", "['foo']"); ExpectSuccess(spec, "['foo', 'bar']", "['foo','bar']"); ExpectSuccess(spec, "var x = new Array(); x[0] = 'foo'; x;", "['foo']"); - ExpectFailure(spec, "'foo'"); - ExpectFailure(spec, "[1, 2]"); - ExpectFailure(spec, "['foo', 1]"); + ExpectFailure(spec, "'foo'", InvalidType(kTypeList, kTypeString)); + ExpectFailure(spec, "[1, 2]", + IndexError(0u, InvalidType(kTypeString, kTypeInteger))); + ExpectFailure(spec, "['foo', 1]", + IndexError(1u, InvalidType(kTypeString, kTypeInteger))); ExpectFailure(spec, "var x = ['a', 'b', 'c'];" "x[4] = 'd';" // x[3] is undefined, violating the spec. - "x;"); + "x;", + IndexError(3u, InvalidType(kTypeString, kTypeUndefined))); ExpectThrow( spec, "var x = [];" @@ -246,27 +280,34 @@ ExpectSuccess(spec, "({prop1: 'foo'})", "{'prop1':'foo'}"); ExpectSuccess(spec, "({prop1: 'foo', prop2: null})", "{'prop1':'foo'}"); ExpectSuccess(spec, "x = {}; x.prop1 = 'foo'; x;", "{'prop1':'foo'}"); - ExpectFailure(spec, "({prop1: 'foo', prop2: 'bar'})"); - ExpectFailure(spec, "({prop2: 2})"); + ExpectFailure( + spec, "({prop1: 'foo', prop2: 'bar'})", + PropertyError("prop2", InvalidType(kTypeInteger, kTypeString))); + ExpectFailure(spec, "({prop2: 2})", MissingRequiredProperty("prop1")); // Unknown properties are not allowed. - ExpectFailure(spec, "({prop1: 'foo', prop2: 2, prop3: 'blah'})"); + ExpectFailure(spec, "({prop1: 'foo', prop2: 2, prop3: 'blah'})", + UnexpectedProperty("prop3")); // We only consider properties on the object itself, not its prototype // chain. ExpectFailure(spec, "function X() {}\n" "X.prototype = { prop1: 'foo' };\n" "var x = new X();\n" - "x;"); + "x;", + MissingRequiredProperty("prop1")); ExpectFailure(spec, "function X() {}\n" "X.prototype = { prop1: 'foo' };\n" "function Y() { this.__proto__ = X.prototype; }\n" "var z = new Y();\n" - "z;"); + "z;", + MissingRequiredProperty("prop1")); // Self-referential fun. Currently we don't have to worry about these much // because the spec won't match at some point (and V8ValueConverter has // cycle detection and will fail). - ExpectFailure(spec, "x = {}; x.prop1 = x; x;"); + ExpectFailure( + spec, "x = {}; x.prop1 = x; x;", + PropertyError("prop1", InvalidType(kTypeString, kTypeObject))); ExpectThrow( spec, "({ get prop1() { throw new Error('Badness'); }});", @@ -300,9 +341,12 @@ ExpectSuccessWithNoConversion(spec, "(function() {})"); ExpectSuccessWithNoConversion(spec, "(function(a, b) { a(); b(); })"); ExpectSuccessWithNoConversion(spec, "(function(a, b) { a(); b(); })"); - ExpectFailureWithNoConversion(spec, "({a: function() {}})"); - ExpectFailureWithNoConversion(spec, "([function() {}])"); - ExpectFailureWithNoConversion(spec, "1"); + ExpectFailureWithNoConversion(spec, "({a: function() {}})", + InvalidType(kTypeFunction, kTypeObject)); + ExpectFailureWithNoConversion(spec, "([function() {}])", + InvalidType(kTypeFunction, kTypeList)); + ExpectFailureWithNoConversion(spec, "1", + InvalidType(kTypeFunction, kTypeInteger)); } { @@ -334,7 +378,7 @@ "b;", *expected_value); } - ExpectFailure(spec, "1"); + ExpectFailure(spec, "1", InvalidType(kTypeBinary, kTypeInteger)); } { const char kAnySpec[] = "{ 'type': 'any' }"; @@ -358,12 +402,14 @@ // null, which is a potentially important distinction. However, this means // that in serialization of an object {a: 1, foo:undefined}, we lose the // 'foo' property. - ExpectFailure(spec, "undefined"); + ExpectFailure(spec, "undefined", UnserializableValue()); + ExpectSuccess(spec, "({prop1: 1, prop2: undefined})", "{'prop1':1}"); } } TEST_F(ArgumentSpecUnitTest, TypeRefsTest) { + using namespace api_errors; const char kObjectType[] = "{" " 'id': 'refObj'," @@ -379,6 +425,7 @@ base::MakeUnique<ArgumentSpec>(*ValueFromString(kObjectType))); AddTypeRef("refEnum", base::MakeUnique<ArgumentSpec>(*ValueFromString(kEnumType))); + std::set<std::string> valid_enums = {"alpha", "beta"}; { const char kObjectWithRefEnumSpec[] = @@ -393,8 +440,9 @@ ArgumentSpec spec(*ValueFromString(kObjectWithRefEnumSpec)); ExpectSuccess(spec, "({e: 'alpha', sub: 1})", "{'e':'alpha','sub':1}"); ExpectSuccess(spec, "({e: 'beta', sub: 1})", "{'e':'beta','sub':1}"); - ExpectFailure(spec, "({e: 'gamma', sub: 1})"); - ExpectFailure(spec, "({e: 'alpha'})"); + ExpectFailure(spec, "({e: 'gamma', sub: 1})", + PropertyError("e", InvalidEnumValue(valid_enums))); + ExpectFailure(spec, "({e: 'alpha'})", MissingRequiredProperty("sub")); } { @@ -410,7 +458,10 @@ ExpectSuccess(spec, "({o: {prop1: 'foo'}})", "{'o':{'prop1':'foo'}}"); ExpectSuccess(spec, "({o: {prop1: 'foo', prop2: 2}})", "{'o':{'prop1':'foo','prop2':2}}"); - ExpectFailure(spec, "({o: {prop1: 1}})"); + ExpectFailure( + spec, "({o: {prop1: 1}})", + PropertyError("o", PropertyError("prop1", InvalidType(kTypeString, + kTypeInteger)))); } { @@ -420,18 +471,20 @@ ExpectSuccess(spec, "['alpha']", "['alpha']"); ExpectSuccess(spec, "['alpha', 'alpha']", "['alpha','alpha']"); ExpectSuccess(spec, "['alpha', 'beta']", "['alpha','beta']"); - ExpectFailure(spec, "['alpha', 'beta', 'gamma']"); + ExpectFailure(spec, "['alpha', 'beta', 'gamma']", + IndexError(2u, InvalidEnumValue(valid_enums))); } } TEST_F(ArgumentSpecUnitTest, TypeChoicesTest) { + using namespace api_errors; { const char kSimpleChoices[] = "{'choices': [{'type': 'string'}, {'type': 'integer'}]}"; ArgumentSpec spec(*ValueFromString(kSimpleChoices)); ExpectSuccess(spec, "'alpha'", "'alpha'"); ExpectSuccess(spec, "42", "42"); - ExpectFailure(spec, "true"); + ExpectFailure(spec, "true", InvalidChoice()); } { @@ -446,13 +499,14 @@ ExpectSuccess(spec, "['alpha']", "['alpha']"); ExpectSuccess(spec, "['alpha', 'beta']", "['alpha','beta']"); ExpectSuccess(spec, "({prop1: 'alpha'})", "{'prop1':'alpha'}"); - ExpectFailure(spec, "({prop1: 1})"); - ExpectFailure(spec, "'alpha'"); - ExpectFailure(spec, "42"); + ExpectFailure(spec, "({prop1: 1})", InvalidChoice()); + ExpectFailure(spec, "'alpha'", InvalidChoice()); + ExpectFailure(spec, "42", InvalidChoice()); } } TEST_F(ArgumentSpecUnitTest, AdditionalPropertiesTest) { + using namespace api_errors; { const char kOnlyAnyAdditionalProperties[] = "{" @@ -533,8 +587,11 @@ "{'prop1':'alpha','prop2':42,'prop3':{'foo':'bar'}}"); // Additional properties are optional. ExpectSuccess(spec, "({prop1: 'foo'})", "{'prop1':'foo'}"); - ExpectFailure(spec, "({prop2: 42, prop3: {foo: 'bar'}})"); - ExpectFailure(spec, "({prop1: 42})"); + ExpectFailure(spec, "({prop2: 42, prop3: {foo: 'bar'}})", + MissingRequiredProperty("prop1")); + ExpectFailure( + spec, "({prop1: 42})", + PropertyError("prop1", InvalidType(kTypeString, kTypeInteger))); } { const char kTypedAdditionalProperties[] = @@ -545,11 +602,14 @@ ArgumentSpec spec(*ValueFromString(kTypedAdditionalProperties)); ExpectSuccess(spec, "({prop1: 'alpha', prop2: 'beta', prop3: 'gamma'})", "{'prop1':'alpha','prop2':'beta','prop3':'gamma'}"); - ExpectFailure(spec, "({prop1: 'alpha', prop2: 42})"); + ExpectFailure( + spec, "({prop1: 'alpha', prop2: 42})", + PropertyError("prop2", InvalidType(kTypeString, kTypeInteger))); } } TEST_F(ArgumentSpecUnitTest, InstanceOfTest) { + using namespace api_errors; { const char kInstanceOfRegExp[] = "{" @@ -572,10 +632,11 @@ " return new RegExp();\n" "})()", "{}"); - ExpectFailure(spec, "({})"); - ExpectFailure(spec, "('')"); - ExpectFailure(spec, "('.*')"); - ExpectFailure(spec, "({ __proto__: Date.prototype })"); + ExpectFailure(spec, "({})", NotAnInstance("RegExp")); + ExpectFailure(spec, "('')", InvalidType("RegExp", kTypeString)); + ExpectFailure(spec, "('.*')", InvalidType("RegExp", kTypeString)); + ExpectFailure(spec, "({ __proto__: Date.prototype })", + NotAnInstance("RegExp")); } { @@ -600,23 +661,25 @@ " return new otherClass();\n" "})()", "{}"); - ExpectFailure(spec, "({})"); + ExpectFailure(spec, "({})", NotAnInstance("customClass")); ExpectFailure(spec, "(function() {\n" " function otherClass() {}\n" " return new otherClass();\n" - "})()"); + "})()", + NotAnInstance("customClass")); } } TEST_F(ArgumentSpecUnitTest, MinAndMaxLengths) { + using namespace api_errors; { const char kMinLengthString[] = "{'type': 'string', 'minLength': 3}"; ArgumentSpec spec(*ValueFromString(kMinLengthString)); ExpectSuccess(spec, "'aaa'", "'aaa'"); ExpectSuccess(spec, "'aaaa'", "'aaaa'"); - ExpectFailure(spec, "'aa'"); - ExpectFailure(spec, "''"); + ExpectFailure(spec, "'aa'", TooFewStringChars(3, 2)); + ExpectFailure(spec, "''", TooFewStringChars(3, 0)); } { @@ -625,7 +688,7 @@ ExpectSuccess(spec, "'aaa'", "'aaa'"); ExpectSuccess(spec, "'aa'", "'aa'"); ExpectSuccess(spec, "''", "''"); - ExpectFailure(spec, "'aaaa'"); + ExpectFailure(spec, "'aaaa'", TooManyStringChars(3, 4)); } { @@ -634,8 +697,8 @@ ArgumentSpec spec(*ValueFromString(kMinLengthArray)); ExpectSuccess(spec, "[1, 2, 3]", "[1,2,3]"); ExpectSuccess(spec, "[1, 2, 3, 4]", "[1,2,3,4]"); - ExpectFailure(spec, "[1, 2]"); - ExpectFailure(spec, "[]"); + ExpectFailure(spec, "[1, 2]", TooFewArrayItems(3, 2)); + ExpectFailure(spec, "[]", TooFewArrayItems(3, 0)); } { @@ -645,7 +708,7 @@ ExpectSuccess(spec, "[1, 2, 3]", "[1,2,3]"); ExpectSuccess(spec, "[1, 2]", "[1,2]"); ExpectSuccess(spec, "[]", "[]"); - ExpectFailure(spec, "[1, 2, 3, 4]"); + ExpectFailure(spec, "[1, 2, 3, 4]", TooManyArrayItems(3, 4)); } }
diff --git a/headless/app/headless_shell.cc b/headless/app/headless_shell.cc index ff670db0..18d986e 100644 --- a/headless/app/headless_shell.cc +++ b/headless/app/headless_shell.cc
@@ -18,6 +18,7 @@ #include "base/memory/weak_ptr.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" +#include "content/public/common/content_switches.h" #include "headless/app/headless_shell.h" #include "headless/app/headless_shell_switches.h" #include "headless/public/headless_devtools_target.h"
diff --git a/ios/chrome/browser/notification_promo_unittest.cc b/ios/chrome/browser/notification_promo_unittest.cc index 3299c13..2b3718e 100644 --- a/ios/chrome/browser/notification_promo_unittest.cc +++ b/ios/chrome/browser/notification_promo_unittest.cc
@@ -297,14 +297,14 @@ bool closed = true; // Save data into old prefs structure. - base::DictionaryValue* ntp_promo = new base::DictionaryValue; + auto ntp_promo = base::MakeUnique<base::DictionaryValue>(); ntp_promo->SetInteger("id", promo.promo_id_); ntp_promo->SetDouble("first_view_time", first_view_time); ntp_promo->SetInteger("views", views); ntp_promo->SetBoolean("closed", true); base::ListValue* promo_list = new base::ListValue; - promo_list->Set(0, ntp_promo); + promo_list->Append(std::move(ntp_promo)); std::string promo_list_key = "mobile_ntp_whats_new_promo"; std::string promo_dict_key = "ios.ntppromo";
diff --git a/ipc/ipc_message_unittest.cc b/ipc/ipc_message_unittest.cc index 1bf52d8..67235e3 100644 --- a/ipc/ipc_message_unittest.cc +++ b/ipc/ipc_message_unittest.cc
@@ -66,9 +66,9 @@ TEST(IPCMessageTest, ListValue) { base::ListValue input; - input.Set(0, new base::Value(42.42)); - input.Set(1, new base::Value("forty")); - input.Set(2, base::MakeUnique<base::Value>()); + input.AppendDouble(42.42); + input.AppendString("forty"); + input.Append(base::MakeUnique<base::Value>()); IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::WriteParam(&msg, input); @@ -98,9 +98,9 @@ subdict->Set("bool", new base::Value(false)); std::unique_ptr<base::ListValue> sublist(new base::ListValue()); - sublist->Set(0, new base::Value(42.42)); - sublist->Set(1, new base::Value("forty")); - sublist->Set(2, new base::Value("two")); + sublist->AppendDouble(42.42); + sublist->AppendString("forty"); + sublist->AppendString("two"); subdict->Set("list", sublist.release()); input.Set("dict", subdict.release());
diff --git a/ipc/ipc_message_utils.cc b/ipc/ipc_message_utils.cc index 9a8630dc..80533181 100644 --- a/ipc/ipc_message_utils.cc +++ b/ipc/ipc_message_utils.cc
@@ -9,6 +9,7 @@ #include "base/files/file_path.h" #include "base/json/json_writer.h" +#include "base/memory/ptr_util.h" #include "base/strings/nullable_string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -71,7 +72,7 @@ bool ReadValue(const base::Pickle* m, base::PickleIterator* iter, - base::Value** value, + std::unique_ptr<base::Value>* value, int recursion); void GetValueSize(base::PickleSizer* sizer, @@ -218,11 +219,11 @@ for (int i = 0; i < size; ++i) { std::string key; - base::Value* subval; + std::unique_ptr<base::Value> subval; if (!ReadParam(m, iter, &key) || !ReadValue(m, iter, &subval, recursion + 1)) return false; - value->SetWithoutPathExpansion(key, subval); + value->SetWithoutPathExpansion(key, std::move(subval)); } return true; @@ -239,10 +240,10 @@ return false; for (int i = 0; i < size; ++i) { - base::Value* subval; + std::unique_ptr<base::Value> subval; if (!ReadValue(m, iter, &subval, recursion + 1)) return false; - value->Set(i, subval); + value->Set(i, std::move(subval)); } return true; @@ -250,7 +251,7 @@ bool ReadValue(const base::Pickle* m, base::PickleIterator* iter, - base::Value** value, + std::unique_ptr<base::Value>* value, int recursion) { if (recursion > kMaxRecursionDepth) { LOG(ERROR) << "Max recursion depth hit in ReadValue."; @@ -263,34 +264,34 @@ switch (static_cast<base::Value::Type>(type)) { case base::Value::Type::NONE: - *value = new base::Value(); + *value = base::MakeUnique<base::Value>(); break; case base::Value::Type::BOOLEAN: { bool val; if (!ReadParam(m, iter, &val)) return false; - *value = new base::Value(val); + *value = base::MakeUnique<base::Value>(val); break; } case base::Value::Type::INTEGER: { int val; if (!ReadParam(m, iter, &val)) return false; - *value = new base::Value(val); + *value = base::MakeUnique<base::Value>(val); break; } case base::Value::Type::DOUBLE: { double val; if (!ReadParam(m, iter, &val)) return false; - *value = new base::Value(val); + *value = base::MakeUnique<base::Value>(val); break; } case base::Value::Type::STRING: { std::string val; if (!ReadParam(m, iter, &val)) return false; - *value = new base::Value(val); + *value = base::MakeUnique<base::Value>(std::move(val)); break; } case base::Value::Type::BINARY: { @@ -298,23 +299,21 @@ int length; if (!iter->ReadData(&data, &length)) return false; - std::unique_ptr<base::Value> val = - base::Value::CreateWithCopiedBuffer(data, length); - *value = val.release(); + *value = base::Value::CreateWithCopiedBuffer(data, length); break; } case base::Value::Type::DICTIONARY: { - std::unique_ptr<base::DictionaryValue> val(new base::DictionaryValue()); - if (!ReadDictionaryValue(m, iter, val.get(), recursion)) + base::DictionaryValue val; + if (!ReadDictionaryValue(m, iter, &val, recursion)) return false; - *value = val.release(); + *value = base::MakeUnique<base::Value>(std::move(val)); break; } case base::Value::Type::LIST: { - std::unique_ptr<base::ListValue> val(new base::ListValue()); - if (!ReadListValue(m, iter, val.get(), recursion)) + base::ListValue val; + if (!ReadListValue(m, iter, &val, recursion)) return false; - *value = val.release(); + *value = base::MakeUnique<base::Value>(std::move(val)); break; } default:
diff --git a/media/formats/mp4/track_run_iterator.cc b/media/formats/mp4/track_run_iterator.cc index 25fc5ec..f109873 100644 --- a/media/formats/mp4/track_run_iterator.cc +++ b/media/formats/mp4/track_run_iterator.cc
@@ -169,11 +169,11 @@ // that marks non-key video frames as sync samples (http://crbug.com/507916 // and http://crbug.com/310712). Hence, for video we additionally check that // the sample does not depend on others (FFmpeg does too, see mov_read_trun). - // Sample dependency is not ignored for audio because encoded audio samples - // can depend on other samples and still be used for random access. Generally - // all audio samples are expected to be sync samples, but we prefer to check - // the flags to catch badly muxed audio (for now anyway ;P). History of - // attempts to get this right discussed in http://crrev.com/1319813002 + // Sample dependency is ignored for audio because encoded audio samples can + // depend on other samples and still be used for random access. Generally all + // audio samples are expected to be sync samples, but we prefer to check the + // flags to catch badly muxed audio (for now anyway ;P). History of attempts + // to get this right discussed in http://crrev.com/1319813002 bool sample_is_sync_sample = !(flags & kSampleIsNonSyncSample); bool sample_depends_on_others = sample_depends_on == kSampleDependsOnOthers; sample_info->is_keyframe = sample_is_sync_sample &&
diff --git a/net/log/net_log_event_type_list.h b/net/log/net_log_event_type_list.h index 9653c7a..043cf8e 100644 --- a/net/log/net_log_event_type_list.h +++ b/net/log/net_log_event_type_list.h
@@ -1687,9 +1687,6 @@ // } EVENT_TYPE(QUIC_STREAM_FACTORY_JOB_BOUND_TO_HTTP_STREAM_JOB) -// Measures the time taken to load server information. -EVENT_TYPE(QUIC_STREAM_FACTORY_JOB_LOAD_SERVER_INFO) - // Measures the time taken to establish a QUIC connection. // The event parameters are: // {
diff --git a/net/quic/chromium/quic_http_stream_test.cc b/net/quic/chromium/quic_http_stream_test.cc index 6b7e951..a35bbb9 100644 --- a/net/quic/chromium/quic_http_stream_test.cc +++ b/net/quic/chromium/quic_http_stream_test.cc
@@ -176,14 +176,6 @@ QuicHttpStream* stream) { return stream->stream_; } - - static bool WasHandshakeConfirmed(QuicHttpStream* stream) { - return stream->was_handshake_confirmed_; - } - - static void SetHandshakeConfirmed(QuicHttpStream* stream, bool confirmed) { - stream->was_handshake_confirmed_ = confirmed; - } }; class QuicHttpStreamTest : public ::testing::TestWithParam<QuicVersion> { @@ -330,7 +322,6 @@ session_->Initialize(); TestCompletionCallback callback; session_->CryptoConnect(callback.callback()); - EXPECT_TRUE(session_->IsCryptoHandshakeConfirmed()); stream_.reset(use_closing_stream_ ? new AutoClosingStream(session_->GetWeakPtr(), &http_server_properties_) @@ -1022,8 +1013,6 @@ EXPECT_THAT(stream_->ReadResponseHeaders(callback_.callback()), IsError(ERR_IO_PENDING)); - EXPECT_TRUE(QuicHttpStreamPeer::WasHandshakeConfirmed(stream_.get())); - QuicConnectionCloseFrame frame; frame.error_code = QUIC_PEER_GOING_AWAY; session_->connection()->OnConnectionCloseFrame(frame); @@ -1035,14 +1024,18 @@ } TEST_P(QuicHttpStreamTest, DoNotLogGranularQuicErrorIfHandshakeNotConfirmed) { + // By default the test setup defaults handshake to be confirmed. Manually set + // it to be not confirmed. + // Granular errors shouldn't be reported if handshake not confirmed. + crypto_client_stream_factory_.set_handshake_mode( + MockCryptoClientStream::ZERO_RTT); + SetRequest("GET", "/", DEFAULT_PRIORITY); size_t spdy_request_headers_frame_length; QuicStreamOffset header_stream_offset = 0; - AddWrite(ConstructInitialSettingsPacket(&header_stream_offset)); AddWrite(InnerConstructRequestHeadersPacket( - 2, kClientDataStreamId1, kIncludeVersion, kFin, DEFAULT_PRIORITY, + 1, kClientDataStreamId1, kIncludeVersion, kFin, DEFAULT_PRIORITY, &spdy_request_headers_frame_length, &header_stream_offset)); - AddWrite(ConstructAckAndRstStreamPacket(3)); use_closing_stream_ = true; Initialize(); @@ -1060,12 +1053,6 @@ EXPECT_THAT(stream_->ReadResponseHeaders(callback_.callback()), IsError(ERR_IO_PENDING)); - // The test setup defaults handshake to be confirmed. Manually set - // it to be not confirmed. - // Granular errors shouldn't be reported if handshake not confirmed. - QuicHttpStreamPeer::SetHandshakeConfirmed(stream_.get(), false); - - EXPECT_FALSE(QuicHttpStreamPeer::WasHandshakeConfirmed(stream_.get())); QuicConnectionCloseFrame frame; frame.error_code = QUIC_PEER_GOING_AWAY; session_->connection()->OnConnectionCloseFrame(frame);
diff --git a/net/quic/chromium/quic_stream_factory.cc b/net/quic/chromium/quic_stream_factory.cc index 30a09c3..61f79e0 100644 --- a/net/quic/chromium/quic_stream_factory.cc +++ b/net/quic/chromium/quic_stream_factory.cc
@@ -898,19 +898,13 @@ // Associate with active job to |server_id| if such exists. auto it = active_jobs_.find(server_id); if (it != active_jobs_.end()) { - const JobSet& job_set = it->second; - // TODO(zhongyi): figure out how to link the NetLogs if there are more than - // one job serving the same server id, i.e., auxiliary job is also - // created. - if (job_set.size() == 1) { - const NetLogWithSource& job_net_log = job_set.begin()->first->net_log(); - job_net_log.AddEvent( - NetLogEventType::QUIC_STREAM_FACTORY_JOB_BOUND_TO_HTTP_STREAM_JOB, - net_log.source().ToEventParametersCallback()); - net_log.AddEvent( - NetLogEventType::HTTP_STREAM_JOB_BOUND_TO_QUIC_STREAM_FACTORY_JOB, - job_net_log.source().ToEventParametersCallback()); - } + const NetLogWithSource& job_net_log = it->second->net_log(); + job_net_log.AddEvent( + NetLogEventType::QUIC_STREAM_FACTORY_JOB_BOUND_TO_HTTP_STREAM_JOB, + net_log.source().ToEventParametersCallback()); + net_log.AddEvent( + NetLogEventType::HTTP_STREAM_JOB_BOUND_TO_QUIC_STREAM_FACTORY_JOB, + job_net_log.source().ToEventParametersCallback()); job_requests_map_[server_id].insert(request); return ERR_IO_PENDING; } @@ -942,8 +936,7 @@ base::Unretained(this), job.get())); if (rv == ERR_IO_PENDING) { job_requests_map_[server_id].insert(request); - Job* job_ptr = job.get(); - active_jobs_[server_id][job_ptr] = std::move(job); + active_jobs_[server_id] = std::move(job); return rv; } if (rv == OK) { @@ -1007,16 +1000,6 @@ // Copy |server_id|, because |job| might be destroyed before this method // returns. const QuicServerId server_id(job->key().server_id()); - if (rv != OK) { - JobSet* jobs = &(active_jobs_[server_id]); - if (jobs->size() > 1) { - // If there is another pending job, then we can delete this job and let - // the other job handle the request. - job->Cancel(); - jobs->erase(job); - return; - } - } ServerIDRequestsMap::iterator requests_iter = job_requests_map_.find(server_id); @@ -1045,12 +1028,6 @@ request->OnRequestComplete(rv); } - for (auto& other_job : active_jobs_[server_id]) { - if (other_job.first != job) - other_job.first->Cancel(); - } - - active_jobs_[server_id].clear(); active_jobs_.erase(server_id); job_requests_map_.erase(requests_iter); }
diff --git a/net/quic/chromium/quic_stream_factory.h b/net/quic/chromium/quic_stream_factory.h index 916c2f97..9feedb3 100644 --- a/net/quic/chromium/quic_stream_factory.h +++ b/net/quic/chromium/quic_stream_factory.h
@@ -392,8 +392,7 @@ typedef std::set<QuicChromiumClientSession*> SessionSet; typedef std::map<IPEndPoint, SessionSet> IPAliasMap; typedef std::map<QuicChromiumClientSession*, IPEndPoint> SessionPeerIPMap; - typedef std::map<Job*, std::unique_ptr<Job>> JobSet; - typedef std::map<QuicServerId, JobSet> JobMap; + typedef std::map<QuicServerId, std::unique_ptr<Job>> JobMap; typedef std::set<QuicStreamRequest*> RequestSet; typedef std::map<QuicServerId, RequestSet> ServerIDRequestsMap; typedef std::map<QuicServerId, std::unique_ptr<CertVerifierJob>>
diff --git a/net/quic/chromium/quic_stream_factory_peer.cc b/net/quic/chromium/quic_stream_factory_peer.cc index f801fada..40fcd9b 100644 --- a/net/quic/chromium/quic_stream_factory_peer.cc +++ b/net/quic/chromium/quic_stream_factory_peer.cc
@@ -104,15 +104,6 @@ factory->yield_after_duration_ = yield_after_duration; } -size_t QuicStreamFactoryPeer::GetNumberOfActiveJobs( - QuicStreamFactory* factory, - const QuicServerId& server_id) { - auto it = factory->active_jobs_.find(server_id); - if (it == factory->active_jobs_.end()) - return 0; - return it->second.size(); -} - bool QuicStreamFactoryPeer::CryptoConfigCacheIsEmpty( QuicStreamFactory* factory, const QuicServerId& quic_server_id) {
diff --git a/remoting/host/mac/BUILD.gn b/remoting/host/mac/BUILD.gn index 73cf0e8..33362130 100644 --- a/remoting/host/mac/BUILD.gn +++ b/remoting/host/mac/BUILD.gn
@@ -14,6 +14,8 @@ "constants_mac.cc", "constants_mac.h", ] + + deps = [ "//remoting/host:remoting_version" ] } # remoting_me2me_host-InfoPlist.strings
diff --git a/sandbox/win/BUILD.gn b/sandbox/win/BUILD.gn index 1d51220c..8eea346 100644 --- a/sandbox/win/BUILD.gn +++ b/sandbox/win/BUILD.gn
@@ -314,6 +314,7 @@ "sandbox_poc/pocdll/handles.cc", "sandbox_poc/pocdll/invasive.cc", "sandbox_poc/pocdll/network.cc", + "sandbox_poc/pocdll/ntundoc.h", "sandbox_poc/pocdll/pocdll.cc", "sandbox_poc/pocdll/processes_and_threads.cc", "sandbox_poc/pocdll/registry.cc",
diff --git a/sandbox/win/sandbox_poc/pocdll/handles.cc b/sandbox/win/sandbox_poc/pocdll/handles.cc index 1c6116e..8a51cf8 100644 --- a/sandbox/win/sandbox_poc/pocdll/handles.cc +++ b/sandbox/win/sandbox_poc/pocdll/handles.cc
@@ -3,8 +3,8 @@ // found in the LICENSE file. #include "sandbox/win/sandbox_poc/pocdll/exports.h" +#include "sandbox/win/sandbox_poc/pocdll/ntundoc.h" #include "sandbox/win/sandbox_poc/pocdll/utils.h" -#include "sandbox/win/tools/finder/ntundoc.h" // This file contains the tests used to verify the security of handles in // the process
diff --git a/sandbox/win/tools/finder/ntundoc.h b/sandbox/win/sandbox_poc/pocdll/ntundoc.h similarity index 100% rename from sandbox/win/tools/finder/ntundoc.h rename to sandbox/win/sandbox_poc/pocdll/ntundoc.h
diff --git a/sandbox/win/tools/finder/finder.cc b/sandbox/win/tools/finder/finder.cc deleted file mode 100644 index 7753dd0..0000000 --- a/sandbox/win/tools/finder/finder.cc +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2006-2008 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 "sandbox/win/src/restricted_token.h" -#include "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/finder.h" - -Finder::Finder() { - file_output_ = NULL; - object_type_ = 0; - access_type_ = 0; - memset(filesystem_stats_, 0, sizeof(filesystem_stats_)); - memset(registry_stats_, 0, sizeof(registry_stats_)); - memset(kernel_object_stats_, 0, sizeof(kernel_object_stats_)); -} - -Finder::~Finder() { -} - -DWORD Finder::Init(sandbox::TokenLevel token_type, - DWORD object_type, - DWORD access_type, - FILE *file_output) { - DWORD err_code = ERROR_SUCCESS; - - err_code = InitNT(); - if (ERROR_SUCCESS != err_code) - return err_code; - - object_type_ = object_type; - access_type_ = access_type; - file_output_ = file_output; - - err_code = sandbox::CreateRestrictedToken(token_type, - sandbox::INTEGRITY_LEVEL_LAST, - sandbox::PRIMARY, &token_handle_); - return err_code; -} - -DWORD Finder::Scan() { - if (!token_handle_.IsValid()) { - return ERROR_NO_TOKEN; - } - - if (object_type_ & kScanRegistry) { - ParseRegistry(HKEY_LOCAL_MACHINE, L"HKLM\\"); - ParseRegistry(HKEY_USERS, L"HKU\\"); - ParseRegistry(HKEY_CURRENT_CONFIG, L"HKCC\\"); - } - - if (object_type_ & kScanFileSystem) { - ParseFileSystem(L"\\\\?\\C:"); - } - - if (object_type_ & kScanKernelObjects) { - ParseKernelObjects(L"\\"); - } - - return ERROR_SUCCESS; -}
diff --git a/sandbox/win/tools/finder/finder.h b/sandbox/win/tools/finder/finder.h deleted file mode 100644 index 503447d..0000000 --- a/sandbox/win/tools/finder/finder.h +++ /dev/null
@@ -1,144 +0,0 @@ -// Copyright (c) 2006-2008 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 SANDBOX_TOOLS_FINDER_FINDER_H_ -#define SANDBOX_TOOLS_FINDER_FINDER_H_ - -#include "base/win/scoped_handle.h" -#include "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/ntundoc.h" - -// Type of stats that we calculate during the Scan operation -enum Stats { - READ = 0, // Number of objects with read access - WRITE, // Number of objects with write access - ALL, // Number of objects with r/w access - PARSE, // Number of objects parsed - BROKEN, // Number of errors while parsing the objects - SIZE_STATS // size of the enum -}; - -const int kScanRegistry = 0x01; -const int kScanFileSystem = 0x02; -const int kScanKernelObjects = 0x04; - -const int kTestForRead = 0x01; -const int kTestForWrite = 0x02; -const int kTestForAll = 0x04; - -#define FS_ERR L"FILE-ERROR" -#define OBJ_ERR L"OBJ-ERROR" -#define REG_ERR L"REG_ERROR" -#define OBJ L"OBJ" -#define FS L"FILE" -#define REG L"REG" - -// The impersonater class will impersonate a token when the object is created -// and revert when the object is going out of scope. -class Impersonater { - public: - Impersonater(HANDLE token_handle) { - if (token_handle) - ::ImpersonateLoggedOnUser(token_handle); - }; - ~Impersonater() { - ::RevertToSelf(); - }; -}; - -// The finder class handles the search of objects (file system, registry, kernel -// objects) on the system that can be opened by a restricted token. It can -// support multiple levels of restriction for the restricted token and can check -// for read, write or r/w access. It outputs the results to a file or stdout. -class Finder { - public: - Finder(); - ~Finder(); - DWORD Init(sandbox::TokenLevel token_type, DWORD object_type, - DWORD access_type, FILE *file_output); - DWORD Scan(); - - private: - // Parses a file system path and perform an access check on all files and - // folder found. - // Returns ERROR_SUCCESS if the function succeeded, otherwise, it returns the - // win32 error code associated with the error. - DWORD ParseFileSystem(ATL::CString path); - - // Parses a registry hive referenced by "key" and performs an access check on - // all subkeys found. - // Returns ERROR_SUCCESS if the function succeeded, otherwise, it returns the - // win32 error code associated with the error. - DWORD ParseRegistry(HKEY key, ATL::CString print_name); - - // Parses the kernel namespace beginning at "path" and performs an access - // check on all objects found. However, only some object types are supported, - // all non supported objects are ignored. - // Returns ERROR_SUCCESS if the function succeeded, otherwise, it returns the - // win32 error code associated with the error. - DWORD ParseKernelObjects(ATL::CString path); - - // Checks if "path" can be accessed with the restricted token. - // Returns the access granted. - DWORD TestFileAccess(ATL::CString path); - - // Checks if the registry key with the path key\name can be accessed with the - // restricted token. - // print_name is only use for logging purpose. - // Returns the access granted. - DWORD TestRegAccess(HKEY key, ATL::CString name, ATL::CString print_name); - - // Checks if the kernel object "path" of type "type" can be accessed with - // the restricted token. - // Returns the access granted. - DWORD TestKernelObjectAccess(ATL::CString path, ATL::CString type); - - // Outputs information to the logfile - void Output(ATL::CString type, ATL::CString access, ATL::CString info) { - fprintf(file_output_, "\n%S;%S;%S", type.GetBuffer(), access.GetBuffer(), - info.GetBuffer()); - }; - - // Output information to the log file. - void Output(ATL::CString type, DWORD error, ATL::CString info) { - fprintf(file_output_, "\n%S;0x%X;%S", type.GetBuffer(), error, - info.GetBuffer()); - }; - - // Set func_to_call to the function pointer of the function used to handle - // requests for the kernel objects of type "type". If the type is not - // supported at the moment the function returns false and the func_to_call - // parameter is not modified. - bool GetFunctionForType(ATL::CString type, NTGENERICOPEN * func_to_call); - - // Initializes the NT function pointers to be able to use all the needed - // functions in NTDDL. - // Returns ERROR_SUCCESS if the function succeeded, otherwise, it returns the - // win32 error code associated with the error. - DWORD InitNT(); - - // Calls func_to_call with the parameters desired_access, object_attributes - // and handle. func_to_call is a pointer to a function to open a kernel - // object. - NTSTATUS NtGenericOpen(ACCESS_MASK desired_access, - OBJECT_ATTRIBUTES *object_attributes, - NTGENERICOPEN func_to_call, - HANDLE *handle); - - // Type of object to check for. - DWORD object_type_; - // Access to try. - DWORD access_type_; - // Output file for the results. - FILE * file_output_; - // Handle to the restricted token. - base::win::ScopedHandle token_handle_; - // Stats containing the number of operations performed on the different - // objects. - int filesystem_stats_[SIZE_STATS]; - int registry_stats_[SIZE_STATS]; - int kernel_object_stats_[SIZE_STATS]; -}; - -#endif // SANDBOX_TOOLS_FINDER_FINDER_H_
diff --git a/sandbox/win/tools/finder/finder.vcproj b/sandbox/win/tools/finder/finder.vcproj deleted file mode 100644 index 787c8477..0000000 --- a/sandbox/win/tools/finder/finder.vcproj +++ /dev/null
@@ -1,201 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="8.00" - Name="finder" - ProjectGUID="{ACDC2E06-0366-41A4-A646-C37E130A605D}" - RootNamespace="finder" - Keyword="Win32Proj" - > - <Platforms> - <Platform - Name="Win32" - /> - </Platforms> - <ToolFiles> - </ToolFiles> - <Configurations> - <Configuration - Name="Debug|Win32" - ConfigurationType="1" - InheritedPropertySheets="$(SolutionDir)..\build\debug.vsprops;$(SolutionDir)..\build\common.vsprops" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="2" - ForcedIncludeFiles="stdafx.h" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - <Configuration - Name="Release|Win32" - ConfigurationType="1" - InheritedPropertySheets="$(SolutionDir)..\build\release.vsprops;$(SolutionDir)..\build\common.vsprops" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="0" - ForcedIncludeFiles="stdafx.h" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <File - RelativePath=".\finder.cc" - > - </File> - <File - RelativePath=".\finder.h" - > - </File> - <File - RelativePath=".\finder_fs.cc" - > - </File> - <File - RelativePath=".\finder_kernel.cc" - > - </File> - <File - RelativePath=".\finder_registry.cc" - > - </File> - <File - RelativePath=".\main.cc" - > - </File> - <File - RelativePath=".\ntundoc.h" - > - </File> - <File - RelativePath=".\stdafx.cc" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="0" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\stdafx.h" - > - </File> - </Files> - <Globals> - </Globals> -</VisualStudioProject>
diff --git a/sandbox/win/tools/finder/finder_fs.cc b/sandbox/win/tools/finder/finder_fs.cc deleted file mode 100644 index ddcc4be..0000000 --- a/sandbox/win/tools/finder/finder_fs.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2006-2008 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 "sandbox/win/src/restricted_token.h" -#include "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/finder.h" - -DWORD Finder::ParseFileSystem(ATL::CString directory) { - WIN32_FIND_DATA find_data; - HANDLE find; - - //Search for items in the directory. - ATL::CString name_to_search = directory + L"\\*"; - find = ::FindFirstFile(name_to_search, &find_data); - if (INVALID_HANDLE_VALUE == find) { - DWORD error = ::GetLastError(); - Output(FS_ERR, error, directory); - filesystem_stats_[BROKEN]++; - return error; - } - - // parse all files or folders. - do { - if (_tcscmp(find_data.cFileName, L".") == 0 || - _tcscmp(find_data.cFileName, L"..") == 0) - continue; - - ATL::CString complete_name = directory + L"\\" + find_data.cFileName; - TestFileAccess(complete_name); - - // Call recursively the function if the path found is a directory. - if ((find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { - ParseFileSystem(complete_name); - } - } while (::FindNextFile(find, &find_data) != 0); - - DWORD err_code = ::GetLastError(); - ::FindClose(find); - - if (ERROR_NO_MORE_FILES != err_code) { - Output(FS_ERR, err_code, directory); - filesystem_stats_[BROKEN]++; - return err_code; - } - - return ERROR_SUCCESS; -} - -DWORD Finder::TestFileAccess(ATL::CString name) { - Impersonater impersonate(token_handle_); - - filesystem_stats_[PARSE]++; - - HANDLE file; - if (access_type_ & kTestForAll) { - file = ::CreateFile(name.GetBuffer(), - GENERIC_ALL, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (file != INVALID_HANDLE_VALUE) { - filesystem_stats_[ALL]++; - Output(FS, L"R/W", name.GetBuffer()); - ::CloseHandle(file); - return GENERIC_ALL; - } else if (::GetLastError() != ERROR_ACCESS_DENIED) { - Output(FS_ERR, GetLastError(), name); - filesystem_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForWrite) { - file = ::CreateFile(name.GetBuffer(), - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (file != INVALID_HANDLE_VALUE) { - filesystem_stats_[WRITE]++; - Output(FS, L"W", name); - ::CloseHandle(file); - return GENERIC_WRITE; - } else if (::GetLastError() != ERROR_ACCESS_DENIED) { - Output(FS_ERR, ::GetLastError(), name); - filesystem_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForRead) { - file = ::CreateFile(name.GetBuffer(), - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (file != INVALID_HANDLE_VALUE) { - filesystem_stats_[READ]++; - Output(FS, L"R", name); - ::CloseHandle(file); - return GENERIC_READ; - } else if (::GetLastError() != ERROR_ACCESS_DENIED) { - Output(FS_ERR, GetLastError(), name); - filesystem_stats_[BROKEN]++; - } - } - - return 0; -}
diff --git a/sandbox/win/tools/finder/finder_kernel.cc b/sandbox/win/tools/finder/finder_kernel.cc deleted file mode 100644 index 430a4c0..0000000 --- a/sandbox/win/tools/finder/finder_kernel.cc +++ /dev/null
@@ -1,248 +0,0 @@ -// Copyright (c) 2006-2008 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 "sandbox/win/src/restricted_token.h" -#include "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/finder.h" -#include "sandbox/win/tools/finder/ntundoc.h" - -#define BUFFER_SIZE 0x800 -#define CHECKPTR(x) if (!x) return ::GetLastError() - -// NT API -NTQUERYDIRECTORYOBJECT NtQueryDirectoryObject; -NTOPENDIRECTORYOBJECT NtOpenDirectoryObject; -NTOPENEVENT NtOpenEvent; -NTOPENJOBOBJECT NtOpenJobObject; -NTOPENKEYEDEVENT NtOpenKeyedEvent; -NTOPENMUTANT NtOpenMutant; -NTOPENSECTION NtOpenSection; -NTOPENSEMAPHORE NtOpenSemaphore; -NTOPENSYMBOLICLINKOBJECT NtOpenSymbolicLinkObject; -NTOPENTIMER NtOpenTimer; -NTOPENFILE NtOpenFile; -NTCLOSE NtClose; - -DWORD Finder::InitNT() { - HMODULE ntdll_handle = ::LoadLibrary(L"ntdll.dll"); - CHECKPTR(ntdll_handle); - - NtOpenSymbolicLinkObject = (NTOPENSYMBOLICLINKOBJECT) ::GetProcAddress( - ntdll_handle, "NtOpenSymbolicLinkObject"); - CHECKPTR(NtOpenSymbolicLinkObject); - - NtQueryDirectoryObject = (NTQUERYDIRECTORYOBJECT) ::GetProcAddress( - ntdll_handle, "NtQueryDirectoryObject"); - CHECKPTR(NtQueryDirectoryObject); - - NtOpenDirectoryObject = (NTOPENDIRECTORYOBJECT) ::GetProcAddress( - ntdll_handle, "NtOpenDirectoryObject"); - CHECKPTR(NtOpenDirectoryObject); - - NtOpenKeyedEvent = (NTOPENKEYEDEVENT) ::GetProcAddress( - ntdll_handle, "NtOpenKeyedEvent"); - CHECKPTR(NtOpenKeyedEvent); - - NtOpenJobObject = (NTOPENJOBOBJECT) ::GetProcAddress( - ntdll_handle, "NtOpenJobObject"); - CHECKPTR(NtOpenJobObject); - - NtOpenSemaphore = (NTOPENSEMAPHORE) ::GetProcAddress( - ntdll_handle, "NtOpenSemaphore"); - CHECKPTR(NtOpenSemaphore); - - NtOpenSection = (NTOPENSECTION) ::GetProcAddress( - ntdll_handle, "NtOpenSection"); - CHECKPTR(NtOpenSection); - - NtOpenMutant= (NTOPENMUTANT) ::GetProcAddress(ntdll_handle, "NtOpenMutant"); - CHECKPTR(NtOpenMutant); - - NtOpenEvent = (NTOPENEVENT) ::GetProcAddress(ntdll_handle, "NtOpenEvent"); - CHECKPTR(NtOpenEvent); - - NtOpenTimer = (NTOPENTIMER) ::GetProcAddress(ntdll_handle, "NtOpenTimer"); - CHECKPTR(NtOpenTimer); - - NtOpenFile = (NTOPENFILE) ::GetProcAddress(ntdll_handle, "NtOpenFile"); - CHECKPTR(NtOpenFile); - - NtClose = (NTCLOSE) ::GetProcAddress(ntdll_handle, "NtClose"); - CHECKPTR(NtClose); - - return ERROR_SUCCESS; -} - -DWORD Finder::ParseKernelObjects(ATL::CString path) { - UNICODE_STRING unicode_str; - unicode_str.Length = (USHORT)path.GetLength()*2; - unicode_str.MaximumLength = (USHORT)path.GetLength()*2+2; - unicode_str.Buffer = path.GetBuffer(); - - OBJECT_ATTRIBUTES path_attributes; - InitializeObjectAttributes(&path_attributes, - &unicode_str, - 0, // No Attributes - NULL, // No Root Directory - NULL); // No Security Descriptor - - - DWORD object_index = 0; - DWORD data_written = 0; - - // TODO(nsylvain): Do not use BUFFER_SIZE. Try to get the size - // dynamically. - OBJDIR_INFORMATION *object_directory_info = - (OBJDIR_INFORMATION*) ::HeapAlloc(GetProcessHeap(), - 0, - BUFFER_SIZE); - - HANDLE file_handle; - NTSTATUS status_code = NtOpenDirectoryObject(&file_handle, - DIRECTORY_QUERY, - &path_attributes); - if (status_code != 0) - return ERROR_UNIDENTIFIED_ERROR; - - status_code = NtQueryDirectoryObject(file_handle, - object_directory_info, - BUFFER_SIZE, - TRUE, // Get Next Index - TRUE, // Ignore Input Index - &object_index, - &data_written); - - if (status_code != 0) - return ERROR_UNIDENTIFIED_ERROR; - - while (NtQueryDirectoryObject(file_handle, object_directory_info, - BUFFER_SIZE, TRUE, FALSE, &object_index, - &data_written) == 0 ) { - ATL::CString cur_path(object_directory_info->ObjectName.Buffer, - object_directory_info->ObjectName.Length / sizeof(WCHAR)); - - ATL::CString cur_type(object_directory_info->ObjectTypeName.Buffer, - object_directory_info->ObjectTypeName.Length / sizeof(WCHAR)); - - ATL::CString new_path; - if (path == L"\\") { - new_path = path + cur_path; - } else { - new_path = path + L"\\" + cur_path; - } - - TestKernelObjectAccess(new_path, cur_type); - - // Call the function recursively for all subdirectories - if (cur_type == L"Directory") { - ParseKernelObjects(new_path); - } - } - - NtClose(file_handle); - return ERROR_SUCCESS; -} - -DWORD Finder::TestKernelObjectAccess(ATL::CString path, ATL::CString type) { - Impersonater impersonate(token_handle_); - - kernel_object_stats_[PARSE]++; - - NTGENERICOPEN func = NULL; - GetFunctionForType(type, &func); - - if (!func) { - kernel_object_stats_[BROKEN]++; - Output(OBJ_ERR, type + L" Unsupported", path); - return ERROR_UNSUPPORTED_TYPE; - } - - UNICODE_STRING unicode_str; - unicode_str.Length = (USHORT)path.GetLength()*2; - unicode_str.MaximumLength = (USHORT)path.GetLength()*2+2; - unicode_str.Buffer = path.GetBuffer(); - - OBJECT_ATTRIBUTES path_attributes; - InitializeObjectAttributes(&path_attributes, - &unicode_str, - 0, // No Attributes - NULL, // No Root Directory - NULL); // No Security Descriptor - - HANDLE handle; - NTSTATUS status_code = 0; - - if (access_type_ & kTestForAll) { - status_code = NtGenericOpen(GENERIC_ALL, &path_attributes, func, &handle); - if (STATUS_SUCCESS == status_code) { - kernel_object_stats_[ALL]++; - Output(OBJ, L"R/W", path); - NtClose(handle); - return GENERIC_ALL; - } else if (status_code != EXCEPTION_ACCESS_VIOLATION && - status_code != STATUS_ACCESS_DENIED) { - Output(OBJ_ERR, status_code, path); - kernel_object_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForWrite) { - status_code = NtGenericOpen(GENERIC_WRITE, &path_attributes, func, &handle); - if (STATUS_SUCCESS == status_code) { - kernel_object_stats_[WRITE]++; - Output(OBJ, L"W", path); - NtClose(handle); - return GENERIC_WRITE; - } else if (status_code != EXCEPTION_ACCESS_VIOLATION && - status_code != STATUS_ACCESS_DENIED) { - Output(OBJ_ERR, status_code, path); - kernel_object_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForRead) { - status_code = NtGenericOpen(GENERIC_READ, &path_attributes, func, &handle); - if (STATUS_SUCCESS == status_code) { - kernel_object_stats_[READ]++; - Output(OBJ, L"R", path); - NtClose(handle); - return GENERIC_READ; - } else if (status_code != EXCEPTION_ACCESS_VIOLATION && - status_code != STATUS_ACCESS_DENIED) { - Output(OBJ_ERR, status_code, path); - kernel_object_stats_[BROKEN]++; - } - } - - return 0; -} - -NTSTATUS Finder::NtGenericOpen(ACCESS_MASK desired_access, - OBJECT_ATTRIBUTES *object_attributes, - NTGENERICOPEN func_to_call, - HANDLE *handle) { - return func_to_call(handle, desired_access, object_attributes); -} - -bool Finder::GetFunctionForType(ATL::CString type, - NTGENERICOPEN * func_to_call) { - NTGENERICOPEN func = NULL; - - if (type == L"Event") func = NtOpenEvent; - else if (type == L"Job") func = NtOpenJobObject; - else if (type == L"KeyedEvent") func = NtOpenKeyedEvent; - else if (type == L"Mutant") func = NtOpenMutant; - else if (type == L"Section") func = NtOpenSection; - else if (type == L"Semaphore") func = NtOpenSemaphore; - else if (type == L"Timer") func = NtOpenTimer; - else if (type == L"SymbolicLink") func = NtOpenSymbolicLinkObject; - else if (type == L"Directory") func = NtOpenDirectoryObject; - - if (func) { - *func_to_call = func; - return true; - } - - return false; -}
diff --git a/sandbox/win/tools/finder/finder_registry.cc b/sandbox/win/tools/finder/finder_registry.cc deleted file mode 100644 index a84e413..0000000 --- a/sandbox/win/tools/finder/finder_registry.cc +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright (c) 2006-2008 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 "sandbox/win/src/restricted_token.h" -#include "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/finder.h" - -DWORD Finder::ParseRegistry(HKEY key, ATL::CString print_name) { - DWORD index = 0; - DWORD name_size = 2048; - wchar_t buffer[2048] = {0}; - // TODO(nsylvain): Don't hardcode 2048. Get the key len by calling the - // function. - LONG err_code = ::RegEnumKey(key, index, buffer, name_size); - while (ERROR_SUCCESS == err_code) { - ATL::CString name_complete = print_name + buffer + L"\\"; - TestRegAccess(key, buffer, name_complete); - - // Call the function recursively to parse all subkeys - HKEY key_to_parse; - err_code = ::RegOpenKeyEx(key, buffer, 0, KEY_ENUMERATE_SUB_KEYS, - &key_to_parse); - if (ERROR_SUCCESS == err_code) { - ParseRegistry(key_to_parse, name_complete); - ::RegCloseKey(key_to_parse); - } else { - registry_stats_[BROKEN]++; - Output(REG_ERR, err_code, name_complete); - } - - index++; - err_code = ::RegEnumKey(key, index, buffer, name_size); - } - - if (ERROR_NO_MORE_ITEMS != err_code) { - registry_stats_[BROKEN]++; - Output(REG_ERR, err_code, print_name); - } - - return ERROR_SUCCESS; -} - -DWORD Finder::TestRegAccess(HKEY key, ATL::CString name, - ATL::CString print_name) { - Impersonater impersonate(token_handle_); - - registry_stats_[PARSE]++; - - HKEY key_res; - LONG err_code = 0; - - if (access_type_ & kTestForAll) { - err_code = ::RegOpenKeyEx(key, name, 0, GENERIC_ALL, &key_res); - if (ERROR_SUCCESS == err_code) { - registry_stats_[ALL]++; - Output(REG, L"R/W", print_name); - ::RegCloseKey(key_res); - return GENERIC_ALL; - } else if (err_code != ERROR_ACCESS_DENIED) { - Output(REG_ERR, err_code, print_name); - registry_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForWrite) { - err_code = ::RegOpenKeyEx(key, name, 0, GENERIC_WRITE, &key_res); - if (ERROR_SUCCESS == err_code) { - registry_stats_[WRITE]++; - Output(REG, L"W", print_name); - ::RegCloseKey(key_res); - return GENERIC_WRITE; - } else if (err_code != ERROR_ACCESS_DENIED) { - Output(REG_ERR, err_code, print_name); - registry_stats_[BROKEN]++; - } - } - - if (access_type_ & kTestForRead) { - err_code = ::RegOpenKeyEx(key, name, 0, GENERIC_READ, &key_res); - if (ERROR_SUCCESS == err_code) { - registry_stats_[READ]++; - Output(REG, L"R", print_name); - ::RegCloseKey(key_res); - return GENERIC_READ; - } else if (err_code != ERROR_ACCESS_DENIED) { - Output(REG_ERR, err_code, print_name); - registry_stats_[BROKEN]++; - } - } - - return 0; -}
diff --git a/sandbox/win/tools/finder/main.cc b/sandbox/win/tools/finder/main.cc deleted file mode 100644 index 7cadbef8..0000000 --- a/sandbox/win/tools/finder/main.cc +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright (c) 2006-2008 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 "sandbox/win/src/restricted_token_utils.h" -#include "sandbox/win/tools/finder/finder.h" - -#define PARAM_IS(y) (argc > i) && (_wcsicmp(argv[i], y) == 0) - -void PrintUsage(wchar_t *application_name) { - wprintf(L"\n\nUsage: \n %ls --token type --object ob1 [ob2 ob3] " - L"--access ac1 [ac2 ac3] [--log filename]", application_name); - wprintf(L"\n\n Token Types : \n\tLOCKDOWN \n\tRESTRICTED " - L"\n\tLIMITED_USER \n\tINTERACTIVE_USER \n\tNON_ADMIN \n\tUNPROTECTED"); - wprintf(L"\n Object Types: \n\tREG \n\tFILE \n\tKERNEL"); - wprintf(L"\n Access Types: \n\tR \n\tW \n\tALL"); - wprintf(L"\n\nSample: \n %ls --token LOCKDOWN --object REG FILE KERNEL " - L"--access R W ALL", application_name); -} - -int wmain(int argc, wchar_t* argv[]) { - // Extract the filename from the path. - wchar_t *app_name = wcsrchr(argv[0], L'\\'); - if (!app_name) { - app_name = argv[0]; - } else { - app_name++; - } - - // parameters to read - ATL::CString log_file; - sandbox::TokenLevel token_type = sandbox::USER_LOCKDOWN; - DWORD object_type = 0; - DWORD access_type = 0; - - // no arguments - if (argc == 1) { - PrintUsage(app_name); - return -1; - } - - // parse command line. - for (int i = 1; i < argc; ++i) { - if (PARAM_IS(L"--token")) { - i++; - if (argc > i) { - if (PARAM_IS(L"LOCKDOWN")) { - token_type = sandbox::USER_LOCKDOWN; - } else if (PARAM_IS(L"RESTRICTED")) { - token_type = sandbox::USER_RESTRICTED; - } else if (PARAM_IS(L"LIMITED_USER")) { - token_type = sandbox::USER_LIMITED; - } else if (PARAM_IS(L"INTERACTIVE_USER")) { - token_type = sandbox::USER_INTERACTIVE; - } else if (PARAM_IS(L"NON_ADMIN")) { - token_type = sandbox::USER_NON_ADMIN; - } else if (PARAM_IS(L"USER_RESTRICTED_SAME_ACCESS")) { - token_type = sandbox::USER_RESTRICTED_SAME_ACCESS; - } else if (PARAM_IS(L"UNPROTECTED")) { - token_type = sandbox::USER_UNPROTECTED; - } else { - wprintf(L"\nAbord. Invalid token type \"%ls\"", argv[i]); - PrintUsage(app_name); - return -1; - } - } - } else if (PARAM_IS(L"--object")) { - bool is_object = true; - do { - i++; - if (PARAM_IS(L"REG")) { - object_type |= kScanRegistry; - } else if (PARAM_IS(L"FILE")) { - object_type |= kScanFileSystem; - } else if (PARAM_IS(L"KERNEL")) { - object_type |= kScanKernelObjects; - } else { - is_object = false; - } - } while(is_object); - i--; - } else if (PARAM_IS(L"--access")) { - bool is_access = true; - do { - i++; - if (PARAM_IS(L"R")) { - access_type |= kTestForRead; - } else if (PARAM_IS(L"W")) { - access_type |= kTestForWrite; - } else if (PARAM_IS(L"ALL")) { - access_type |= kTestForAll; - } else { - is_access = false; - } - } while(is_access); - i--; - } else if (PARAM_IS(L"--log")) { - i++; - if (argc > i) { - log_file = argv[i]; - } - else { - wprintf(L"\nAbord. No log file specified"); - PrintUsage(app_name); - return -1; - } - } else { - wprintf(L"\nAbord. Unrecognized parameter \"%ls\"", argv[i]); - PrintUsage(app_name); - return -1; - } - } - - // validate parameters - if (0 == access_type) { - wprintf(L"\nAbord, Access type not specified"); - PrintUsage(app_name); - return -1; - } - - if (0 == object_type) { - wprintf(L"\nAbord, Object type not specified"); - PrintUsage(app_name); - return -1; - } - - - // Open log file - FILE * file_output; - if (log_file.GetLength()) { - errno_t err = _wfopen_s(&file_output, log_file, L"w"); - if (err) { - wprintf(L"\nAbord, Cannot open file \"%ls\"", log_file.GetBuffer()); - return -1; - } - } else { - file_output = stdout; - } - - Finder finder_obj; - finder_obj.Init(token_type, object_type, access_type, file_output); - finder_obj.Scan(); - - fclose(file_output); - - return 0; -}
diff --git a/sandbox/win/tools/launcher/launcher.cc b/sandbox/win/tools/launcher/launcher.cc deleted file mode 100644 index a037702..0000000 --- a/sandbox/win/tools/launcher/launcher.cc +++ /dev/null
@@ -1,270 +0,0 @@ -// Copyright (c) 2006-2008 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 "base/win/scoped_handle.h" -#include "base/win/scoped_process_information.h" -#include "base/win/windows_version.h" -#include "sandbox/win/src/restricted_token_utils.h" - -// launcher.exe is an application used to launch another application with a -// restricted token. This is to be used for testing only. -// The parameters are the level of security of the primary token, the -// impersonation token and the job object along with the command line to -// execute. -// See the usage (launcher.exe without parameters) for the correct format. - -namespace { - -// Starts the process described by the input parameter command_line in a job -// with a restricted token. Also set the main thread of this newly created -// process to impersonate a user with more rights so it can initialize -// correctly. -// -// Parameters: primary_level is the security level of the primary token. -// impersonation_level is the security level of the impersonation token used -// to initialize the process. job_level is the security level of the job -// object used to encapsulate the process. -// -// The output parameter job_handle is the handle to the job object. Closing this -// handle will kill the process started. -// -// Note: The process started with this function has to call RevertToSelf() as -// soon as possible to stop using the impersonation token and start being -// secure. -// -// Note: The Unicode version of this function will fail if the command_line -// parameter is a const string. -DWORD StartRestrictedProcessInJob(wchar_t* command_line, - TokenLevel primary_level, - TokenLevel impersonation_level, - JobLevel job_level, - base::win::ScopedHandle* job_handle) { - Job job; - DWORD err_code = job.Init(job_level, NULL, 0, 0); - if (ERROR_SUCCESS != err_code) - return err_code; - - if (JOB_UNPROTECTED != job_level) { - // Share the Desktop handle to be able to use MessageBox() in the sandboxed - // application. - err_code = job.UserHandleGrantAccess(GetDesktopWindow()); - if (ERROR_SUCCESS != err_code) - return err_code; - } - - // Create the primary (restricted) token for the process - base::win::ScopedHandle primary_token; - err_code = sandbox::CreateRestrictedToken(primary_level, INTEGRITY_LEVEL_LAST, - PRIMARY, &primary_token); - if (ERROR_SUCCESS != err_code) - return err_code; - - - // Create the impersonation token (restricted) to be able to start the - // process. - base::win::ScopedHandle impersonation_token; - err_code = sandbox::CreateRestrictedToken(impersonation_level, - INTEGRITY_LEVEL_LAST, - IMPERSONATION, - &impersonation_token); - if (ERROR_SUCCESS != err_code) - return err_code; - - // Start the process - STARTUPINFO startup_info = {0}; - PROCESS_INFORMATION temp_process_info = {}; - DWORD flags = CREATE_SUSPENDED; - - if (base::win::GetVersion() < base::win::VERSION_WIN8) { - // Windows 8 implements nested jobs, but for older systems we need to - // break out of any job we're in to enforce our restrictions. - flags |= CREATE_BREAKAWAY_FROM_JOB; - } - - if (!::CreateProcessAsUser(primary_token.Get(), - NULL, // No application name. - command_line, - NULL, // No security attribute. - NULL, // No thread attribute. - FALSE, // Do not inherit handles. - flags, - NULL, // Use the environment of the caller. - NULL, // Use current directory of the caller. - &startup_info, - &temp_process_info)) { - return ::GetLastError(); - } - base::win::ScopedProcessInformation process_info(temp_process_info); - - // Change the token of the main thread of the new process for the - // impersonation token with more rights. - { - HANDLE temp_thread = process_info.thread_handle(); - if (!::SetThreadToken(&temp_thread, impersonation_token.Get())) { - auto last_error = ::GetLastError(); - ::TerminateProcess(process_info.process_handle(), - 0); // exit code - return last_error; - } - } - - err_code = job.AssignProcessToJob(process_info.process_handle()); - if (ERROR_SUCCESS != err_code) { - auto last_error = ::GetLastError(); - ::TerminateProcess(process_info.process_handle(), - 0); // exit code - return last_error; - } - - // Start the application - ::ResumeThread(process_info.thread_handle()); - - *job_handle = job.Take(); - - return ERROR_SUCCESS; -} - -} // namespace - -#define PARAM_IS(y) (argc > i) && (_wcsicmp(argv[i], y) == 0) - -void PrintUsage(const wchar_t *application_name) { - wprintf(L"\n\nUsage: \n %ls --main level --init level --job level cmd_line ", - application_name); - wprintf(L"\n\n Levels : \n\tLOCKDOWN \n\tRESTRICTED " - L"\n\tLIMITED_USER \n\tINTERACTIVE_USER \n\tNON_ADMIN \n\tUNPROTECTED"); - wprintf(L"\n\n main: Security level of the main token"); - wprintf(L"\n init: Security level of the impersonation token"); - wprintf(L"\n job: Security level of the job object"); -} - -bool GetTokenLevelFromString(const wchar_t *param, - sandbox::TokenLevel* level) { - if (_wcsicmp(param, L"LOCKDOWN") == 0) { - *level = sandbox::USER_LOCKDOWN; - } else if (_wcsicmp(param, L"RESTRICTED") == 0) { - *level = sandbox::USER_RESTRICTED; - } else if (_wcsicmp(param, L"LIMITED_USER") == 0) { - *level = sandbox::USER_LIMITED; - } else if (_wcsicmp(param, L"INTERACTIVE_USER") == 0) { - *level = sandbox::USER_INTERACTIVE; - } else if (_wcsicmp(param, L"NON_ADMIN") == 0) { - *level = sandbox::USER_NON_ADMIN; - } else if (_wcsicmp(param, L"USER_RESTRICTED_SAME_ACCESS") == 0) { - *level = sandbox::USER_RESTRICTED_SAME_ACCESS; - } else if (_wcsicmp(param, L"UNPROTECTED") == 0) { - *level = sandbox::USER_UNPROTECTED; - } else { - return false; - } - - return true; -} - -bool GetJobLevelFromString(const wchar_t *param, sandbox::JobLevel* level) { - if (_wcsicmp(param, L"LOCKDOWN") == 0) { - *level = sandbox::JOB_LOCKDOWN; - } else if (_wcsicmp(param, L"RESTRICTED") == 0) { - *level = sandbox::JOB_RESTRICTED; - } else if (_wcsicmp(param, L"LIMITED_USER") == 0) { - *level = sandbox::JOB_LIMITED_USER; - } else if (_wcsicmp(param, L"INTERACTIVE_USER") == 0) { - *level = sandbox::JOB_INTERACTIVE; - } else if (_wcsicmp(param, L"NON_ADMIN") == 0) { - wprintf(L"\nNON_ADMIN is not a supported job type"); - return false; - } else if (_wcsicmp(param, L"UNPROTECTED") == 0) { - *level = sandbox::JOB_UNPROTECTED; - } else { - return false; - } - - return true; -} - -int wmain(int argc, wchar_t *argv[]) { - // Extract the filename from the path. - wchar_t *app_name = wcsrchr(argv[0], L'\\'); - if (!app_name) { - app_name = argv[0]; - } else { - app_name++; - } - - // no argument - if (argc == 1) { - PrintUsage(app_name); - return -1; - } - - sandbox::TokenLevel primary_level = sandbox::USER_LOCKDOWN; - sandbox::TokenLevel impersonation_level = - sandbox::USER_RESTRICTED_SAME_ACCESS; - sandbox::JobLevel job_level = sandbox::JOB_LOCKDOWN; - ATL::CString command_line; - - // parse command line. - for (int i = 1; i < argc; ++i) { - if (PARAM_IS(L"--main")) { - i++; - if (argc > i) { - if (!GetTokenLevelFromString(argv[i], &primary_level)) { - wprintf(L"\nAbord, Unrecognized main token level \"%ls\"", argv[i]); - PrintUsage(app_name); - return -1; - } - } - } else if (PARAM_IS(L"--init")) { - i++; - if (argc > i) { - if (!GetTokenLevelFromString(argv[i], &impersonation_level)) { - wprintf(L"\nAbord, Unrecognized init token level \"%ls\"", argv[i]); - PrintUsage(app_name); - return -1; - } - } - } else if (PARAM_IS(L"--job")) { - i++; - if (argc > i) { - if (!GetJobLevelFromString(argv[i], &job_level)) { - wprintf(L"\nAbord, Unrecognized job security level \"%ls\"", argv[i]); - PrintUsage(app_name); - return -1; - } - } - } else { - if (command_line.GetLength()) { - command_line += L' '; - } - command_line += argv[i]; - } - } - - if (!command_line.GetLength()) { - wprintf(L"\nAbord, No command line specified"); - PrintUsage(app_name); - return -1; - } - - wprintf(L"\nLaunching command line: \"%ls\"\n", command_line.GetBuffer()); - - base::win::ScopedHandle job_handle; - DWORD err_code = StartRestrictedProcessInJob( - command_line.GetBuffer(), - primary_level, - impersonation_level, - job_level, - &job_handle); - if (ERROR_SUCCESS != err_code) { - wprintf(L"\nAbord, Error %d while launching command line.", err_code); - return -1; - } - - wprintf(L"\nPress any key to continue."); - while(!_kbhit()) { - Sleep(100); - } - - return 0; -}
diff --git a/sandbox/win/tools/launcher/launcher.vcproj b/sandbox/win/tools/launcher/launcher.vcproj deleted file mode 100644 index 71ed011..0000000 --- a/sandbox/win/tools/launcher/launcher.vcproj +++ /dev/null
@@ -1,177 +0,0 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="8.00" - Name="launcher" - ProjectGUID="{386FA217-FBC2-4461-882D-CDAD221ED800}" - RootNamespace="launcher" - Keyword="Win32Proj" - > - <Platforms> - <Platform - Name="Win32" - /> - </Platforms> - <ToolFiles> - </ToolFiles> - <Configurations> - <Configuration - Name="Debug|Win32" - ConfigurationType="1" - InheritedPropertySheets="$(SolutionDir)..\build\debug.vsprops;$(SolutionDir)..\build\common.vsprops" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="2" - ForcedIncludeFiles="stdafx.h" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - <Configuration - Name="Release|Win32" - ConfigurationType="1" - InheritedPropertySheets="$(SolutionDir)..\build\release.vsprops;$(SolutionDir)..\build\common.vsprops" - > - <Tool - Name="VCPreBuildEventTool" - /> - <Tool - Name="VCCustomBuildTool" - /> - <Tool - Name="VCXMLDataGeneratorTool" - /> - <Tool - Name="VCWebServiceProxyGeneratorTool" - /> - <Tool - Name="VCMIDLTool" - /> - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="0" - ForcedIncludeFiles="stdafx.h" - /> - <Tool - Name="VCManagedResourceCompilerTool" - /> - <Tool - Name="VCResourceCompilerTool" - /> - <Tool - Name="VCPreLinkEventTool" - /> - <Tool - Name="VCLinkerTool" - /> - <Tool - Name="VCALinkTool" - /> - <Tool - Name="VCManifestTool" - /> - <Tool - Name="VCXDCMakeTool" - /> - <Tool - Name="VCBscMakeTool" - /> - <Tool - Name="VCFxCopTool" - /> - <Tool - Name="VCAppVerifierTool" - /> - <Tool - Name="VCWebDeploymentTool" - /> - <Tool - Name="VCPostBuildEventTool" - /> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <File - RelativePath=".\launcher.cc" - > - </File> - <File - RelativePath=".\stdafx.cc" - > - <FileConfiguration - Name="Debug|Win32" - > - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="1" - /> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32" - > - <Tool - Name="VCCLCompilerTool" - UsePrecompiledHeader="0" - /> - </FileConfiguration> - </File> - <File - RelativePath=".\stdafx.h" - > - </File> - </Files> - <Globals> - </Globals> -</VisualStudioProject>
diff --git a/testing/buildbot/chromium.perf.fyi.json b/testing/buildbot/chromium.perf.fyi.json index 035452d..85eee416 100644 --- a/testing/buildbot/chromium.perf.fyi.json +++ b/testing/buildbot/chromium.perf.fyi.json
@@ -831,65 +831,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=android-chromium" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "android_devices": "1", - "id": "build248-m4--device3", - "os": "Android", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "android_devices": "1", - "id": "build248-m4--device3", - "os": "Android", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -12271,65 +12212,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:22b1", - "id": "build141-b1", - "os": "Windows-10-10586", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:22b1", - "id": "build141-b1", - "os": "Windows-10-10586", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -23791,65 +23673,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:9874", - "id": "build205-b4", - "os": "Windows-10-10586", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:9874", - "id": "build205-b4", - "os": "Windows-10-10586", - "pool": "Chrome-perf-fyi" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results",
diff --git a/testing/buildbot/chromium.perf.json b/testing/buildbot/chromium.perf.json index c108514..f0c648ae 100644 --- a/testing/buildbot/chromium.perf.json +++ b/testing/buildbot/chromium.perf.json
@@ -898,65 +898,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0534", - "id": "build150-m1", - "os": "Ubuntu-14.04", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0534", - "id": "build150-m1", - "os": "Ubuntu-14.04", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -12378,65 +12319,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0166", - "id": "build104-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0166", - "id": "build104-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -23818,65 +23700,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0a2e", - "id": "build160-m1", - "os": "Mac-10.12", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0a2e", - "id": "build160-m1", - "os": "Mac-10.12", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -35238,65 +35061,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:1626", - "id": "build125-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:1626", - "id": "build125-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -46658,65 +46422,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0a26", - "id": "build26-b1", - "os": "Mac-10.12", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0a26", - "id": "build26-b1", - "os": "Mac-10.12", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -58078,65 +57783,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6821", - "id": "build130-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6821", - "id": "build130-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -69498,65 +69144,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0d26", - "id": "build6-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:0d26", - "id": "build6-b1", - "os": "Mac-10.11", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -80918,65 +80505,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:1616", - "id": "build119-b1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:1616", - "id": "build119-b1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -92338,65 +91866,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0534", - "id": "build134-m1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0534", - "id": "build134-m1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -103798,65 +103267,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6613", - "id": "build103-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "1002:6613", - "id": "build103-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -115298,65 +114708,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:041a", - "id": "build166-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:041a", - "id": "build166-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -126778,65 +126129,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:104a", - "id": "build94-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "10de:104a", - "id": "build94-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -138258,65 +137550,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build187-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build187-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -149738,65 +148971,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build140-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build140-m1", - "os": "Windows-2008ServerR2-SP1", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -161198,65 +160372,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build145-m1", - "os": "Windows-2012ServerR2-SP0", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "102b:0532", - "id": "build145-m1", - "os": "Windows-2012ServerR2-SP0", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results", @@ -172678,65 +171793,6 @@ }, { "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=release_x64" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:161e", - "id": "build32-b1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": false, - "io_timeout": 3600 - } - }, - { - "args": [ - "blink_perf.xml_http_request", - "-v", - "--upload-results", - "--output-format=chartjson", - "--browser=reference", - "--output-trace-tag=_ref" - ], - "isolate_name": "telemetry_perf_tests", - "name": "blink_perf.xml_http_request.reference", - "override_compile_targets": [ - "telemetry_perf_tests" - ], - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "gpu": "8086:161e", - "id": "build32-b1", - "os": "Windows-10-10240", - "pool": "Chrome-perf" - } - ], - "expiration": 36000, - "hard_timeout": 7200, - "ignore_task_failure": true, - "io_timeout": 3600 - } - }, - { - "args": [ "blink_style.key_mobile_sites", "-v", "--upload-results",
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 86b8571..2b1b4374 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1971,7 +1971,6 @@ crbug.com/662010 [ Win7 ] csspaint/invalidation-background-image.html [ Skip ] crbug.com/693568 virtual/gpu/fast/canvas/canvas-imageSmoothingQuality.html [ Failure ] -crbug.com/712629 [ Linux ] virtual/gpu/fast/canvas/canvas-imageSmoothingQuality-pixel.html [ Pass Crash ] # This is temporary until we revert the speculative change crbug.com/704935 fast/events/pointerevents/pointer-event-consumed-touchstart-in-slop-region.html [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/webaudio/constructor/oscillator.html b/third_party/WebKit/LayoutTests/webaudio/constructor/oscillator.html index 7d91505..f204254 100644 --- a/third_party/WebKit/LayoutTests/webaudio/constructor/oscillator.html +++ b/third_party/WebKit/LayoutTests/webaudio/constructor/oscillator.html
@@ -5,8 +5,8 @@ <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script src="../resources/audit-util.js"></script> - <script src="../resources/audio-testing.js"></script> - <script src="audionodeoptions.js"></script> + <script src="../resources/audit.js"></script> + <script src="new-audionodeoptions.js"></script> </head> <body> @@ -15,145 +15,94 @@ var audit = Audit.createTaskRunner(); - audit.defineTask("initialize", function (taskDone) { - Should("context = new OfflineAudioContext(...)", function () { - context = new OfflineAudioContext(1, 1, 48000); - }).notThrow(); - - taskDone(); + audit.define('initialize', (task, should) => { + context = initializeContext(should); + task.done(); }); - audit.defineTask("invalid constructor", function (taskDone) { + audit.define('invalid constructor', (task, should) => { + testInvalidConstructor(should, 'OscillatorNode', context); + task.done(); + }); + + audit.define('default constructor', (task, should) => { + let prefix = 'node0'; + let node = testDefaultConstructor(should, 'OscillatorNode', context, { + prefix: prefix, + numberOfInputs: 0, + numberOfOutputs: 1, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers' + }); + + testDefaultAttributes( + should, node, prefix, + [{name: 'type', value: 'sine'}, {name: 'frequency', value: 440}]); + + task.done(); + }); + + audit.define('test AudioNodeOptions', (task, should) => { + testAudioNodeOptions(should, context, 'OscillatorNode'); + task.done(); + }); + + audit.define('constructor options', (task, should) => { var node; - var success = true; + var options = {type: 'sawtooth', detune: 7, frequency: 918}; - success = Should("new OscillatorNode()", function () { - node = new OscillatorNode(); - }).throw("TypeError"); - success = Should("new OscillatorNode(1)", function () { - node = new OscillatorNode(1) && success; - }).throw("TypeError"); - success = Should("new OscillatorNode(context, 42)", function () { - node = new OscillatorNode(context, 42) && success; - }).throw("TypeError"); + should( + () => { + node = new OscillatorNode(context, options); + }, + 'node1 = new OscillatorNode(c, ' + JSON.stringify(options) + ')') + .notThrow(); - Should("Invalid constructors", success) - .summarize( - "correctly threw errors", - "did not throw errors in all cases"); + should(node.type, 'node1.type').beEqualTo(options.type); + should(node.detune.value, 'node1.detune.value') + .beEqualTo(options.detune); + should(node.frequency.value, 'node1.frequency.value') + .beEqualTo(options.frequency); - taskDone(); - }); - - audit.defineTask("default constructor", function (taskDone) { - var node; - var success = true; - - success = Should("node0 = new OscillatorNode(context)", function () { - node = new OscillatorNode(context); - }).notThrow(); - success = Should("node0 instanceof OscillatorNode", node instanceof OscillatorNode) - .beEqualTo(true) && success; - - success = Should("node0.type", node.type) - .beEqualTo("sine") && success; - success = Should("node0.detune.value", node.detune.value) - .beEqualTo(0) && success; - success = Should("node0.frequency.value", node.frequency.value) - .beEqualTo(440) && success; - - success = Should("node0.channelCount", node.channelCount) - .beEqualTo(2) && success; - success = Should("node0.channelCountMode", node.channelCountMode) - .beEqualTo("max") && success; - success = Should("node0.channelInterpretation", node.channelInterpretation) - .beEqualTo("speakers") && success; - - Should("new OscillatorNode(context)", success) - .summarize( - "constructed node with correct attributes", - "did not construct correct node correctly") - - taskDone(); - }); - - audit.defineTask("test AudioNodeOptions", function (taskDone) { - testAudioNodeOptions(context, "OscillatorNode"); - taskDone(); - }); - - audit.defineTask("constructor options", function (taskDone) { - var node; - var success = true; - var options = { - type: "sawtooth", - detune: 7, - frequency: 918 - }; - - success = Should("node1 = new OscillatorNode(c, " + JSON.stringify(options) + ")", - function () { - node = new OscillatorNode(context, options); - }).notThrow(); - - success = Should("node1.type", node.type) - .beEqualTo(options.type) && success; - success = Should("node1.detune.value", node.detune.value) - .beEqualTo(options.detune) && success; - success = Should("node1.frequency.value", node.frequency.value) - .beEqualTo(options.frequency) && success; - - success = Should("node1.channelCount", node.channelCount) - .beEqualTo(2) && success; - success = Should("node1.channelCountMode", node.channelCountMode) - .beEqualTo("max") && success; - success = Should("node1.channelInterpretation", node.channelInterpretation) - .beEqualTo("speakers") && success; + should(node.channelCount, 'node1.channelCount').beEqualTo(2); + should(node.channelCountMode, 'node1.channelCountMode') + .beEqualTo('max'); + should(node.channelInterpretation, 'node1.channelInterpretation') + .beEqualTo('speakers'); // Test that type and periodicWave options work as described. options = { - type: "sine", - periodicWave: new PeriodicWave(context, { - real: [1, 1] - }) + type: 'sine', + periodicWave: new PeriodicWave(context, {real: [1, 1]}) }; - success = Should("node2 = new OscillatorNode(c, " + JSON.stringify(options) + ")", - function () { + should( + () => { node = new OscillatorNode(context, options); - }) - .notThrow() && success; - Should("node2.type", node.type).beEqualTo("custom"); + }, + 'new OscillatorNode(c, ' + JSON.stringify(options) + ')') + .notThrow(); + + options = {type: 'custom'}; + should( + () => { + node = new OscillatorNode(context, options); + }, + 'new OscillatorNode(c, ' + JSON.stringify(options) + ')') + .throw('InvalidStateError'); options = { - type: "custom" + type: 'custom', + periodicWave: new PeriodicWave(context, {real: [1, 1]}) }; - success = Should("new OscillatorNode(c, " + JSON.stringify(options) + ")", - function () { - node = new OscillatorNode(context, options); - }) - .throw("InvalidStateError") && success; + should(() => { + node = new OscillatorNode(context, options); + }, 'new OscillatorNode(, ' + JSON.stringify(options) + ')').notThrow(); - options = { - type: "custom", - periodicWave: new PeriodicWave(context, { - real: [1, 1] - }) - }; - success = Should("new OscillatorNode(, " + JSON.stringify(options) + ")", - function () { - node = new OscillatorNode(context, options); - }) - .notThrow() && success; - - Should("new OscillatorNode() with options", success) - .summarize( - "constructed with correct attributes", - "was not constructed correctly"); - - taskDone(); + task.done(); }); - audit.runTasks(); + audit.run(); </script> </body> </html>
diff --git a/third_party/WebKit/Source/core/frame/DOMTimerTest.cpp b/third_party/WebKit/Source/core/frame/DOMTimerTest.cpp index f9802469..39e316d2 100644 --- a/third_party/WebKit/Source/core/frame/DOMTimerTest.cpp +++ b/third_party/WebKit/Source/core/frame/DOMTimerTest.cpp
@@ -25,7 +25,9 @@ namespace { -const double kThreshold = 0.000001; +// The resolution of performance.now is 5us, so the threshold for time +// comparison is 6us to account for rounding errors. +const double kThreshold = 0.006; class DOMTimerTest : public RenderingTest { public: @@ -33,7 +35,7 @@ platform_; // Expected time between each iterator for setInterval(..., 1) or nested - // setTimeout(..., 1) are 1, 1, 1, 1, 4, 4, ... as a minumum clamp of 4m + // setTimeout(..., 1) are 1, 1, 1, 1, 4, 4, ... as a minimum clamp of 4ms // is applied from the 5th iteration onwards. const std::vector<Matcher<double>> kExpectedTimings = { DoubleNear(1., kThreshold), DoubleNear(1., kThreshold), @@ -46,9 +48,6 @@ // Advance timer manually as RenderingTest expects the time to be non-zero. platform_->AdvanceClockSeconds(1.); RenderingTest::SetUp(); - // Advance timer again as otherwise the time between the first call to - // setInterval and it running will be off by 5us. - platform_->AdvanceClockSeconds(1); GetDocument().GetSettings()->SetScriptEnabled(true); } @@ -85,7 +84,6 @@ "function setTimeoutCallback() {" " var current = performance.now();" " elapsed = current - last;" - " times.push(elapsed);" "}" "setTimeout(setTimeoutCallback, 0);";
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index bde3d1a..8a6cdc1 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -260,7 +260,6 @@ visitor->Trace(progress_tracker_); visitor->Trace(document_loader_); visitor->Trace(provisional_document_loader_); - visitor->Trace(deferred_history_load_); } void FrameLoader::Init() { @@ -305,13 +304,6 @@ } if (!defers) { - if (deferred_history_load_) { - Load(FrameLoadRequest(nullptr, deferred_history_load_->request_), - deferred_history_load_->load_type_, - deferred_history_load_->item_.Get(), - deferred_history_load_->history_load_type_); - deferred_history_load_.Clear(); - } frame_->GetNavigationScheduler().StartTimer(); ScheduleCheckCompleted(); } @@ -941,14 +933,6 @@ if (in_stop_all_loaders_) return; - if (frame_->GetPage()->Suspended() && - IsBackForwardLoadType(frame_load_type)) { - deferred_history_load_ = DeferredHistoryLoad::Create( - passed_request.GetResourceRequest(), history_item, frame_load_type, - history_load_type); - return; - } - FrameLoadRequest request(passed_request); request.GetResourceRequest().SetHasUserGesture( UserGestureIndicator::ProcessingUserGesture());
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.h b/third_party/WebKit/Source/core/loader/FrameLoader.h index 7ea22eb..010f24d 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.h +++ b/third_party/WebKit/Source/core/loader/FrameLoader.h
@@ -289,38 +289,6 @@ Member<DocumentLoader> document_loader_; Member<DocumentLoader> provisional_document_loader_; - class DeferredHistoryLoad - : public GarbageCollectedFinalized<DeferredHistoryLoad> { - WTF_MAKE_NONCOPYABLE(DeferredHistoryLoad); - - public: - static DeferredHistoryLoad* Create(ResourceRequest request, - HistoryItem* item, - FrameLoadType load_type, - HistoryLoadType history_load_type) { - return new DeferredHistoryLoad(request, item, load_type, - history_load_type); - } - - DeferredHistoryLoad(ResourceRequest request, - HistoryItem* item, - FrameLoadType load_type, - HistoryLoadType history_load_type) - : request_(request), - item_(item), - load_type_(load_type), - history_load_type_(history_load_type) {} - - DEFINE_INLINE_TRACE() { visitor->Trace(item_); } - - ResourceRequest request_; - Member<HistoryItem> item_; - FrameLoadType load_type_; - HistoryLoadType history_load_type_; - }; - - Member<DeferredHistoryLoad> deferred_history_load_; - bool in_stop_all_loaders_; TaskRunnerTimer<FrameLoader> check_timer_;
diff --git a/third_party/WebKit/Source/devtools/front_end/source_frame/UISourceCodeFrame.js b/third_party/WebKit/Source/devtools/front_end/source_frame/UISourceCodeFrame.js index 6e013ce..750c37b 100644 --- a/third_party/WebKit/Source/devtools/front_end/source_frame/UISourceCodeFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/source_frame/UISourceCodeFrame.js
@@ -568,7 +568,8 @@ this._decoration._messageBucket = this; this._wave = this._decoration.createChild('div', 'text-editor-line-decoration-wave'); this._icon = this._wave.createChild('label', 'text-editor-line-decoration-icon', 'dt-icon-label'); - this._hasDecoration = false; + /** @type {?number} */ + this._decorationStartColumn = null; this._messagesDescriptionElement = createElementWithClass('div', 'text-editor-messages-description-container'); /** @type {!Array.<!SourceFrame.UISourceCodeFrame.RowMessage>} */ @@ -586,10 +587,13 @@ var lineText = this.textEditor.line(lineNumber); columnNumber = Math.min(columnNumber, lineText.length); var lineIndent = TextUtils.TextUtils.lineIndent(lineText).length; - if (this._hasDecoration) + var startColumn = Math.max(columnNumber - 1, lineIndent); + if (this._decorationStartColumn === startColumn) + return; + if (this._decorationStartColumn !== null) this.textEditor.removeDecoration(this._decoration, lineNumber); - this._hasDecoration = true; - this.textEditor.addDecoration(this._decoration, lineNumber, Math.max(columnNumber - 1, lineIndent)); + this.textEditor.addDecoration(this._decoration, lineNumber, startColumn); + this._decorationStartColumn = startColumn; } /** @@ -611,9 +615,10 @@ var lineNumber = position.lineNumber; if (this._level) this.textEditor.toggleLineClass(lineNumber, SourceFrame.UISourceCodeFrame._lineClassPerLevel[this._level], false); - if (this._hasDecoration) + if (this._decorationStartColumn !== null) { this.textEditor.removeDecoration(this._decoration, lineNumber); - this._hasDecoration = false; + this._decorationStartColumn = null; + } } /** @@ -676,6 +681,8 @@ } this._updateWavePosition(lineNumber, columnNumber); + if (this._level === maxMessage.level()) + return; if (this._level) { this.textEditor.toggleLineClass(lineNumber, SourceFrame.UISourceCodeFrame._lineClassPerLevel[this._level], false); this._icon.type = '';
diff --git a/third_party/WebKit/Source/modules/imagecapture/ImageCapture.cpp b/third_party/WebKit/Source/modules/imagecapture/ImageCapture.cpp index 58a274f5..083e595 100644 --- a/third_party/WebKit/Source/modules/imagecapture/ImageCapture.cpp +++ b/third_party/WebKit/Source/modules/imagecapture/ImageCapture.cpp
@@ -496,10 +496,14 @@ // TODO(mcasas): Remove the explicit MediaSettingsRange::create() when // mojo::StructTraits supports garbage-collected mappings, // https://crbug.com/700180. - caps->SetImageHeight( - MediaSettingsRange::Create(std::move(capabilities->height))); - caps->SetImageWidth( - MediaSettingsRange::Create(std::move(capabilities->width))); + if (capabilities->height->min != 0 || capabilities->height->max != 0) { + caps->SetImageHeight( + MediaSettingsRange::Create(std::move(capabilities->height))); + } + if (capabilities->width->min != 0 || capabilities->width->max != 0) { + caps->SetImageWidth( + MediaSettingsRange::Create(std::move(capabilities->width))); + } caps->SetFillLightMode(capabilities->fill_light_mode); resolver->Resolve(caps);
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBIndex.idl b/third_party/WebKit/Source/modules/indexeddb/IDBIndex.idl index 5e1bace3..b7b57e3ac 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBIndex.idl +++ b/third_party/WebKit/Source/modules/indexeddb/IDBIndex.idl
@@ -36,12 +36,10 @@ [NewObject, CallWith=ScriptState, RaisesException] IDBRequest get(any key); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getKey(any key); - // TODO(cmumford): 0xFFFFFFFF is not necessary. Remove once crbug.com/335871 is fixed. - [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAll([Default=Undefined] optional any range, - [EnforceRange] optional unsigned long maxCount = 0xFFFFFFFF); - // TODO(cmumford): 0xFFFFFFFF is not necessary. Remove once crbug.com/335871 is fixed. - [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAllKeys([Default=Undefined] optional any range, - [EnforceRange] optional unsigned long maxCount = 0xFFFFFFFF); + [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAll([Default=Undefined] optional any query, + [EnforceRange] optional unsigned long count); + [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAllKeys([Default=Undefined] optional any query, + [EnforceRange] optional unsigned long count); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest count([Default=Undefined] optional any key); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest openCursor([Default=Undefined] optional any range,
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBObjectStore.idl b/third_party/WebKit/Source/modules/indexeddb/IDBObjectStore.idl index 2c4a8cd..e3f144f 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBObjectStore.idl +++ b/third_party/WebKit/Source/modules/indexeddb/IDBObjectStore.idl
@@ -40,12 +40,10 @@ [NewObject, CallWith=ScriptState, RaisesException] IDBRequest clear(); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest get(any key); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getKey(any key); - // TODO(cmumford): 0xFFFFFFFF is not necessary. Remove once crbug.com/335871 is fixed. - [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAll([Default=Undefined] optional any range, - [EnforceRange] optional unsigned long maxCount = 0xFFFFFFFF); - // TODO(cmumford): 0xFFFFFFFF is not necessary. Remove once crbug.com/335871 is fixed. - [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAllKeys([Default=Undefined] optional any range, - [EnforceRange] optional unsigned long maxCount = 0xFFFFFFFF); + [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAll([Default=Undefined] optional any query, + [EnforceRange] optional unsigned long count); + [NewObject, CallWith=ScriptState, RaisesException] IDBRequest getAllKeys([Default=Undefined] optional any query, + [EnforceRange] optional unsigned long count); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest count([Default=Undefined] optional any key); [NewObject, CallWith=ScriptState, RaisesException] IDBRequest openCursor([Default=Undefined] optional any range,
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp b/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp index fa84d72..d546197 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp +++ b/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp
@@ -53,9 +53,12 @@ } mojom::blink::PermissionStatus permission_status; - const bool result = notification_service_->GetPermissionStatus( - execution_context->GetSecurityOrigin()->ToString(), &permission_status); - DCHECK(result); + if (!notification_service_->GetPermissionStatus( + execution_context->GetSecurityOrigin()->ToString(), + &permission_status)) { + NOTREACHED(); + return mojom::blink::PermissionStatus::DENIED; + } return permission_status; }
diff --git a/third_party/WebKit/Source/platform/Timer.cpp b/third_party/WebKit/Source/platform/Timer.cpp index 0d5cd7f..30b6b04 100644 --- a/third_party/WebKit/Source/platform/Timer.cpp +++ b/third_party/WebKit/Source/platform/Timer.cpp
@@ -137,7 +137,7 @@ // Cancel any previously posted task. weak_ptr_factory_.RevokeAll(); - double delay_ms = 1000.0 * (new_time - now); + double delay_ms = 1000.0 * delay; TimerTaskRunner()->PostDelayedTask( location_, base::Bind(&TimerBase::RunInternal, weak_ptr_factory_.CreateWeakPtr()),
diff --git a/third_party/WebKit/Source/platform/audio/resources/Composite.wav b/third_party/WebKit/Source/platform/audio/resources/Composite.wav deleted file mode 100644 index fab198d..0000000 --- a/third_party/WebKit/Source/platform/audio/resources/Composite.wav +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp index 99379a0..0f6039a9 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp
@@ -490,8 +490,7 @@ surface_->color_params().GetSkColorSpaceForSkSurfaces()); } else { info = SkImageInfo::Make(source_rect.Width(), source_rect.Height(), - kRGBA_8888_SkColorType, alpha_type, - SkColorSpace::MakeSRGB()); + kRGBA_8888_SkColorType, alpha_type); } surface_->WritePixels(info, src_addr, src_bytes_per_row, dest_x, dest_y); }
diff --git a/third_party/WebKit/Source/platform/scheduler/base/lazy_now.h b/third_party/WebKit/Source/platform/scheduler/base/lazy_now.h index 1b63f0f..2cb6d0b 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/lazy_now.h +++ b/third_party/WebKit/Source/platform/scheduler/base/lazy_now.h
@@ -6,7 +6,7 @@ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_BASE_LAZY_NOW_H_ #include "base/time/time.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace base { class TickClock; @@ -17,7 +17,7 @@ // Now() is somewhat expensive so it makes sense not to call Now() unless we // really need to. -class BLINK_PLATFORM_EXPORT LazyNow { +class PLATFORM_EXPORT LazyNow { public: explicit LazyNow(base::TimeTicks now) : tick_clock_(nullptr), now_(now) { DCHECK(!now.is_null());
diff --git a/third_party/WebKit/Source/platform/scheduler/base/queueing_time_estimator.h b/third_party/WebKit/Source/platform/scheduler/base/queueing_time_estimator.h index 131735a..4bdd475 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/queueing_time_estimator.h +++ b/third_party/WebKit/Source/platform/scheduler/base/queueing_time_estimator.h
@@ -7,16 +7,16 @@ #include "base/macros.h" #include "base/time/time.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace blink { namespace scheduler { // Records the expected queueing time for a high priority task occurring // randomly during each interval of length |window_duration|. -class BLINK_PLATFORM_EXPORT QueueingTimeEstimator { +class PLATFORM_EXPORT QueueingTimeEstimator { public: - class BLINK_PLATFORM_EXPORT Client { + class PLATFORM_EXPORT Client { public: virtual void OnQueueingTimeForWindowEstimated( base::TimeDelta queueing_time) = 0;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc index 802e56f6..18d9d25 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc
@@ -12,8 +12,7 @@ namespace blink { namespace scheduler { -RealTimeDomain::RealTimeDomain(const char* tracing_category) - : tracing_category_(tracing_category), task_queue_manager_(nullptr) {} +RealTimeDomain::RealTimeDomain() : task_queue_manager_(nullptr) {} RealTimeDomain::~RealTimeDomain() {} @@ -54,7 +53,7 @@ return base::TimeDelta(); // Makes DoWork post an immediate continuation. base::TimeDelta delay = next_run_time - now; - TRACE_EVENT1(tracing_category_, "RealTimeDomain::DelayTillNextTask", + TRACE_EVENT1("renderer.scheduler", "RealTimeDomain::DelayTillNextTask", "delay_ms", delay.InMillisecondsF()); // The next task is sometime in the future. DoWork will make sure it gets
diff --git a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h index 872cde9..0825b18 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h
@@ -8,15 +8,15 @@ #include <set> #include "base/macros.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/time_domain.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT RealTimeDomain : public TimeDomain { +class PLATFORM_EXPORT RealTimeDomain : public TimeDomain { public: - explicit RealTimeDomain(const char* tracing_category); + RealTimeDomain(); ~RealTimeDomain() override; // TimeDomain implementation: @@ -34,7 +34,6 @@ base::trace_event::TracedValue* state) const override; private: - const char* tracing_category_; // NOT OWNED TaskQueueManager* task_queue_manager_; // NOT OWNED DISALLOW_COPY_AND_ASSIGN(RealTimeDomain);
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue.h index 43a8bc5..dd9ba26 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue.h
@@ -10,7 +10,7 @@ #include "base/optional.h" #include "base/single_thread_task_runner.h" #include "base/time/time.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace base { namespace trace_event { @@ -23,11 +23,11 @@ class TimeDomain; -class BLINK_PLATFORM_EXPORT TaskQueue : public base::SingleThreadTaskRunner { +class PLATFORM_EXPORT TaskQueue : public base::SingleThreadTaskRunner { public: TaskQueue() {} - class BLINK_PLATFORM_EXPORT Observer { + class PLATFORM_EXPORT Observer { public: virtual ~Observer() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc index e010806..5d147972 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc
@@ -71,20 +71,13 @@ namespace internal { -TaskQueueImpl::TaskQueueImpl( - TaskQueueManager* task_queue_manager, - TimeDomain* time_domain, - const Spec& spec, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category) +TaskQueueImpl::TaskQueueImpl(TaskQueueManager* task_queue_manager, + TimeDomain* time_domain, + const Spec& spec) : thread_id_(base::PlatformThread::CurrentId()), any_thread_(task_queue_manager, time_domain), type_(spec.type), name_(NameForQueueType(spec.type)), - disabled_by_default_tracing_category_( - disabled_by_default_tracing_category), - disabled_by_default_verbose_tracing_category_( - disabled_by_default_verbose_tracing_category), main_thread_only_(task_queue_manager, this, time_domain), should_monitor_quiescence_(spec.should_monitor_quiescence), should_notify_observers_(spec.should_notify_observers), @@ -466,8 +459,8 @@ void TaskQueueImpl::TraceQueueSize() const { bool is_tracing; - TRACE_EVENT_CATEGORY_GROUP_ENABLED(disabled_by_default_tracing_category_, - &is_tracing); + TRACE_EVENT_CATEGORY_GROUP_ENABLED( + TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), &is_tracing); if (!is_tracing) return; @@ -477,7 +470,7 @@ return; base::AutoLock lock(immediate_incoming_queue_lock_); - TRACE_COUNTER1(disabled_by_default_tracing_category_, GetName(), + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), GetName(), immediate_incoming_queue().size() + main_thread_only().immediate_work_queue->Size() + main_thread_only().delayed_work_queue->Size() + @@ -519,7 +512,8 @@ main_thread_only().time_domain->GetName()); bool verbose_tracing_enabled = false; TRACE_EVENT_CATEGORY_GROUP_ENABLED( - disabled_by_default_verbose_tracing_category_, &verbose_tracing_enabled); + TRACE_DISABLED_BY_DEFAULT("renderer.scheduler.debug"), + &verbose_tracing_enabled); state->SetInteger("immediate_incoming_queue_size", immediate_incoming_queue().size()); state->SetInteger("delayed_incoming_queue_size",
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h index 9281500..2f8ad95e 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h
@@ -57,13 +57,11 @@ // queue is selected, it round-robins between the immediate_work_queue and // delayed_work_queue. The reason for this is we want to make sure delayed // tasks (normally the most common type) don't starve out immediate work. -class BLINK_PLATFORM_EXPORT TaskQueueImpl final : public TaskQueue { +class PLATFORM_EXPORT TaskQueueImpl final : public TaskQueue { public: TaskQueueImpl(TaskQueueManager* task_queue_manager, TimeDomain* time_domain, - const Spec& spec, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category); + const Spec& spec); // Represents a time at which a task wants to run. Tasks scheduled for the // same point in time will be ordered by their sequence numbers. @@ -80,7 +78,7 @@ } }; - class BLINK_PLATFORM_EXPORT Task : public base::PendingTask { + class PLATFORM_EXPORT Task : public base::PendingTask { public: Task(); Task(const tracked_objects::Location& posted_from, @@ -357,8 +355,6 @@ const QueueType type_; const char* const name_; - const char* const disabled_by_default_tracing_category_; - const char* const disabled_by_default_verbose_tracing_category_; base::ThreadChecker main_thread_checker_; MainThreadOnly main_thread_only_;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.cc index 629495d..cdea7a84 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.cc
@@ -51,28 +51,21 @@ } TaskQueueManager::TaskQueueManager( - scoped_refptr<TaskQueueManagerDelegate> delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category) - : real_time_domain_(new RealTimeDomain(tracing_category)), + scoped_refptr<TaskQueueManagerDelegate> delegate) + : real_time_domain_(new RealTimeDomain()), delegate_(delegate), task_was_run_on_quiescence_monitored_queue_(false), record_task_delay_histograms_(true), work_batch_size_(1), task_count_(0), - tracing_category_(tracing_category), - disabled_by_default_tracing_category_( - disabled_by_default_tracing_category), - disabled_by_default_verbose_tracing_category_( - disabled_by_default_verbose_tracing_category), currently_executing_task_queue_(nullptr), observer_(nullptr), deletion_sentinel_(new DeletionSentinel()), weak_factory_(this) { DCHECK(delegate->RunsTasksOnCurrentThread()); - TRACE_EVENT_OBJECT_CREATED_WITH_ID(disabled_by_default_tracing_category, - "TaskQueueManager", this); + TRACE_EVENT_OBJECT_CREATED_WITH_ID( + TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager", + this); selector_.SetTaskQueueSelectorObserver(this); delayed_do_work_closure_ = @@ -87,8 +80,9 @@ } TaskQueueManager::~TaskQueueManager() { - TRACE_EVENT_OBJECT_DELETED_WITH_ID(disabled_by_default_tracing_category_, - "TaskQueueManager", this); + TRACE_EVENT_OBJECT_DELETED_WITH_ID( + TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager", + this); while (!queues_.empty()) (*queues_.begin())->UnregisterTaskQueue(); @@ -114,16 +108,14 @@ scoped_refptr<internal::TaskQueueImpl> TaskQueueManager::NewTaskQueue( const TaskQueue::Spec& spec) { - TRACE_EVENT1(tracing_category_, "TaskQueueManager::NewTaskQueue", + TRACE_EVENT1("renderer.scheduler", "TaskQueueManager::NewTaskQueue", "queue_name", TaskQueue::NameForQueueType(spec.type)); DCHECK(main_thread_checker_.CalledOnValidThread()); TimeDomain* time_domain = spec.time_domain ? spec.time_domain : real_time_domain_.get(); DCHECK(time_domains_.find(time_domain) != time_domains_.end()); scoped_refptr<internal::TaskQueueImpl> queue( - make_scoped_refptr(new internal::TaskQueueImpl( - this, time_domain, spec, disabled_by_default_tracing_category_, - disabled_by_default_verbose_tracing_category_))); + make_scoped_refptr(new internal::TaskQueueImpl(this, time_domain, spec))); queues_.insert(queue); selector_.AddQueue(queue.get()); return queue; @@ -136,7 +128,7 @@ void TaskQueueManager::UnregisterTaskQueue( scoped_refptr<internal::TaskQueueImpl> task_queue) { - TRACE_EVENT1(tracing_category_, "TaskQueueManager::UnregisterTaskQueue", + TRACE_EVENT1("renderer.scheduler", "TaskQueueManager::UnregisterTaskQueue", "queue_name", task_queue->GetName()); DCHECK(main_thread_checker_.CalledOnValidThread()); if (observer_) @@ -167,7 +159,7 @@ } void TaskQueueManager::WakeUpReadyDelayedQueues(LazyNow* lazy_now) { - TRACE_EVENT0(disabled_by_default_tracing_category_, + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager::WakeUpReadyDelayedQueues"); for (TimeDomain* time_domain : time_domains_) { @@ -229,7 +221,7 @@ any_thread().immediate_do_work_posted_count++; } - TRACE_EVENT0(disabled_by_default_tracing_category_, + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager::MaybeScheduleImmediateWorkLocked::PostTask"); delegate_->PostTask(from_here, immediate_do_work_closure_); } @@ -264,7 +256,7 @@ cancelable_delayed_do_work_closure_.Reset(delayed_do_work_closure_); base::TimeDelta delay = std::max(base::TimeDelta(), run_time - now); - TRACE_EVENT1(disabled_by_default_tracing_category_, + TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager::MaybeScheduleDelayedWork::PostDelayedTask", "delay_ms", delay.InMillisecondsF()); @@ -287,7 +279,7 @@ void TaskQueueManager::DoWork(bool delayed) { DCHECK(main_thread_checker_.CalledOnValidThread()); - TRACE_EVENT1(tracing_category_, "TaskQueueManager::DoWork", "delayed", + TRACE_EVENT1("renderer.scheduler", "TaskQueueManager::DoWork", "delayed", delayed); LazyNow lazy_now(real_time_domain()->CreateLazyNow()); @@ -467,7 +459,7 @@ internal::WorkQueue** out_work_queue) { bool should_run = selector_.SelectWorkQueueToService(out_work_queue); TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID( - disabled_by_default_tracing_category_, "TaskQueueManager", this, + TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "TaskQueueManager", this, AsValueWithSelectorResult(should_run, *out_work_queue)); return should_run; } @@ -528,7 +520,7 @@ } } - TRACE_EVENT1(tracing_category_, "TaskQueueManager::RunTask", "queue", + TRACE_EVENT1("renderer.scheduler", "TaskQueueManager::RunTask", "queue", queue->GetName()); // NOTE when TaskQueues get unregistered a reference ends up getting retained // by |queues_to_delete_| which is cleared at the top of |DoWork|. This means
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.h index 6215f40..9ff0333 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager.h
@@ -51,17 +51,14 @@ // the incoming task queue (if any) are moved here. The work queues are // registered with the selector as input to the scheduling decision. // -class BLINK_PLATFORM_EXPORT TaskQueueManager +class PLATFORM_EXPORT TaskQueueManager : public internal::TaskQueueSelector::Observer, public base::MessageLoop::NestingObserver { public: // Create a task queue manager where |delegate| identifies the thread // on which where the tasks are eventually run. Category strings must have // application lifetime (statics or literals). They may not include " chars. - TaskQueueManager(scoped_refptr<TaskQueueManagerDelegate> delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category); + explicit TaskQueueManager(scoped_refptr<TaskQueueManagerDelegate> delegate); ~TaskQueueManager() override; // Requests that a task to process work is posted on the main task runner. @@ -105,7 +102,7 @@ scoped_refptr<internal::TaskQueueImpl> NewTaskQueue( const TaskQueue::Spec& spec); - class BLINK_PLATFORM_EXPORT Observer { + class PLATFORM_EXPORT Observer { public: virtual ~Observer() {} @@ -372,10 +369,6 @@ base::ObserverList<TaskTimeObserver> task_time_observers_; - const char* tracing_category_; - const char* disabled_by_default_tracing_category_; - const char* disabled_by_default_verbose_tracing_category_; - internal::TaskQueueImpl* currently_executing_task_queue_; // NOT OWNED Observer* observer_; // NOT OWNED
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_delegate.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_delegate.h index dcd13fe..988a24e 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_delegate.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_delegate.h
@@ -9,12 +9,12 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/time/tick_clock.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT TaskQueueManagerDelegate +class PLATFORM_EXPORT TaskQueueManagerDelegate : public base::SingleThreadTaskRunner, public base::TickClock { public:
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc index 8a9138e..60a2266 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc
@@ -84,8 +84,7 @@ manager_ = base::MakeUnique<TaskQueueManager>( TaskQueueManagerDelegateForTest::Create( message_loop_->task_runner(), - base::WrapUnique(new base::DefaultTickClock())), - "fake.category", "fake.category", "fake.category.debug"); + base::WrapUnique(new base::DefaultTickClock()))); manager_->AddTaskTimeObserver(&test_task_time_observer_); virtual_time_domain_.reset(new PerfTestTimeDomain());
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc index 8befec1..a282c4e2 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc
@@ -46,15 +46,9 @@ class TaskQueueManagerForTest : public TaskQueueManager { public: - TaskQueueManagerForTest( - scoped_refptr<TaskQueueManagerDelegate> delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category) - : TaskQueueManager(delegate, - tracing_category, - disabled_by_default_tracing_category, - disabled_by_default_verbose_tracing_category) {} + explicit TaskQueueManagerForTest( + scoped_refptr<TaskQueueManagerDelegate> delegate) + : TaskQueueManager(delegate) {} using TaskQueueManager::NextTaskDelay; }; @@ -102,9 +96,7 @@ test_task_runner_.get(), base::MakeUnique<TestTimeSource>(now_src_.get())); - manager_ = base::MakeUnique<TaskQueueManagerForTest>( - main_task_runner_, "test.scheduler", "test.scheduler", - "test.scheduler.debug"); + manager_ = base::MakeUnique<TaskQueueManagerForTest>(main_task_runner_); for (size_t i = 0; i < num_queues; i++) runners_.push_back( @@ -123,10 +115,9 @@ message_loop_.reset(new base::MessageLoop()); // A null clock triggers some assertions. now_src_->Advance(base::TimeDelta::FromMicroseconds(1000)); - manager_ = base::MakeUnique<TaskQueueManagerForTest>( - MessageLoopTaskRunner::Create( - base::WrapUnique(new TestTimeSource(now_src_.get()))), - "test.scheduler", "test.scheduler", "test.scheduler.debug"); + manager_ = + base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( + base::WrapUnique(new TestTimeSource(now_src_.get())))); for (size_t i = 0; i < num_queues; i++) runners_.push_back( @@ -223,10 +214,9 @@ TestCountUsesTimeSource* test_count_uses_time_source = new TestCountUsesTimeSource(); - manager_ = base::MakeUnique<TaskQueueManagerForTest>( - MessageLoopTaskRunner::Create( - base::WrapUnique(test_count_uses_time_source)), - "test.scheduler", "test.scheduler", "test.scheduler.debug"); + manager_ = + base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( + base::WrapUnique(test_count_uses_time_source))); manager_->SetWorkBatchSize(6); manager_->AddTaskTimeObserver(&test_task_time_observer_); @@ -256,10 +246,9 @@ TestCountUsesTimeSource* test_count_uses_time_source = new TestCountUsesTimeSource(); - manager_ = base::MakeUnique<TaskQueueManagerForTest>( - MessageLoopTaskRunner::Create( - base::WrapUnique(test_count_uses_time_source)), - "test.scheduler", "test.scheduler", "test.scheduler.debug"); + manager_ = + base::MakeUnique<TaskQueueManagerForTest>(MessageLoopTaskRunner::Create( + base::WrapUnique(test_count_uses_time_source))); manager_->AddTaskTimeObserver(&test_task_time_observer_); runners_.push_back( @@ -1659,8 +1648,8 @@ std::vector<EnqueueOrder> run_order; - std::unique_ptr<RealTimeDomain> domain_a(new RealTimeDomain("test")); - std::unique_ptr<RealTimeDomain> domain_b(new RealTimeDomain("test")); + std::unique_ptr<RealTimeDomain> domain_a(new RealTimeDomain()); + std::unique_ptr<RealTimeDomain> domain_b(new RealTimeDomain()); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get());
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector.h index 2ebf18f..1fd9a60 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector.h
@@ -21,7 +21,7 @@ // TaskQueueSelector is used by the SchedulerHelper to enable prioritization // of particular task queues. -class BLINK_PLATFORM_EXPORT TaskQueueSelector { +class PLATFORM_EXPORT TaskQueueSelector { public: TaskQueueSelector(); ~TaskQueueSelector(); @@ -58,7 +58,7 @@ // Serialize the selector state for tracing. void AsValueInto(base::trace_event::TracedValue* state) const; - class BLINK_PLATFORM_EXPORT Observer { + class PLATFORM_EXPORT Observer { public: virtual ~Observer() {} @@ -83,7 +83,7 @@ bool EnabledWorkQueuesEmpty() const; protected: - class BLINK_PLATFORM_EXPORT PrioritizingSelector { + class PLATFORM_EXPORT PrioritizingSelector { public: PrioritizingSelector(TaskQueueSelector* task_queue_selector, const char* name);
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc index 08c5b0d..8e9c04c6 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc
@@ -122,10 +122,9 @@ virtual_time_domain_ = base::WrapUnique<VirtualTimeDomain>( new VirtualTimeDomain(base::TimeTicks())); for (size_t i = 0; i < kTaskQueueCount; i++) { - scoped_refptr<TaskQueueImpl> task_queue = - make_scoped_refptr(new TaskQueueImpl( - nullptr, virtual_time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), "test", "test")); + scoped_refptr<TaskQueueImpl> task_queue = make_scoped_refptr( + new TaskQueueImpl(nullptr, virtual_time_domain_.get(), + TaskQueue::Spec(TaskQueue::QueueType::TEST))); selector_.AddQueue(task_queue.get()); task_queues_.push_back(task_queue); } @@ -150,8 +149,7 @@ return make_scoped_refptr( new TaskQueueImpl(nullptr, virtual_time_domain_.get(), TaskQueue::Spec(TaskQueue::QueueType::TEST) - .SetShouldReportWhenExecutionBlocked(true), - "test", "test")); + .SetShouldReportWhenExecutionBlocked(true))); } const size_t kTaskQueueCount = 5;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_time_observer.h b/third_party/WebKit/Source/platform/scheduler/base/task_time_observer.h index 1131f8f..47ae3b94 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_time_observer.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_time_observer.h
@@ -6,7 +6,7 @@ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_BASE_TASK_TIME_OBSERVER_H_ #include "base/time/time.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace blink { namespace scheduler { @@ -14,7 +14,7 @@ class TaskQueue; // TaskTimeObserver provides an API for observing completion of renderer tasks. -class BLINK_PLATFORM_EXPORT TaskTimeObserver { +class PLATFORM_EXPORT TaskTimeObserver { public: TaskTimeObserver() {} virtual ~TaskTimeObserver() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/base/thread_load_tracker.h b/third_party/WebKit/Source/platform/scheduler/base/thread_load_tracker.h index d0d4e54..5a3d8ce 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/thread_load_tracker.h +++ b/third_party/WebKit/Source/platform/scheduler/base/thread_load_tracker.h
@@ -8,7 +8,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/time/time.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace blink { namespace scheduler { @@ -18,7 +18,7 @@ // In order to avoid bias it reports load level at regular intervals. // Every |reporting_interval_| time units, it reports the average thread load // level computed using a sliding window of width |reporting_interval_|. -class BLINK_PLATFORM_EXPORT ThreadLoadTracker { +class PLATFORM_EXPORT ThreadLoadTracker { public: // Callback is called with (current_time, load_level) parameters. using Callback = base::Callback<void(base::TimeTicks, double)>;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/time_domain.h index 82db58b..6f1abcf 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/time_domain.h
@@ -34,7 +34,7 @@ // Note the TimeDomain only knows about the first wake-up per queue, it's the // responsibility of TaskQueueImpl to keep the time domain up to date if this // changes. -class BLINK_PLATFORM_EXPORT TimeDomain { +class PLATFORM_EXPORT TimeDomain { public: TimeDomain(); virtual ~TimeDomain();
diff --git a/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc index 0e6fc28..0107d4d 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc
@@ -68,10 +68,9 @@ public: void SetUp() final { time_domain_ = base::WrapUnique(CreateMockTimeDomain()); - task_queue_ = make_scoped_refptr( - new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + task_queue_ = make_scoped_refptr(new internal::TaskQueueImpl( + nullptr, time_domain_.get(), + TaskQueue::Spec(TaskQueue::QueueType::TEST))); } void TearDown() final { @@ -138,18 +137,15 @@ TEST_F(TimeDomainTest, RequestWakeUpAt_OnlyCalledForEarlierTasks) { scoped_refptr<internal::TaskQueueImpl> task_queue2 = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); scoped_refptr<internal::TaskQueueImpl> task_queue3 = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); scoped_refptr<internal::TaskQueueImpl> task_queue4 = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); base::TimeDelta delay1 = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delay2 = base::TimeDelta::FromMilliseconds(20); @@ -185,8 +181,7 @@ TEST_F(TimeDomainTest, UnregisterQueue) { scoped_refptr<internal::TaskQueueImpl> task_queue2_ = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); base::TimeTicks now = time_domain_->Now(); base::TimeTicks wake_up1 = now + base::TimeDelta::FromMilliseconds(10); @@ -250,8 +245,7 @@ scoped_refptr<internal::TaskQueueImpl> task_queue2 = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); time_domain_->ScheduleDelayedWork(task_queue2.get(), {delayed_runtime, ++sequence_num}, now); @@ -289,8 +283,7 @@ TEST_F(TimeDomainTest, CancelDelayedWork_TwoQueues) { scoped_refptr<internal::TaskQueueImpl> task_queue2 = make_scoped_refptr( new internal::TaskQueueImpl(nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), - "test.category", "test.category")); + TaskQueue::Spec(TaskQueue::QueueType::TEST))); base::TimeTicks now = time_domain_->Now(); base::TimeTicks run_time1 = now + base::TimeDelta::FromMilliseconds(20);
diff --git a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h index 050c0ba..21d88db 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h
@@ -12,7 +12,7 @@ namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT VirtualTimeDomain : public TimeDomain { +class PLATFORM_EXPORT VirtualTimeDomain : public TimeDomain { public: VirtualTimeDomain(base::TimeTicks initial_time); ~VirtualTimeDomain() override;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/work_queue.h b/third_party/WebKit/Source/platform/scheduler/base/work_queue.h index 1dd47e1..ff0f55a 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/work_queue.h +++ b/third_party/WebKit/Source/platform/scheduler/base/work_queue.h
@@ -29,7 +29,7 @@ // API subset used by WorkQueueSets pretends the WorkQueue is empty until the // fence is removed. This functionality is a primitive intended for use by // throttling mechanisms. -class BLINK_PLATFORM_EXPORT WorkQueue { +class PLATFORM_EXPORT WorkQueue { public: enum class QueueType { DELAYED, IMMEDIATE };
diff --git a/third_party/WebKit/Source/platform/scheduler/base/work_queue_sets.h b/third_party/WebKit/Source/platform/scheduler/base/work_queue_sets.h index cbddfa43..c293405e 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/work_queue_sets.h +++ b/third_party/WebKit/Source/platform/scheduler/base/work_queue_sets.h
@@ -13,10 +13,10 @@ #include "base/logging.h" #include "base/macros.h" #include "base/trace_event/trace_event_argument.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/intrusive_heap.h" #include "platform/scheduler/base/task_queue_impl.h" #include "platform/scheduler/base/work_queue.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { @@ -28,7 +28,7 @@ // TaskQueueSelector chooses to run a task a given priority). The reason this // works is because std::map is a tree based associative container and all the // values are kept in sorted order. -class BLINK_PLATFORM_EXPORT WorkQueueSets { +class PLATFORM_EXPORT WorkQueueSets { public: WorkQueueSets(size_t num_sets, const char* name); ~WorkQueueSets();
diff --git a/third_party/WebKit/Source/platform/scheduler/base/work_queue_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/work_queue_unittest.cc index 2045fead..36fd80c 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/work_queue_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/work_queue_unittest.cc
@@ -23,10 +23,10 @@ class WorkQueueTest : public testing::Test { public: void SetUp() override { - time_domain_.reset(new RealTimeDomain("test")); - task_queue_ = make_scoped_refptr(new TaskQueueImpl( - nullptr, time_domain_.get(), - TaskQueue::Spec(TaskQueue::QueueType::TEST), "test", "test")); + time_domain_.reset(new RealTimeDomain()); + task_queue_ = make_scoped_refptr( + new TaskQueueImpl(nullptr, time_domain_.get(), + TaskQueue::Spec(TaskQueue::QueueType::TEST))); work_queue_.reset(new WorkQueue(task_queue_.get(), "test", WorkQueue::QueueType::IMMEDIATE));
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc index d2275cc..10522bcb 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc
@@ -20,11 +20,7 @@ CompositorWorkerScheduler::CompositorWorkerScheduler( base::Thread* thread, scoped_refptr<SchedulerTqmDelegate> main_task_runner) - : WorkerScheduler(WTF::MakeUnique<SchedulerHelper>( - main_task_runner, - "compositor.scheduler", - TRACE_DISABLED_BY_DEFAULT("compositor.scheduler"), - TRACE_DISABLED_BY_DEFAULT("compositor.scheduler.debug"))), + : WorkerScheduler(WTF::MakeUnique<SchedulerHelper>(main_task_runner)), thread_(thread) {} CompositorWorkerScheduler::~CompositorWorkerScheduler() {} @@ -46,8 +42,8 @@ // an idle task runner with the semantics we want for the compositor thread // which runs them after the current frame has been drawn before the next // vsync. https://crbug.com/609532 - return make_scoped_refptr(new SingleThreadIdleTaskRunner( - thread_->task_runner(), this, "compositor.scheduler")); + return make_scoped_refptr( + new SingleThreadIdleTaskRunner(thread_->task_runner(), this)); } bool CompositorWorkerScheduler::CanExceedIdleDeadlineIfRequired() const {
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h index 4e1a370..93f9601 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.h
@@ -6,8 +6,8 @@ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_COMPOSITOR_WORKER_SCHEDULER_H_ #include "base/macros.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/child/worker_scheduler.h" -#include "public/platform/WebCommon.h" #include "public/platform/scheduler/child/single_thread_idle_task_runner.h" namespace base { @@ -19,7 +19,7 @@ class SchedulerTqmDelegate; -class BLINK_PLATFORM_EXPORT CompositorWorkerScheduler +class PLATFORM_EXPORT CompositorWorkerScheduler : public WorkerScheduler, public SingleThreadIdleTaskRunner::Delegate { public:
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.cc b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.cc index ed969fb..78aa610f 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.cc
@@ -14,11 +14,9 @@ } IdleCanceledDelayedTaskSweeper::IdleCanceledDelayedTaskSweeper( - const char* tracing_category, SchedulerHelper* scheduler_helper, scoped_refptr<SingleThreadIdleTaskRunner> idle_task_runner) - : tracing_category_(tracing_category), - scheduler_helper_(scheduler_helper), + : scheduler_helper_(scheduler_helper), idle_task_runner_(idle_task_runner), weak_factory_(this) { PostIdleTask(); @@ -32,7 +30,7 @@ } void IdleCanceledDelayedTaskSweeper::SweepIdleTask(base::TimeTicks deadline) { - TRACE_EVENT0(tracing_category_, + TRACE_EVENT0("renderer.scheduler", "IdleCanceledDelayedTaskSweeper::SweepIdleTask"); scheduler_helper_->SweepCanceledDelayedTasks(); PostIdleTask();
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.h b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.h index 7482b147..b43620f 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.h +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper.h
@@ -14,10 +14,9 @@ // This class periodically sweeps away canceled delayed tasks, which helps // reduce memory consumption. -class BLINK_PLATFORM_EXPORT IdleCanceledDelayedTaskSweeper { +class PLATFORM_EXPORT IdleCanceledDelayedTaskSweeper { public: IdleCanceledDelayedTaskSweeper( - const char* tracing_category, SchedulerHelper* scheduler_helper, scoped_refptr<SingleThreadIdleTaskRunner> idle_task_runner); @@ -25,7 +24,6 @@ void PostIdleTask(); void SweepIdleTask(base::TimeTicks deadline); - const char* tracing_category_; // NOT OWNED SchedulerHelper* scheduler_helper_; // NOT OWNED scoped_refptr<SingleThreadIdleTaskRunner> idle_task_runner_; base::WeakPtrFactory<IdleCanceledDelayedTaskSweeper> weak_factory_;
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper_unittest.cc b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper_unittest.cc index 5fe0cb1..b0a4a89 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_canceled_delayed_task_sweeper_unittest.cc
@@ -36,21 +36,13 @@ delegate_(SchedulerTqmDelegateForTest::Create( mock_task_runner_, base::WrapUnique(new TestTimeSource(clock_.get())))), - scheduler_helper_(new SchedulerHelper( - delegate_, - "test.scheduler", - TRACE_DISABLED_BY_DEFAULT("test.scheduler"), - TRACE_DISABLED_BY_DEFAULT("test.scheduler.dbg"))), - idle_helper_( - new IdleHelper(scheduler_helper_.get(), - this, - "test.scheduler", - TRACE_DISABLED_BY_DEFAULT("test.scheduler"), - TRACE_DISABLED_BY_DEFAULT("test.scheduler.dbg"), - base::TimeDelta::FromSeconds(30))), + scheduler_helper_(new SchedulerHelper(delegate_)), + idle_helper_(new IdleHelper(scheduler_helper_.get(), + this, + "test", + base::TimeDelta::FromSeconds(30))), idle_canceled_delayed_taks_sweeper_( - new IdleCanceledDelayedTaskSweeper("test", - scheduler_helper_.get(), + new IdleCanceledDelayedTaskSweeper(scheduler_helper_.get(), idle_helper_->IdleTaskRunner())), default_task_queue_(scheduler_helper_->DefaultTaskQueue()) { clock_->Advance(base::TimeDelta::FromMicroseconds(5000));
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/idle_helper.cc index 8824f81..615f8d79 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_helper.cc
@@ -19,8 +19,6 @@ IdleHelper::IdleHelper( SchedulerHelper* helper, Delegate* delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, const char* idle_period_tracing_name, base::TimeDelta required_quiescence_duration_before_long_idle_period) : helper_(helper), @@ -29,13 +27,9 @@ helper_->NewTaskQueue(TaskQueue::Spec(TaskQueue::QueueType::IDLE))), state_(helper, delegate, - tracing_category, - disabled_by_default_tracing_category, idle_period_tracing_name), required_quiescence_duration_before_long_idle_period_( required_quiescence_duration_before_long_idle_period), - disabled_by_default_tracing_category_( - disabled_by_default_tracing_category), is_shutdown_(false), weak_factory_(this) { weak_idle_helper_ptr_ = weak_factory_.GetWeakPtr(); @@ -44,8 +38,8 @@ on_idle_task_posted_closure_.Reset(base::Bind( &IdleHelper::OnIdleTaskPostedOnMainThread, weak_idle_helper_ptr_)); - idle_task_runner_ = make_scoped_refptr( - new SingleThreadIdleTaskRunner(idle_queue_, this, tracing_category)); + idle_task_runner_ = + make_scoped_refptr(new SingleThreadIdleTaskRunner(idle_queue_, this)); // This fence will block any idle tasks from running. idle_queue_->InsertFence(TaskQueue::InsertFencePosition::BEGINNING_OF_TIME); @@ -126,13 +120,15 @@ } bool system_is_quiescent = helper_->GetAndClearSystemIsQuiescentBit(); - TRACE_EVENT1(disabled_by_default_tracing_category_, "ShouldWaitForQuiescence", - "system_is_quiescent", system_is_quiescent); + TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "ShouldWaitForQuiescence", "system_is_quiescent", + system_is_quiescent); return !system_is_quiescent; } void IdleHelper::EnableLongIdlePeriod() { - TRACE_EVENT0(disabled_by_default_tracing_category_, "EnableLongIdlePeriod"); + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "EnableLongIdlePeriod"); helper_->CheckOnValidThread(); if (is_shutdown_) return; @@ -177,14 +173,15 @@ base::TimeDelta idle_period_duration(idle_period_deadline - now); if (idle_period_duration < base::TimeDelta::FromMilliseconds(kMinimumIdlePeriodDurationMillis)) { - TRACE_EVENT1(disabled_by_default_tracing_category_, + TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "NotStartingIdlePeriodBecauseDeadlineIsTooClose", "idle_period_duration_ms", idle_period_duration.InMillisecondsF()); return; } - TRACE_EVENT0(disabled_by_default_tracing_category_, "StartIdlePeriod"); + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "StartIdlePeriod"); if (!IsInIdlePeriod(state_.idle_period_state())) helper_->AddTaskObserver(this); @@ -200,7 +197,8 @@ return; helper_->CheckOnValidThread(); - TRACE_EVENT0(disabled_by_default_tracing_category_, "EndIdlePeriod"); + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "EndIdlePeriod"); enable_next_long_idle_period_closure_.Cancel(); on_idle_task_posted_closure_.Cancel(); @@ -225,7 +223,8 @@ helper_->CheckOnValidThread(); DCHECK(!is_shutdown_); DCHECK(IsInIdlePeriod(state_.idle_period_state())); - TRACE_EVENT0(disabled_by_default_tracing_category_, "DidProcessTask"); + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "DidProcessTask"); if (state_.idle_period_state() != IdlePeriodState::IN_LONG_IDLE_PERIOD_PAUSED && helper_->scheduler_tqm_delegate()->NowTicks() >= @@ -246,7 +245,7 @@ helper_->CheckOnValidThread(); DCHECK(!is_shutdown_); DCHECK(IsInLongIdlePeriod(state_.idle_period_state())); - TRACE_EVENT0(disabled_by_default_tracing_category_, + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "UpdateLongIdlePeriodStateAfterIdleTask"); if (!idle_queue_->HasPendingImmediateWork()) { @@ -285,7 +284,8 @@ } void IdleHelper::OnIdleTaskPosted() { - TRACE_EVENT0(disabled_by_default_tracing_category_, "OnIdleTaskPosted"); + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "OnIdleTaskPosted"); if (is_shutdown_) return; if (idle_task_runner_->RunsTasksOnCurrentThread()) { @@ -297,7 +297,7 @@ } void IdleHelper::OnIdleTaskPostedOnMainThread() { - TRACE_EVENT0(disabled_by_default_tracing_category_, + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "OnIdleTaskPostedOnMainThread"); if (is_shutdown_) return; @@ -343,7 +343,7 @@ } bool IdleHelper::CanExceedIdleDeadlineIfRequired() const { - TRACE_EVENT0(disabled_by_default_tracing_category_, + TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "CanExceedIdleDeadlineIfRequired"); helper_->CheckOnValidThread(); return state_.idle_period_state() == @@ -356,17 +356,12 @@ IdleHelper::State::State(SchedulerHelper* helper, Delegate* delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, const char* idle_period_tracing_name) : helper_(helper), delegate_(delegate), idle_period_state_(IdlePeriodState::NOT_IN_IDLE_PERIOD), idle_period_trace_event_started_(false), running_idle_task_for_tracing_(false), - tracing_category_(tracing_category), - disabled_by_default_tracing_category_( - disabled_by_default_tracing_category), idle_period_tracing_name_(idle_period_tracing_name) {} IdleHelper::State::~State() {} @@ -393,7 +388,7 @@ } bool is_tracing; - TRACE_EVENT_CATEGORY_GROUP_ENABLED(tracing_category_, &is_tracing); + TRACE_EVENT_CATEGORY_GROUP_ENABLED("renderer.scheduler", &is_tracing); if (is_tracing) { base::TimeTicks now(optional_now.is_null() ? helper_->scheduler_tqm_delegate()->NowTicks() @@ -418,7 +413,7 @@ helper_->CheckOnValidThread(); bool is_tracing; - TRACE_EVENT_CATEGORY_GROUP_ENABLED(tracing_category_, &is_tracing); + TRACE_EVENT_CATEGORY_GROUP_ENABLED("renderer.scheduler", &is_tracing); if (is_tracing) { TraceEventIdlePeriodStateChange(idle_period_state_, true, idle_period_deadline_, @@ -430,7 +425,7 @@ helper_->CheckOnValidThread(); bool is_tracing; - TRACE_EVENT_CATEGORY_GROUP_ENABLED(tracing_category_, &is_tracing); + TRACE_EVENT_CATEGORY_GROUP_ENABLED("renderer.scheduler", &is_tracing); if (is_tracing) { TraceEventIdlePeriodStateChange(idle_period_state_, false, idle_period_deadline_, @@ -443,8 +438,8 @@ bool new_running_idle_task, base::TimeTicks new_deadline, base::TimeTicks now) { - TRACE_EVENT2(disabled_by_default_tracing_category_, "SetIdlePeriodState", - "old_state", + TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), + "SetIdlePeriodState", "old_state", IdleHelper::IdlePeriodStateToString(idle_period_state_), "new_state", IdleHelper::IdlePeriodStateToString(new_state)); @@ -453,7 +448,8 @@ running_idle_task_for_tracing_ = false; if (!idle_period_deadline_.is_null() && now > idle_period_deadline_) { TRACE_EVENT_ASYNC_STEP_INTO_WITH_TIMESTAMP0( - tracing_category_, idle_period_tracing_name_, this, "DeadlineOverrun", + "renderer.scheduler", idle_period_tracing_name_, this, + "DeadlineOverrun", std::max(idle_period_deadline_, last_idle_task_trace_time_)); } } @@ -461,7 +457,7 @@ if (IsInIdlePeriod(new_state)) { if (!idle_period_trace_event_started_) { idle_period_trace_event_started_ = true; - TRACE_EVENT_ASYNC_BEGIN1(tracing_category_, idle_period_tracing_name_, + TRACE_EVENT_ASYNC_BEGIN1("renderer.scheduler", idle_period_tracing_name_, this, "idle_period_length_ms", (new_deadline - now).ToInternalValue()); } @@ -469,22 +465,27 @@ if (new_running_idle_task) { last_idle_task_trace_time_ = now; running_idle_task_for_tracing_ = true; - TRACE_EVENT_ASYNC_STEP_INTO0(tracing_category_, idle_period_tracing_name_, - this, "RunningIdleTask"); + TRACE_EVENT_ASYNC_STEP_INTO0("renderer.scheduler", + idle_period_tracing_name_, this, + "RunningIdleTask"); } else if (new_state == IdlePeriodState::IN_SHORT_IDLE_PERIOD) { - TRACE_EVENT_ASYNC_STEP_INTO0(tracing_category_, idle_period_tracing_name_, - this, "ShortIdlePeriod"); + TRACE_EVENT_ASYNC_STEP_INTO0("renderer.scheduler", + idle_period_tracing_name_, this, + "ShortIdlePeriod"); } else if (IsInLongIdlePeriod(new_state) && new_state != IdlePeriodState::IN_LONG_IDLE_PERIOD_PAUSED) { - TRACE_EVENT_ASYNC_STEP_INTO0(tracing_category_, idle_period_tracing_name_, - this, "LongIdlePeriod"); + TRACE_EVENT_ASYNC_STEP_INTO0("renderer.scheduler", + idle_period_tracing_name_, this, + "LongIdlePeriod"); } else if (new_state == IdlePeriodState::IN_LONG_IDLE_PERIOD_PAUSED) { - TRACE_EVENT_ASYNC_STEP_INTO0(tracing_category_, idle_period_tracing_name_, - this, "LongIdlePeriodPaused"); + TRACE_EVENT_ASYNC_STEP_INTO0("renderer.scheduler", + idle_period_tracing_name_, this, + "LongIdlePeriodPaused"); } } else if (idle_period_trace_event_started_) { idle_period_trace_event_started_ = false; - TRACE_EVENT_ASYNC_END0(tracing_category_, idle_period_tracing_name_, this); + TRACE_EVENT_ASYNC_END0("renderer.scheduler", idle_period_tracing_name_, + this); } }
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_helper.h b/third_party/WebKit/Source/platform/scheduler/child/idle_helper.h index 602f1b2e..4b1d5876 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_helper.h +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_helper.h
@@ -7,11 +7,11 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/cancelable_closure_holder.h" #include "platform/scheduler/base/task_queue_selector.h" #include "platform/scheduler/child/scheduler_helper.h" #include "public/platform/scheduler/child/single_thread_idle_task_runner.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { @@ -37,12 +37,11 @@ // // Idle tasks are supplied a deadline, and should endeavor to finished before it // ends to avoid jank. -class BLINK_PLATFORM_EXPORT IdleHelper - : public base::MessageLoop::TaskObserver, - public SingleThreadIdleTaskRunner::Delegate { +class PLATFORM_EXPORT IdleHelper : public base::MessageLoop::TaskObserver, + public SingleThreadIdleTaskRunner::Delegate { public: // Used to by scheduler implementations to customize idle behaviour. - class BLINK_PLATFORM_EXPORT Delegate { + class PLATFORM_EXPORT Delegate { public: Delegate(); virtual ~Delegate(); @@ -88,8 +87,6 @@ IdleHelper( SchedulerHelper* helper, Delegate* delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, const char* idle_period_tracing_name, base::TimeDelta required_quiescence_duration_before_long_idle_period); ~IdleHelper() override; @@ -157,8 +154,6 @@ public: State(SchedulerHelper* helper, Delegate* delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, const char* idle_period_tracing_name); virtual ~State(); @@ -188,8 +183,6 @@ base::TimeTicks last_idle_task_trace_time_; bool idle_period_trace_event_started_; bool running_idle_task_for_tracing_; - const char* tracing_category_; - const char* disabled_by_default_tracing_category_; const char* idle_period_tracing_name_; DISALLOW_COPY_AND_ASSIGN(State); @@ -233,8 +226,6 @@ base::TimeDelta required_quiescence_duration_before_long_idle_period_; - const char* disabled_by_default_tracing_category_; - bool is_shutdown_; base::WeakPtr<IdleHelper> weak_idle_helper_ptr_;
diff --git a/third_party/WebKit/Source/platform/scheduler/child/idle_helper_unittest.cc b/third_party/WebKit/Source/platform/scheduler/child/idle_helper_unittest.cc index db533c5..d5311fc 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/idle_helper_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/idle_helper_unittest.cc
@@ -159,8 +159,6 @@ base::TimeDelta required_quiescence_duration_before_long_idle_period) : IdleHelper(scheduler_helper, this, - "test.idle", - TRACE_DISABLED_BY_DEFAULT("test.idle"), "TestSchedulerIdlePeriod", required_quiescence_duration_before_long_idle_period) {} @@ -191,11 +189,7 @@ message_loop, mock_task_runner_, base::WrapUnique(new TestTimeSource(clock_.get())))), - scheduler_helper_( - new SchedulerHelper(main_task_runner_, - "test.idle", - TRACE_DISABLED_BY_DEFAULT("test.idle"), - TRACE_DISABLED_BY_DEFAULT("test.idle.debug"))), + scheduler_helper_(new SchedulerHelper(main_task_runner_)), idle_helper_(new IdleHelperForTest( scheduler_helper_.get(), required_quiescence_duration_before_long_idle_period)),
diff --git a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.cc b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.cc index 64f18e2..b0a71c95 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.cc
@@ -14,37 +14,21 @@ namespace scheduler { SchedulerHelper::SchedulerHelper( - scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category) + scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate) : SchedulerHelper(task_queue_manager_delegate, - tracing_category, - disabled_by_default_tracing_category, - disabled_by_default_verbose_tracing_category, TaskQueue::Spec(TaskQueue::QueueType::DEFAULT) .SetShouldMonitorQuiescence(true)) {} SchedulerHelper::SchedulerHelper( scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category, TaskQueue::Spec default_task_queue_spec) : task_queue_manager_delegate_(task_queue_manager_delegate), - task_queue_manager_( - new TaskQueueManager(task_queue_manager_delegate, - tracing_category, - disabled_by_default_tracing_category, - disabled_by_default_verbose_tracing_category)), + task_queue_manager_(new TaskQueueManager(task_queue_manager_delegate)), control_task_queue_( NewTaskQueue(TaskQueue::Spec(TaskQueue::QueueType::CONTROL) .SetShouldNotifyObservers(false))), default_task_queue_(NewTaskQueue(default_task_queue_spec)), - observer_(nullptr), - tracing_category_(tracing_category), - disabled_by_default_tracing_category_( - disabled_by_default_tracing_category) { + observer_(nullptr) { control_task_queue_->SetQueuePriority(TaskQueue::CONTROL_PRIORITY); task_queue_manager_->SetWorkBatchSize(4);
diff --git a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.h b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.h index 46bb9ee..0b252f7f 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.h +++ b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper.h
@@ -18,21 +18,12 @@ class SchedulerTqmDelegate; // Common scheduler functionality for default tasks. -class BLINK_PLATFORM_EXPORT SchedulerHelper - : public TaskQueueManager::Observer { +class PLATFORM_EXPORT SchedulerHelper : public TaskQueueManager::Observer { public: - // Category strings must have application lifetime (statics or - // literals). They may not include " chars. - SchedulerHelper( + explicit SchedulerHelper( + scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate); + explicit SchedulerHelper( scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category); - SchedulerHelper( - scoped_refptr<SchedulerTqmDelegate> task_queue_manager_delegate, - const char* tracing_category, - const char* disabled_by_default_tracing_category, - const char* disabled_by_default_verbose_tracing_category, TaskQueue::Spec default_task_queue_spec); ~SchedulerHelper() override; @@ -77,7 +68,7 @@ // Creates a new TaskQueue with the given |spec|. scoped_refptr<TaskQueue> NewTaskQueue(const TaskQueue::Spec& spec); - class BLINK_PLATFORM_EXPORT Observer { + class PLATFORM_EXPORT Observer { public: virtual ~Observer() {} @@ -123,8 +114,6 @@ scoped_refptr<TaskQueue> default_task_queue_; Observer* observer_; // NOT OWNED - const char* tracing_category_; - const char* disabled_by_default_tracing_category_; DISALLOW_COPY_AND_ASSIGN(SchedulerHelper); };
diff --git a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper_unittest.cc b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper_unittest.cc index a6f3515..edef613 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/scheduler_helper_unittest.cc
@@ -53,11 +53,7 @@ main_task_runner_(SchedulerTqmDelegateForTest::Create( mock_task_runner_, base::WrapUnique(new TestTimeSource(clock_.get())))), - scheduler_helper_(new SchedulerHelper( - main_task_runner_, - "test.scheduler", - TRACE_DISABLED_BY_DEFAULT("test.scheduler"), - TRACE_DISABLED_BY_DEFAULT("test.scheduler.dbg"))), + scheduler_helper_(new SchedulerHelper(main_task_runner_)), default_task_runner_(scheduler_helper_->DefaultTaskQueue()) { clock_->Advance(base::TimeDelta::FromMicroseconds(5000)); }
diff --git a/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate.h b/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate.h index 79c2c774..1b5cdaec 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate.h +++ b/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate.h
@@ -12,8 +12,7 @@ namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT SchedulerTqmDelegate - : public TaskQueueManagerDelegate { +class PLATFORM_EXPORT SchedulerTqmDelegate : public TaskQueueManagerDelegate { public: SchedulerTqmDelegate() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate_impl.h b/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate_impl.h index b043ff4..2d34af4c 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/scheduler_tqm_delegate_impl.h
@@ -16,8 +16,7 @@ namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT SchedulerTqmDelegateImpl - : public SchedulerTqmDelegate { +class PLATFORM_EXPORT SchedulerTqmDelegateImpl : public SchedulerTqmDelegate { public: // |message_loop| is not owned and must outlive the lifetime of this object. static scoped_refptr<SchedulerTqmDelegateImpl> Create(
diff --git a/third_party/WebKit/Source/platform/scheduler/child/single_thread_idle_task_runner.cc b/third_party/WebKit/Source/platform/scheduler/child/single_thread_idle_task_runner.cc index 2ffc75b..93cb75b 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/single_thread_idle_task_runner.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/single_thread_idle_task_runner.cc
@@ -13,11 +13,9 @@ SingleThreadIdleTaskRunner::SingleThreadIdleTaskRunner( scoped_refptr<base::SingleThreadTaskRunner> idle_priority_task_runner, - Delegate* delegate, - const char* tracing_category) + Delegate* delegate) : idle_priority_task_runner_(idle_priority_task_runner), delegate_(delegate), - tracing_category_(tracing_category), blame_context_(nullptr), weak_factory_(this) { DCHECK(!idle_priority_task_runner_ || @@ -80,7 +78,7 @@ void SingleThreadIdleTaskRunner::RunTask(IdleTask idle_task) { base::TimeTicks deadline = delegate_->WillProcessIdleTask(); - TRACE_EVENT1(tracing_category_, "SingleThreadIdleTaskRunner::RunTask", + TRACE_EVENT1("renderer.scheduler", "SingleThreadIdleTaskRunner::RunTask", "allotted_time_ms", (deadline - base::TimeTicks::Now()).InMillisecondsF()); if (blame_context_)
diff --git a/third_party/WebKit/Source/platform/scheduler/child/web_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/web_scheduler.h index 99a3196..8257671c 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/web_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/web_scheduler.h
@@ -20,9 +20,9 @@ // This class is used to submit tasks and pass other information from Blink to // the platform's scheduler. // TODO(skyostil): Replace this class with RendererScheduler. -class BLINK_PLATFORM_EXPORT WebScheduler { +class PLATFORM_EXPORT WebScheduler { public: - class BLINK_PLATFORM_EXPORT InterventionReporter { + class PLATFORM_EXPORT InterventionReporter { public: virtual ~InterventionReporter() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/child/web_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/child/web_scheduler_impl.h index 29736e0..af3f0166 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/web_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/web_scheduler_impl.h
@@ -10,9 +10,9 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/child/web_scheduler.h" -#include "public/platform/WebCommon.h" #include "public/platform/WebThread.h" namespace blink { @@ -22,7 +22,7 @@ class SingleThreadIdleTaskRunner; class WebTaskRunnerImpl; -class BLINK_PLATFORM_EXPORT WebSchedulerImpl : public WebScheduler { +class PLATFORM_EXPORT WebSchedulerImpl : public WebScheduler { public: WebSchedulerImpl(ChildScheduler* child_scheduler, scoped_refptr<SingleThreadIdleTaskRunner> idle_task_runner,
diff --git a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h index 722b941..a62de61 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h
@@ -11,14 +11,14 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" +#include "platform/PlatformExport.h" #include "platform/WebTaskRunner.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { class TaskQueue; -class BLINK_PLATFORM_EXPORT WebTaskRunnerImpl : public WebTaskRunner { +class PLATFORM_EXPORT WebTaskRunnerImpl : public WebTaskRunner { public: static RefPtr<WebTaskRunnerImpl> Create(scoped_refptr<TaskQueue> task_queue);
diff --git a/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.h index 5b9e0057..fd28795 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.h
@@ -26,7 +26,7 @@ class WebTaskRunnerImpl; class WorkerScheduler; -class BLINK_PLATFORM_EXPORT WebThreadImplForWorkerScheduler +class PLATFORM_EXPORT WebThreadImplForWorkerScheduler : public WebThreadBase, public base::MessageLoop::DestructionObserver { public:
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_global_scope_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/worker_global_scope_scheduler.h index 99f0d40..f4596d3 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_global_scope_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_global_scope_scheduler.h
@@ -5,9 +5,9 @@ #ifndef THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_WORKER_GLOBAL_SCOPE_SCHEDULER_H_ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_CHILD_WORKER_GLOBAL_SCOPE_SCHEDULER_H_ +#include "platform/PlatformExport.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/child/web_task_runner_impl.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { @@ -18,7 +18,7 @@ // global scope is created and destructed when it's closed. // // Unless stated otherwise, all methods must be called on the worker thread. -class BLINK_PLATFORM_EXPORT WorkerGlobalScopeScheduler { +class PLATFORM_EXPORT WorkerGlobalScopeScheduler { public: explicit WorkerGlobalScopeScheduler(WorkerScheduler* worker_scheduler); ~WorkerGlobalScopeScheduler();
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h index 2e34af7..1e55375 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler.h
@@ -9,9 +9,9 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/child/scheduler_helper.h" -#include "public/platform/WebCommon.h" #include "public/platform/scheduler/child/child_scheduler.h" #include "public/platform/scheduler/child/single_thread_idle_task_runner.h" @@ -19,7 +19,7 @@ namespace scheduler { class SchedulerTqmDelegate; -class BLINK_PLATFORM_EXPORT WorkerScheduler : public ChildScheduler { +class PLATFORM_EXPORT WorkerScheduler : public ChildScheduler { public: ~WorkerScheduler() override; static std::unique_ptr<WorkerScheduler> Create(
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc index caa31060..8d616a4 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.cc
@@ -38,19 +38,12 @@ WorkerSchedulerImpl::WorkerSchedulerImpl( scoped_refptr<SchedulerTqmDelegate> main_task_runner) - : WorkerScheduler(WTF::MakeUnique<SchedulerHelper>( - main_task_runner, - "worker.scheduler", - TRACE_DISABLED_BY_DEFAULT("worker.scheduler"), - TRACE_DISABLED_BY_DEFAULT("worker.scheduler.debug"))), + : WorkerScheduler(WTF::MakeUnique<SchedulerHelper>(main_task_runner)), idle_helper_(helper_.get(), this, - "worker.scheduler", - TRACE_DISABLED_BY_DEFAULT("worker.scheduler"), "WorkerSchedulerIdlePeriod", base::TimeDelta::FromMilliseconds(300)), - idle_canceled_delayed_task_sweeper_("worker.scheduler", - helper_.get(), + idle_canceled_delayed_task_sweeper_(helper_.get(), idle_helper_.IdleTaskRunner()), load_tracker_(helper_->scheduler_tqm_delegate()->NowTicks(), base::Bind(&ReportWorkerTaskLoad),
diff --git a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h index 0e1d14e..945e125 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/worker_scheduler_impl.h
@@ -17,9 +17,9 @@ class SchedulerTqmDelegate; -class BLINK_PLATFORM_EXPORT WorkerSchedulerImpl : public WorkerScheduler, - public IdleHelper::Delegate, - public TaskTimeObserver { +class PLATFORM_EXPORT WorkerSchedulerImpl : public WorkerScheduler, + public IdleHelper::Delegate, + public TaskTimeObserver { public: explicit WorkerSchedulerImpl( scoped_refptr<SchedulerTqmDelegate> main_task_runner);
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.h b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.h index 1002787c..7e80525e 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.h
@@ -20,7 +20,7 @@ // // |ABCDE (Execution with AutoAdvancingVirtualTimeDomain) // |-----------------------------> time -class BLINK_PLATFORM_EXPORT AutoAdvancingVirtualTimeDomain +class PLATFORM_EXPORT AutoAdvancingVirtualTimeDomain : public VirtualTimeDomain { public: explicit AutoAdvancingVirtualTimeDomain(base::TimeTicks initial_time);
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain_unittest.cc index 82c1e55..7351924 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain_unittest.cc
@@ -32,9 +32,7 @@ main_task_runner_ = SchedulerTqmDelegateForTest::Create( mock_task_runner_, base::MakeUnique<TestTimeSource>(clock_.get())); - manager_ = base::MakeUnique<TaskQueueManager>( - main_task_runner_, "test.scheduler", "test.scheduler", - "test.scheduler.debug"); + manager_ = base::MakeUnique<TaskQueueManager>(main_task_runner_); manager_->AddTaskTimeObserver(&test_task_time_observer_); task_queue_ = manager_->NewTaskQueue(TaskQueue::Spec(TaskQueue::QueueType::TEST));
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/budget_pool.h b/third_party/WebKit/Source/platform/scheduler/renderer/budget_pool.h index 9bcb72a..d00a42a 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/budget_pool.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/budget_pool.h
@@ -29,7 +29,7 @@ // BudgetPool represents a group of task queues which share a limit // on a resource. This limit applies when task queues are already throttled // by TaskQueueThrottler. -class BLINK_PLATFORM_EXPORT BudgetPool { +class PLATFORM_EXPORT BudgetPool { public: virtual ~BudgetPool(); @@ -90,7 +90,7 @@ // CPUTimeBudgetPool represents a collection of task queues which share a limit // on total cpu time. -class BLINK_PLATFORM_EXPORT CPUTimeBudgetPool : public BudgetPool { +class PLATFORM_EXPORT CPUTimeBudgetPool : public BudgetPool { public: CPUTimeBudgetPool(const char* name, BudgetPoolController* budget_pool_controller,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/deadline_task_runner.h b/third_party/WebKit/Source/platform/scheduler/renderer/deadline_task_runner.h index 41937ae..8d61cf2a 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/deadline_task_runner.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/deadline_task_runner.h
@@ -10,14 +10,14 @@ #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/time/time.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/cancelable_closure_holder.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { // Runs a posted task at latest by a given deadline, but possibly sooner. -class BLINK_PLATFORM_EXPORT DeadlineTaskRunner { +class PLATFORM_EXPORT DeadlineTaskRunner { public: DeadlineTaskRunner(const base::Closure& callback, scoped_refptr<base::SingleThreadTaskRunner> task_runner);
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator.h b/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator.h index 5987d914..bfd43af 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator.h
@@ -9,14 +9,14 @@ #include "base/message_loop/message_loop.h" #include "base/time/tick_clock.h" #include "cc/base/rolling_time_delta_history.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/task_queue.h" -#include "public/platform/WebCommon.h" namespace blink { namespace scheduler { // Estimates how much idle time there is available. Ignores nested tasks. -class BLINK_PLATFORM_EXPORT IdleTimeEstimator +class PLATFORM_EXPORT IdleTimeEstimator : public base::MessageLoop::TaskObserver { public: IdleTimeEstimator(const scoped_refptr<TaskQueue>& compositor_task_runner,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator_unittest.cc index d116859..14e62b43 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/idle_time_estimator_unittest.cc
@@ -45,9 +45,7 @@ new cc::OrderedSimpleTaskRunner(clock_.get(), false)); main_task_runner_ = SchedulerTqmDelegateForTest::Create( mock_task_runner_, base::MakeUnique<TestTimeSource>(clock_.get())); - manager_ = base::MakeUnique<TaskQueueManager>( - main_task_runner_, "test.scheduler", "test.scheduler", - "test.scheduler.debug"); + manager_ = base::MakeUnique<TaskQueueManager>(main_task_runner_); compositor_task_queue_ = manager_->NewTaskQueue( TaskQueue::Spec(TaskQueue::QueueType::COMPOSITOR)); estimator_.reset(new IdleTimeEstimatorForTest(
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/render_widget_signals.h b/third_party/WebKit/Source/platform/scheduler/renderer/render_widget_signals.h index ba9d7c0..9ee1c9f19 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/render_widget_signals.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/render_widget_signals.h
@@ -9,16 +9,16 @@ #include "base/trace_event/trace_event.h" #include "base/trace_event/trace_event_argument.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace blink { namespace scheduler { class RenderWidgetSchedulingState; -class BLINK_PLATFORM_EXPORT RenderWidgetSignals { +class PLATFORM_EXPORT RenderWidgetSignals { public: - class BLINK_PLATFORM_EXPORT Observer { + class PLATFORM_EXPORT Observer { public: virtual ~Observer() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc index 112af82..d7db5c1 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
@@ -87,18 +87,12 @@ RendererSchedulerImpl::RendererSchedulerImpl( scoped_refptr<SchedulerTqmDelegate> main_task_runner) - : helper_(main_task_runner, - "renderer.scheduler", - TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), - TRACE_DISABLED_BY_DEFAULT("renderer.scheduler.debug")), + : helper_(main_task_runner), idle_helper_(&helper_, this, - "renderer.scheduler", - TRACE_DISABLED_BY_DEFAULT("renderer.scheduler"), "RendererSchedulerIdlePeriod", base::TimeDelta()), - idle_canceled_delayed_task_sweeper_("renderer.scheduler", - &helper_, + idle_canceled_delayed_task_sweeper_(&helper_, idle_helper_.IdleTaskRunner()), render_widget_scheduler_signals_(this), control_task_queue_(helper_.ControlTaskQueue()), @@ -119,8 +113,7 @@ helper_.scheduler_tqm_delegate()->NowTicks()), policy_may_need_update_(&any_thread_lock_), weak_factory_(this) { - task_queue_throttler_.reset( - new TaskQueueThrottler(this, "renderer.scheduler")); + task_queue_throttler_.reset(new TaskQueueThrottler(this)); update_policy_closure_ = base::Bind(&RendererSchedulerImpl::UpdatePolicy, weak_factory_.GetWeakPtr()); end_renderer_hidden_idle_period_closure_.Reset(base::Bind(
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h index 1af8c53..2cded99 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.h
@@ -39,7 +39,7 @@ class WebViewSchedulerImpl; class TaskQueueThrottler; -class BLINK_PLATFORM_EXPORT RendererSchedulerImpl +class PLATFORM_EXPORT RendererSchedulerImpl : public RendererScheduler, public IdleHelper::Delegate, public SchedulerHelper::Observer,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_web_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_web_scheduler_impl.h index ade2ead..06ba0986 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_web_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_web_scheduler_impl.h
@@ -12,7 +12,7 @@ class RendererSchedulerImpl; -class BLINK_PLATFORM_EXPORT RendererWebSchedulerImpl : public WebSchedulerImpl { +class PLATFORM_EXPORT RendererWebSchedulerImpl : public WebSchedulerImpl { public: explicit RendererWebSchedulerImpl(RendererSchedulerImpl* renderer_scheduler);
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_cost_estimator.h b/third_party/WebKit/Source/platform/scheduler/renderer/task_cost_estimator.h index 0b8298a..3f0631e 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_cost_estimator.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_cost_estimator.h
@@ -9,7 +9,7 @@ #include "base/message_loop/message_loop.h" #include "base/time/time.h" #include "cc/base/rolling_time_delta_history.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" namespace base { class TickClock; @@ -19,7 +19,7 @@ namespace scheduler { // Estimates the cost of running tasks based on historical timing data. -class BLINK_PLATFORM_EXPORT TaskCostEstimator +class PLATFORM_EXPORT TaskCostEstimator : public base::MessageLoop::TaskObserver { public: TaskCostEstimator(base::TickClock* time_source,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc index d37e3f92..7191ec4a 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc
@@ -73,13 +73,11 @@ } // namespace TaskQueueThrottler::TaskQueueThrottler( - RendererSchedulerImpl* renderer_scheduler, - const char* tracing_category) + RendererSchedulerImpl* renderer_scheduler) : control_task_queue_(renderer_scheduler->ControlTaskQueue()), renderer_scheduler_(renderer_scheduler), tick_clock_(renderer_scheduler->tick_clock()), - tracing_category_(tracing_category), - time_domain_(new ThrottledTimeDomain(tracing_category)), + time_domain_(new ThrottledTimeDomain()), allow_throttling_(true), weak_factory_(this) { pump_throttled_tasks_closure_.Reset(base::Bind( @@ -118,7 +116,7 @@ if (insert_result.first->second.throttling_ref_count != 1) return; - TRACE_EVENT1(tracing_category_, "TaskQueueThrottler_TaskQueueThrottled", + TRACE_EVENT1("renderer.scheduler", "TaskQueueThrottler_TaskQueueThrottled", "task_queue", task_queue); task_queue->SetObserver(this); @@ -149,7 +147,7 @@ return; } - TRACE_EVENT1(tracing_category_, "TaskQueueThrottler_TaskQueueUnthrottled", + TRACE_EVENT1("renderer.scheduler", "TaskQueueThrottler_TaskQueueUnthrottled", "task_queue", task_queue); task_queue->SetObserver(nullptr); @@ -201,7 +199,7 @@ return; } - TRACE_EVENT0(tracing_category_, + TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler::OnQueueNextWakeUpChanged"); // We don't expect this to get called for disabled queues, but we can't DCHECK @@ -216,7 +214,7 @@ } void TaskQueueThrottler::PumpThrottledTasks() { - TRACE_EVENT0(tracing_category_, "TaskQueueThrottler::PumpThrottledTasks"); + TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler::PumpThrottledTasks"); pending_pump_throttled_tasks_runtime_.reset(); LazyNow lazy_now(tick_clock_); @@ -236,7 +234,7 @@ if (next_desired_run_time && next_allowed_run_time > next_desired_run_time.value()) { TRACE_EVENT1( - tracing_category_, + "renderer.scheduler", "TaskQueueThrottler::PumpThrottledTasks_ExpensiveTaskThrottled", "throttle_time_in_seconds", (next_allowed_run_time - next_desired_run_time.value()).InSecondsF()); @@ -300,7 +298,7 @@ pump_throttled_tasks_closure_.Cancel(); base::TimeDelta delay = pending_pump_throttled_tasks_runtime_.value() - now; - TRACE_EVENT1(tracing_category_, + TRACE_EVENT1("renderer.scheduler", "TaskQueueThrottler::MaybeSchedulePumpThrottledTasks", "delay_till_next_pump_ms", delay.InMilliseconds()); control_task_queue_->PostDelayedTask( @@ -462,7 +460,7 @@ pump_throttled_tasks_closure_.Cancel(); pending_pump_throttled_tasks_runtime_ = base::nullopt; - TRACE_EVENT0(tracing_category_, "TaskQueueThrottler_DisableThrottling"); + TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler_DisableThrottling"); } void TaskQueueThrottler::EnableThrottling() { @@ -486,7 +484,7 @@ SchedulePumpQueue(FROM_HERE, lazy_now.Now(), queue); } - TRACE_EVENT0(tracing_category_, "TaskQueueThrottler_EnableThrottling"); + TRACE_EVENT0("renderer.scheduler", "TaskQueueThrottler_EnableThrottling"); } } // namespace scheduler
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h index a6d1f842..ac592408 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h
@@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/optional.h" #include "base/threading/thread_checker.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/cancelable_closure_holder.h" #include "platform/scheduler/base/time_domain.h" #include "platform/scheduler/renderer/budget_pool.h" @@ -32,7 +33,7 @@ class CPUTimeBudgetPool; // Interface for BudgetPool to interact with TaskQueueThrottler. -class BLINK_PLATFORM_EXPORT BudgetPoolController { +class PLATFORM_EXPORT BudgetPoolController { public: virtual ~BudgetPoolController() {} @@ -80,13 +81,10 @@ // See IncreaseThrottleRefCount & DecreaseThrottleRefCount. // // This class is main-thread only. -class BLINK_PLATFORM_EXPORT TaskQueueThrottler : public TaskQueue::Observer, - public BudgetPoolController { +class PLATFORM_EXPORT TaskQueueThrottler : public TaskQueue::Observer, + public BudgetPoolController { public: - // TODO(altimin): Do not pass tracing category as const char*, - // hard-code string instead. - TaskQueueThrottler(RendererSchedulerImpl* renderer_scheduler, - const char* tracing_category); + explicit TaskQueueThrottler(RendererSchedulerImpl* renderer_scheduler); ~TaskQueueThrottler() override; @@ -179,7 +177,6 @@ scoped_refptr<TaskQueue> control_task_queue_; RendererSchedulerImpl* renderer_scheduler_; // NOT OWNED base::TickClock* tick_clock_; // NOT OWNED - const char* tracing_category_; // NOT OWNED std::unique_ptr<ThrottledTimeDomain> time_domain_; CancelableClosureHolder pump_throttled_tasks_closure_;
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc index 9126c6f0..f7a7205e 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc
@@ -7,8 +7,7 @@ namespace blink { namespace scheduler { -ThrottledTimeDomain::ThrottledTimeDomain(const char* tracing_category) - : RealTimeDomain(tracing_category) {} +ThrottledTimeDomain::ThrottledTimeDomain() : RealTimeDomain() {} ThrottledTimeDomain::~ThrottledTimeDomain() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h index 53b4514..0cb0f87 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h
@@ -13,9 +13,9 @@ // A time domain for throttled tasks. behaves like an RealTimeDomain except it // relies on the owner (TaskQueueThrottler) to schedule wake-ups. -class BLINK_PLATFORM_EXPORT ThrottledTimeDomain : public RealTimeDomain { +class PLATFORM_EXPORT ThrottledTimeDomain : public RealTimeDomain { public: - ThrottledTimeDomain(const char* tracing_category); + ThrottledTimeDomain(); ~ThrottledTimeDomain() override; // TimeDomain implementation:
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/user_model.h b/third_party/WebKit/Source/platform/scheduler/renderer/user_model.h index c0b5d2e8..571460a 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/user_model.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/user_model.h
@@ -8,14 +8,14 @@ #include "base/macros.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/trace_event_argument.h" -#include "public/platform/scheduler/renderer/renderer_scheduler.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" #include "public/platform/WebInputEvent.h" +#include "public/platform/scheduler/renderer/renderer_scheduler.h" namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT UserModel { +class PLATFORM_EXPORT UserModel { public: UserModel(); ~UserModel();
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/web_frame_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/renderer/web_frame_scheduler_impl.h index 498b078..ae88331 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/web_frame_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/web_frame_scheduler_impl.h
@@ -11,9 +11,9 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/trace_event/trace_event.h" +#include "platform/PlatformExport.h" #include "platform/WebFrameScheduler.h" #include "platform/scheduler/base/task_queue.h" -#include "public/platform/WebCommon.h" namespace base { namespace trace_event {
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler.h b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler.h index 07cbe577..1736a66 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler.h
@@ -5,9 +5,9 @@ #ifndef THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_RENDERER_WEB_VIEW_SCHEDULER_H_ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_RENDERER_WEB_VIEW_SCHEDULER_H_ +#include "platform/PlatformExport.h" #include "platform/wtf/Functional.h" #include "public/platform/BlameContext.h" -#include "public/platform/WebCommon.h" #include <memory> @@ -15,10 +15,10 @@ class WebFrameScheduler; -class BLINK_PLATFORM_EXPORT WebViewScheduler { +class PLATFORM_EXPORT WebViewScheduler { public: // Helper interface to plumb settings from WebSettings to scheduler. - class BLINK_PLATFORM_EXPORT WebViewSchedulerSettings { + class PLATFORM_EXPORT WebViewSchedulerSettings { public: virtual ~WebViewSchedulerSettings() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl.h b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl.h index d869796..8a3a8ca 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl.h
@@ -10,12 +10,12 @@ #include <string> #include "base/macros.h" +#include "platform/PlatformExport.h" #include "platform/scheduler/base/task_queue.h" #include "platform/scheduler/child/web_scheduler.h" #include "platform/scheduler/child/web_task_runner_impl.h" #include "platform/scheduler/renderer/task_queue_throttler.h" #include "platform/scheduler/renderer/web_view_scheduler.h" -#include "public/platform/WebCommon.h" namespace base { namespace trace_event { @@ -31,7 +31,7 @@ class CPUTimeBudgetPool; class WebFrameSchedulerImpl; -class BLINK_PLATFORM_EXPORT WebViewSchedulerImpl : public WebViewScheduler { +class PLATFORM_EXPORT WebViewSchedulerImpl : public WebViewScheduler { public: WebViewSchedulerImpl( WebScheduler::InterventionReporter* intervention_reporter,
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h b/third_party/WebKit/Source/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h index 940f565..f9cf3f9f 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/webthread_impl_for_renderer_scheduler.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_RENDERER_WEBTHREAD_IMPL_FOR_RENDERER_SCHEDULER_H_ #define THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_RENDERER_WEBTHREAD_IMPL_FOR_RENDERER_SCHEDULER_H_ +#include "platform/PlatformExport.h" #include "platform/wtf/RefPtr.h" #include "public/platform/scheduler/child/webthread_base.h" @@ -18,8 +19,7 @@ class WebSchedulerImpl; class WebTaskRunnerImpl; -class BLINK_PLATFORM_EXPORT WebThreadImplForRendererScheduler - : public WebThreadBase { +class PLATFORM_EXPORT WebThreadImplForRendererScheduler : public WebThreadBase { public: explicit WebThreadImplForRendererScheduler(RendererSchedulerImpl* scheduler); ~WebThreadImplForRendererScheduler() override;
diff --git a/third_party/WebKit/Source/platform/scheduler/utility/webthread_impl_for_utility_thread.h b/third_party/WebKit/Source/platform/scheduler/utility/webthread_impl_for_utility_thread.h index 3fdb2e9..e5b915b 100644 --- a/third_party/WebKit/Source/platform/scheduler/utility/webthread_impl_for_utility_thread.h +++ b/third_party/WebKit/Source/platform/scheduler/utility/webthread_impl_for_utility_thread.h
@@ -7,13 +7,13 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "public/platform/WebCommon.h" +#include "platform/PlatformExport.h" #include "public/platform/scheduler/child/webthread_base.h" namespace blink { namespace scheduler { -class BLINK_PLATFORM_EXPORT WebThreadImplForUtilityThread +class PLATFORM_EXPORT WebThreadImplForUtilityThread : public scheduler::WebThreadBase { public: WebThreadImplForUtilityThread();
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp index 78c7c188..389f34cb 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp +++ b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp
@@ -435,7 +435,7 @@ // heuristic. double hue, saturation, lightness; background_color.GetHSL(hue, saturation, lightness); - if (lightness <= .5) + if (lightness <= .5 && background_color.Alpha()) overlay_theme = kScrollbarOverlayColorThemeLight; if (old_overlay_theme != overlay_theme)
diff --git a/third_party/WebKit/Source/web/tests/ScrollbarsTest.cpp b/third_party/WebKit/Source/web/tests/ScrollbarsTest.cpp index 6b8aef9a..0840b47 100644 --- a/third_party/WebKit/Source/web/tests/ScrollbarsTest.cpp +++ b/third_party/WebKit/Source/web/tests/ScrollbarsTest.cpp
@@ -105,6 +105,35 @@ ASSERT_FALSE(layout_viewport->HorizontalScrollbar()); } +TEST_F(ScrollbarsTest, TransparentBackgroundUsesDarkOverlayColorTheme) { + // The bug reproduces only with RLS off. When RLS ships we can keep the test + // but remove this setting. + ScopedRootLayerScrollingForTest turn_off_root_layer_scrolling(false); + + // This test is specifically checking the behavior when overlay scrollbars + // are enabled. + DCHECK(ScrollbarTheme::GetTheme().UsesOverlayScrollbars()); + + WebView().Resize(WebSize(800, 600)); + WebView().SetBaseBackgroundColorOverride(SK_ColorTRANSPARENT); + SimRequest request("https://example.com/test.html", "text/html"); + LoadURL("https://example.com/test.html"); + request.Complete( + "<!DOCTYPE html>" + "<style>" + " body{" + " height: 300%;" + " }" + "</style>"); + Compositor().BeginFrame(); + + ScrollableArea* layout_viewport = + GetDocument().View()->LayoutViewportScrollableArea(); + + EXPECT_EQ(kScrollbarOverlayColorThemeDark, + layout_viewport->GetScrollbarOverlayColorTheme()); +} + typedef bool TestParamOverlayScrollbar; class ScrollbarAppearanceTest : public SimTest,
diff --git a/third_party/WebKit/public/platform/scheduler/child/single_thread_idle_task_runner.h b/third_party/WebKit/public/platform/scheduler/child/single_thread_idle_task_runner.h index b6cdfc76..8fd8ab1 100644 --- a/third_party/WebKit/public/platform/scheduler/child/single_thread_idle_task_runner.h +++ b/third_party/WebKit/public/platform/scheduler/child/single_thread_idle_task_runner.h
@@ -64,8 +64,7 @@ // literals). They may not include " chars. SingleThreadIdleTaskRunner( scoped_refptr<base::SingleThreadTaskRunner> idle_priority_task_runner, - Delegate* delegate, - const char* tracing_category); + Delegate* delegate); virtual void PostIdleTask(const tracked_objects::Location& from_here, const IdleTask& idle_task); @@ -102,7 +101,6 @@ scoped_refptr<base::SingleThreadTaskRunner> idle_priority_task_runner_; std::multimap<base::TimeTicks, DelayedIdleTask> delayed_idle_tasks_; Delegate* delegate_; // NOT OWNED - const char* tracing_category_; base::trace_event::BlameContext* blame_context_; // Not owned. base::WeakPtr<SingleThreadIdleTaskRunner> weak_scheduler_ptr_; base::WeakPtrFactory<SingleThreadIdleTaskRunner> weak_factory_;
diff --git a/tools/ipc_fuzzer/fuzzer/fuzzer.cc b/tools/ipc_fuzzer/fuzzer/fuzzer.cc index a913dc23..159ee81f 100644 --- a/tools/ipc_fuzzer/fuzzer/fuzzer.cc +++ b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
@@ -10,6 +10,7 @@ #include <vector> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/shared_memory_handle.h" #include "base/strings/string_util.h" #include "base/values.h" @@ -510,28 +511,28 @@ bool tmp; p->GetBoolean(index, &tmp); fuzzer->FuzzBool(&tmp); - p->Set(index, new base::Value(tmp)); + p->Set(index, base::MakeUnique<base::Value>(tmp)); break; } case base::Value::Type::INTEGER: { int tmp; p->GetInteger(index, &tmp); fuzzer->FuzzInt(&tmp); - p->Set(index, new base::Value(tmp)); + p->Set(index, base::MakeUnique<base::Value>(tmp)); break; } case base::Value::Type::DOUBLE: { double tmp; p->GetDouble(index, &tmp); fuzzer->FuzzDouble(&tmp); - p->Set(index, new base::Value(tmp)); + p->Set(index, base::MakeUnique<base::Value>(tmp)); break; } case base::Value::Type::STRING: { std::string tmp; p->GetString(index, &tmp); fuzzer->FuzzString(&tmp); - p->Set(index, new base::Value(tmp)); + p->Set(index, base::MakeUnique<base::Value>(tmp)); break; } case base::Value::Type::BINARY: { @@ -542,17 +543,25 @@ break; } case base::Value::Type::DICTIONARY: { - base::DictionaryValue* tmp = new base::DictionaryValue(); - p->GetDictionary(index, &tmp); - FuzzParam(tmp, fuzzer); - p->Set(index, tmp); + base::DictionaryValue* dict_weak = nullptr; + if (p->GetDictionary(index, &dict_weak)) { + FuzzParam(dict_weak, fuzzer); + } else { + auto dict = base::MakeUnique<base::DictionaryValue>(); + FuzzParam(dict.get(), fuzzer); + p->Set(index, std::move(dict)); + } break; } case base::Value::Type::LIST: { - base::ListValue* tmp = new base::ListValue(); - p->GetList(index, &tmp); - FuzzParam(tmp, fuzzer); - p->Set(index, tmp); + base::ListValue* list_weak = nullptr; + if (p->GetList(index, &list_weak)) { + FuzzParam(list_weak, fuzzer); + } else { + auto list = base::MakeUnique<base::ListValue>(); + FuzzParam(list.get(), fuzzer); + p->Set(index, std::move(list)); + } break; } case base::Value::Type::NONE:
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index b76c0f6..d476b29 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -44466,6 +44466,18 @@ </summary> </histogram> +<histogram + name="OfflinePages.Background.EffectiveConnectionType.OffliningStartType" + enum="NQEEffectiveConnectionType"> + <owner>petewil@chromium.org</owner> + <summary> + Effective connection type at the start of an offlining attempt for an + attempt that eventually failed. + + This metric is recorded for RequestCoordinator::SavePageLater API calls. + </summary> +</histogram> + <histogram name="OfflinePages.Background.EffectiveConnectionType.PauseRequests" enum="NQEEffectiveConnectionType"> <owner>dougarnett@chromium.org</owner> @@ -103253,7 +103265,6 @@ <int value="-1634154256" label="ZeroSuggestRedirectToChrome:enabled"/> <int value="-1631329950" label="ssl-version-max"/> <int value="-1630419335" label="enable-download-notification"/> - <int value="-1629748710" label="ash-enable-smooth-screen-rotation"/> <int value="-1624854957" label="enable-es3-apis"/> <int value="-1620568042" label="FeaturePolicy:disabled"/> <int value="-1619757314" label="touch-scrolling-mode"/> @@ -103978,6 +103989,7 @@ <int value="1222017136" label="WebRtcUseEchoCanceller3:disabled"/> <int value="1235800887" label="V8Ignition:enabled"/> <int value="1237297772" label="no-pings"/> + <int value="1240073971" label="ash-disable-smooth-screen-rotation"/> <int value="1242632259" label="ContentSuggestionsCategoryOrder:disabled"/> <int value="1245889469" label="enable-surface-worker"/> <int value="1247293682" label="topchrome-md"/> @@ -111568,6 +111580,8 @@ <int value="3" label="Parse Failed"/> <int value="4" label="Validation Failed"/> <int value="5" label="Incompatible"/> + <int value="6" label="Load from Cache Failed"/> + <int value="7" label="Model Loading Abandoned"/> </enum> <enum name="RapporDiscardReason" type="int"> @@ -124326,6 +124340,8 @@ <suffix name="download" label="Offline downloaded pages"/> <suffix name="ntp_suggestions" label="Offline ntp suggestions"/> <affected-histogram + name="OfflinePages.Background.EffectiveConnectionType.OffliningStartType"/> + <affected-histogram name="OfflinePages.Background.EffectiveConnectionType.SavePageLater"/> <affected-histogram name="OfflinePages.Background.FinalSavePageResult"/> <affected-histogram name="OfflinePages.Background.OfflinerRequestStatus"/>
diff --git a/tools/perf/benchmark.csv b/tools/perf/benchmark.csv index aab457f..8ee02ec 100644 --- a/tools/perf/benchmark.csv +++ b/tools/perf/benchmark.csv
@@ -16,7 +16,6 @@ blink_perf.pywebsocket,"tyoshino@chromium.org, yhirano@chromium.org", blink_perf.shadow_dom,hayato@chromium.org, blink_perf.svg,"kouhei@chromium.org, fs@opera.com", -blink_perf.xml_http_request,"tyoshino@chromium.org, hiroshige@chromium.org", blink_style.key_mobile_sites,, blink_style.polymer,, blink_style.top_25,,
diff --git a/tools/perf/benchmarks/blink_perf.py b/tools/perf/benchmarks/blink_perf.py index fc2b6f8..64a55a45 100644 --- a/tools/perf/benchmarks/blink_perf.py +++ b/tools/perf/benchmarks/blink_perf.py
@@ -298,13 +298,6 @@ return possible_browser.platform.GetDeviceTypeName() == 'Nexus 5X' -# This benchmark is for local testing, doesn't need to run on bots. -@benchmark.Disabled('all') -@benchmark.Owner(emails=['tyoshino@chromium.org', 'hiroshige@chromium.org']) -class BlinkPerfXMLHttpRequest(_BlinkPerfBenchmark): - tag = 'xml_http_request' - subdir = 'XMLHttpRequest' - # Disabled on Windows and ChromeOS due to https://crbug.com/521887 #@benchmark.Disabled('win', 'chromeos')
diff --git a/tools/perf/benchmarks/rasterize_and_record_micro.py b/tools/perf/benchmarks/rasterize_and_record_micro.py index caf9bd5..5c4bf6c0 100644 --- a/tools/perf/benchmarks/rasterize_and_record_micro.py +++ b/tools/perf/benchmarks/rasterize_and_record_micro.py
@@ -87,7 +87,7 @@ return page_sets.KeySilkCasesPageSet(run_no_page_interactions=True) -@benchmark.Enabled('android') +@benchmark.Disabled('all') # http://crbug.com/709561 class RasterizeAndRecordMicroPolymer(_RasterizeAndRecordMicro): """Measures rasterize and record performance on the Polymer cases.
diff --git a/tools/perf/benchmarks/smoothness.py b/tools/perf/benchmarks/smoothness.py index 733eb12..b90a4f5 100644 --- a/tools/perf/benchmarks/smoothness.py +++ b/tools/perf/benchmarks/smoothness.py
@@ -99,6 +99,7 @@ @benchmark.Disabled('android') # crbug.com/526901 +@benchmark.Disabled('linux') # crbug.com/715607 @benchmark.Owner(emails=['junov@chromium.org']) class SmoothnessToughCanvasCases(_Smoothness): """Measures frame rate and a variety of other statistics.
diff --git a/tools/perf/contrib/__init__.py b/tools/perf/contrib/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tools/perf/contrib/__init__.py
diff --git a/tools/perf/contrib/blink_perf_xml_http_request/OWNERS b/tools/perf/contrib/blink_perf_xml_http_request/OWNERS new file mode 100644 index 0000000..3bcd079 --- /dev/null +++ b/tools/perf/contrib/blink_perf_xml_http_request/OWNERS
@@ -0,0 +1,2 @@ +tyoshino@chromium.org +hiroshige@chromium.org
diff --git a/tools/perf/contrib/blink_perf_xml_http_request/__init__.py b/tools/perf/contrib/blink_perf_xml_http_request/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tools/perf/contrib/blink_perf_xml_http_request/__init__.py
diff --git a/tools/perf/contrib/blink_perf_xml_http_request/blink_perf_xml_http_request.py b/tools/perf/contrib/blink_perf_xml_http_request/blink_perf_xml_http_request.py new file mode 100644 index 0000000..f70c69f --- /dev/null +++ b/tools/perf/contrib/blink_perf_xml_http_request/blink_perf_xml_http_request.py
@@ -0,0 +1,9 @@ +# Copyright 2013 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. +from benchmarks import blink_perf + +# pylint: disable=protected-access +class BlinkPerfXMLHttpRequest(blink_perf._BlinkPerfBenchmark): + tag = 'xml_http_request' + subdir = 'XMLHttpRequest'
diff --git a/tools/perf/core/benchmark_finders.py b/tools/perf/core/benchmark_finders.py index 6705b16..4cb79e6 100644 --- a/tools/perf/core/benchmark_finders.py +++ b/tools/perf/core/benchmark_finders.py
@@ -44,8 +44,16 @@ def GetAllPerfBenchmarks(): - benchmarks_dir = path_util.GetPerfBenchmarksDir() - top_level_dir = os.path.join(benchmarks_dir, '..') return discover.DiscoverClasses( - benchmarks_dir, top_level_dir, benchmark_module.Benchmark, + start_dir=path_util.GetPerfBenchmarksDir(), + top_level_dir=path_util.GetPerfDir(), + base_class=benchmark_module.Benchmark, + index_by_class_name=True).values() + + +def GetAllContribBenchmarks(): + return discover.DiscoverClasses( + start_dir=path_util.GetPerfContribDir(), + top_level_dir=path_util.GetPerfDir(), + base_class=benchmark_module.Benchmark, index_by_class_name=True).values()
diff --git a/tools/perf/core/path_util.py b/tools/perf/core/path_util.py index dcfcd08..44bfdd4 100644 --- a/tools/perf/core/path_util.py +++ b/tools/perf/core/path_util.py
@@ -28,6 +28,10 @@ return os.path.join(GetPerfDir(), 'benchmarks') +def GetPerfContribDir(): + return os.path.join(GetPerfDir(), 'contrib') + + def AddTelemetryToPath(): telemetry_path = GetTelemetryDir() if telemetry_path not in sys.path:
diff --git a/tools/perf/core/trybot_command.py b/tools/perf/core/trybot_command.py index ddd9e21..de5a5b4 100644 --- a/tools/perf/core/trybot_command.py +++ b/tools/perf/core/trybot_command.py
@@ -16,11 +16,11 @@ import urllib2 +from core import benchmark_finders from core import path_util from telemetry import benchmark from telemetry import decorators -from telemetry.core import discover from telemetry.util import command_line from telemetry.util import matching @@ -271,10 +271,8 @@ for arg in extra_args: if arg == '--browser' or arg.startswith('--browser='): parser.error('--browser=... is not allowed when running trybot.') - all_benchmarks = discover.DiscoverClasses( - start_dir=path_util.GetPerfBenchmarksDir(), - top_level_dir=path_util.GetPerfDir(), - base_class=benchmark.Benchmark).values() + all_benchmarks = benchmark_finders.GetAllPerfBenchmarks() + all_benchmarks.extend(benchmark_finders.GetAllContribBenchmarks()) all_benchmark_names = [b.Name() for b in all_benchmarks] all_benchmarks_by_names = {b.Name(): b for b in all_benchmarks} benchmark_class = all_benchmarks_by_names.get(options.benchmark_name, None)
diff --git a/tools/perf/run_benchmark b/tools/perf/run_benchmark index 00fb6af..9329184 100755 --- a/tools/perf/run_benchmark +++ b/tools/perf/run_benchmark
@@ -16,7 +16,8 @@ def main(): config = chromium_config.ChromiumConfig( - benchmark_dirs=[path_util.GetPerfBenchmarksDir()], + benchmark_dirs=[path_util.GetPerfBenchmarksDir(), + path_util.GetPerfContribDir()], top_level_dir=path_util.GetPerfDir()) return benchmark_runner.main(config, [trybot_command.Trybot])
diff --git a/ui/base/clipboard/clipboard_win.cc b/ui/base/clipboard/clipboard_win.cc index c135e35..c18c6a5 100644 --- a/ui/base/clipboard/clipboard_win.cc +++ b/ui/base/clipboard/clipboard_win.cc
@@ -568,8 +568,10 @@ offsets.push_back(end_index - html_start); markup->assign(base::UTF8ToUTF16AndAdjustOffsets(cf_html.data() + html_start, &offsets)); - *fragment_start = base::checked_cast<uint32_t>(offsets[0]); - *fragment_end = base::checked_cast<uint32_t>(offsets[1]); + // Ensure the Fragment points within the string; see https://crbug.com/607181. + size_t end = std::min(offsets[1], markup->length()); + *fragment_start = base::checked_cast<uint32_t>(std::min(offsets[0], end)); + *fragment_end = base::checked_cast<uint32_t>(end); } void ClipboardWin::ReadRTF(ClipboardType type, std::string* result) const {
diff --git a/ui/message_center/views/desktop_popup_alignment_delegate.cc b/ui/message_center/views/desktop_popup_alignment_delegate.cc index d6e7ff8f..f57d23ad 100644 --- a/ui/message_center/views/desktop_popup_alignment_delegate.cc +++ b/ui/message_center/views/desktop_popup_alignment_delegate.cc
@@ -89,6 +89,10 @@ // Do nothing, which will use the default container. } +bool DesktopPopupAlignmentDelegate::IsPrimaryDisplayForNotification() const { + return true; +} + // Anytime the display configuration changes, we need to recompute the alignment // on the primary display. But, we get different events on different platforms. // On Windows, for example, when switching from a laptop display to an external
diff --git a/ui/message_center/views/desktop_popup_alignment_delegate.h b/ui/message_center/views/desktop_popup_alignment_delegate.h index 687b9f7..93c05fc 100644 --- a/ui/message_center/views/desktop_popup_alignment_delegate.h +++ b/ui/message_center/views/desktop_popup_alignment_delegate.h
@@ -41,6 +41,7 @@ void ConfigureWidgetInitParamsForContainer( views::Widget* widget, views::Widget::InitParams* init_params) override; + bool IsPrimaryDisplayForNotification() const override; private: friend class test::MessagePopupCollectionTest;
diff --git a/ui/message_center/views/message_popup_collection.cc b/ui/message_center/views/message_popup_collection.cc index 0a2afc4..396721d 100644 --- a/ui/message_center/views/message_popup_collection.cc +++ b/ui/message_center/views/message_popup_collection.cc
@@ -173,6 +173,10 @@ bool top_down = alignment_delegate_->IsTopDown(); int base = GetBaseLine(toasts_.empty() ? NULL : toasts_.back()); +#if defined(OS_CHROMEOS) + bool is_primary_display = + alignment_delegate_->IsPrimaryDisplayForNotification(); +#endif // Iterate in the reverse order to keep the oldest toasts on screen. Newer // items may be ignored if there are no room to place them. @@ -181,6 +185,16 @@ if (FindToast((*iter)->id())) continue; +#if defined(OS_CHROMEOS) + // Disables popup of custom notification on non-primary displays, since + // currently custom notification supports only on one display at the same + // time. + // TODO(yoshiki): Support custom popup notification on multiple display + // (crbug.com/715370). + if (!is_primary_display && (*iter)->type() == NOTIFICATION_TYPE_CUSTOM) + continue; +#endif + MessageView* view; // Create top-level notification. #if defined(OS_CHROMEOS)
diff --git a/ui/message_center/views/popup_alignment_delegate.h b/ui/message_center/views/popup_alignment_delegate.h index 6be86cb..48787456 100644 --- a/ui/message_center/views/popup_alignment_delegate.h +++ b/ui/message_center/views/popup_alignment_delegate.h
@@ -56,6 +56,10 @@ views::Widget* widget, views::Widget::InitParams* init_params) = 0; + // Returns true if the display which notifications show on is the primary + // display. + virtual bool IsPrimaryDisplayForNotification() const = 0; + protected: virtual ~PopupAlignmentDelegate();
diff --git a/ui/views/bubble/tray_bubble_view.cc b/ui/views/bubble/tray_bubble_view.cc index 3d7a93e..70da63a0 100644 --- a/ui/views/bubble/tray_bubble_view.cc +++ b/ui/views/bubble/tray_bubble_view.cc
@@ -49,6 +49,10 @@ return BubbleBorder::RIGHT_BOTTOM; } +// Only one TrayBubbleView is visible at a time, but there are cases where the +// lifetimes of two different bubbles can overlap briefly. +int g_current_tray_bubble_showing_count_ = 0; + } // namespace namespace internal { @@ -225,6 +229,11 @@ delegate_->BubbleViewDestroyed(); } +// static +bool TrayBubbleView::IsATrayBubbleOpen() { + return g_current_tray_bubble_showing_count_ > 0; +} + void TrayBubbleView::InitializeAndShowBubble() { layer()->parent()->SetMaskLayer(bubble_content_mask_->layer()); @@ -232,6 +241,8 @@ GetWidget()->GetNativeWindow()->SetEventTargeter( std::unique_ptr<ui::EventTargeter>(new BubbleWindowTargeter(this))); UpdateBubble(); + + ++g_current_tray_bubble_showing_count_; } void TrayBubbleView::UpdateBubble() { @@ -278,6 +289,12 @@ params->shadow_elevation = wm::ShadowElevation::LARGE; } +void TrayBubbleView::OnWidgetClosing(Widget* widget) { + BubbleDialogDelegateView::OnWidgetClosing(widget); + --g_current_tray_bubble_showing_count_; + DCHECK_GE(g_current_tray_bubble_showing_count_, 0); +} + NonClientFrameView* TrayBubbleView::CreateNonClientFrameView(Widget* widget) { BubbleFrameView* frame = static_cast<BubbleFrameView*>( BubbleDialogDelegateView::CreateNonClientFrameView(widget));
diff --git a/ui/views/bubble/tray_bubble_view.h b/ui/views/bubble/tray_bubble_view.h index 8de9c30..ce396c9 100644 --- a/ui/views/bubble/tray_bubble_view.h +++ b/ui/views/bubble/tray_bubble_view.h
@@ -28,8 +28,8 @@ // Ash status area). Mostly this handles custom anchor location and arrow and // border rendering. This also has its own delegate for handling mouse events // and other implementation specific details. -class VIEWS_EXPORT TrayBubbleView : public views::BubbleDialogDelegateView, - public views::MouseWatcherListener { +class VIEWS_EXPORT TrayBubbleView : public BubbleDialogDelegateView, + public MouseWatcherListener { public: // AnchorAlignment determines to which side of the anchor the bubble will // align itself. @@ -93,6 +93,9 @@ ~TrayBubbleView() override; + // Returns whether a tray bubble is active. + static bool IsATrayBubbleOpen(); + // Sets up animations, and show the bubble. Must occur after CreateBubble() // is called. void InitializeAndShowBubble(); @@ -130,6 +133,7 @@ // Overridden from views::BubbleDialogDelegateView. void OnBeforeBubbleWidgetInit(Widget::InitParams* params, Widget* bubble_widget) const override; + void OnWidgetClosing(Widget* widget) override; // Overridden from views::View. gfx::Size GetPreferredSize() const override;